Counting string to plot a graph using chart.js and angular - javascript

I am trying to create a bar chart in angular using chart.js and angular.
I want to display the disaters vs area. with the type of disaster ( earthquake, hurricane, storm...etc) on the x-axis and area (as in location) on the y-axis.
However, the area data is string and does not work when trying to plot a bar graph as it requires numbers.
I am reading the data as follows:
ngOnInit(): void {
this.chartService.noOfEqu().subscribe((res) => {
let area = res.map((res) => res.area);
let disaster = res.map((res) => res.disasterNature);
new Chart('disasterCanvas', {
type: 'bar',
data: {
labels: disaster,
datasets: [
{
data: area,
label: 'area',
backgroundColor: '#A121D5',
},
],
},
options: {
plugins: {
legend: {
display: true,
},
},
scales: {
x: {
ticks: {
display: true,
},
},
y: {
ticks: {
display: true,
},
},
},
},
});
});
}
}
Where let area = res.map((res) => res.area); is the area variable.
I want to know what is the best way to structure the data to be entered into the graph.
The disaster data that is logged is:
and the area data :
How can i structure the area such that it counts how much areas that a disaster has occured and plot it on the bar chart?
Thank you in advance...if there is anything i can clarify please let me know in the comments
Also is there another way to display this data besides tallying the string data?

You need to add a labels array to the scale and set the type to category to use string data:
const options = {
type: 'bar',
data: {
labels: ["Earthquake", "Tornade", "Flood"],
datasets: [{
label: '# of Votes',
data: ['Paris', 'Berlin', 'London'],
backgroundColor: 'pink'
}]
},
options: {
scales: {
y: {
type: 'category',
reverse: true,
labels: ['', 'London', 'Paris', 'Berlin']
}
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
</body>

Related

Chart.js Treemap Custom text

In my code below, I am able to draw a Treemap and also display the tag in each tree cell. But I want to add some custom text next to my tag,
Like say I want the word 'Language' to appear in each tree map cell. I tried the formatter options, But its not working for the version of chart.js I am using. Kindly provide me a solution for the specific version I am using. Since I have multiple other charts defined and changing the version would cause issues.
var topTags = [
{tag:'android',num:42657},{tag:'reactjs',num:38844},{tag:'php',num:34381},{tag:'sql',num:29996},
];
var canvas = document.getElementById("treemap");
var ctx = canvas.getContext("2d");
var chart = window.chart = new Chart(ctx, {
type: "treemap",
data: {
datasets: [{
tree: topTags,
key: "num",
groups: ['tag'],
spacing: 0.5,
borderWidth: 1.5,
fontColor: "black",
borderColor: "grey"
}]
},
options: {
maintainAspectRatio: false,
legend: { display: false },
tooltips: { enabled: false }
}
});
CHART.JS AND TREEMAP VERSION :
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-chart-treemap#0.2.3"></script>
The formatter option only got added in version 2 of the treemap chart type, the scriptable option is only available in version 1 so the best way for you to get the extra text is by editing your original data array first and adding the text to it that way like so:
let topTags = [{
tag: 'android',
num: 42657
}, {
tag: 'reactjs',
num: 38844
}, {
tag: 'php',
num: 34381
}, {
tag: 'sql',
num: 29996
}, ];
topTags = topTags.map(e => ({
num: e.num,
tag: `Lang: ${e.tag}`
}))
const canvas = document.getElementById("chart");
const ctx = canvas.getContext("2d");
const chart = window.chart = new Chart(ctx, {
type: "treemap",
data: {
datasets: [{
tree: topTags,
key: "num",
groups: ['tag'],
spacing: 0.5,
borderWidth: 1.5,
fontColor: "black",
borderColor: "grey",
}]
},
options: {
maintainAspectRatio: false,
legend: {
display: false
},
tooltips: {
enabled: false
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-chart-treemap#0.2.3"></script>
<canvas id="chart"></canvas>

chart.js - how to draw and manage line when only one label present in chart js Linechart

I'm using Chart.JS v 2.9.3 to create a line chart
line-chart diagram to show the month-wise total of expenses of selected product
For example, if the user select XYZ product then this charts would show the monthly expenses [Jan-2021-Dec-2021]
and if that respective product expense only present Jan-2021 then it displays month on y-Axes at staring
here is jsfiddle example
Adding offset trick I had already tried xAxes : [{ offset:true }],
var config = {
type: 'line',
data: {
labels: ["jan-2021"],
datasets: [{
label: "month-year",
data: [65],
backgroundColor: "rgb(118, 101, 228)",
}],
},
scales : {
xAxes : [{
offset:true
}],
},
};
var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);
<div class="myChart">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<canvas id="myChart"></canvas>
</div>
please refer to the above image for getting an idea of what I'm trying to archive, I'm not concern about dot that on the chart
As you can see, the points are stick to the y-axis. Is there a possibility to center the line chart when only one data is present in the diagram?
Chart.js does not support this kind of use case since it gives a distorted image of your chart since point and label don't align anymore. If you really want this you can check beforehand in your code if there is only 1 data point there. If this is the case add an empty string in your labels array in the front and back and add zero at the front of back of your data array (or a slightly lower value as your single datapoint so that the scales don't get big steps) like so:
var config = {
type: 'line',
data: {
labels: ["", "January-2021", ""],
datasets: [{
label: "month-year",
data: [0, 134335066, 0],
backgroundColor: "rgb(118, 101, 228)",
}],
},
scales: {},
};
var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);
<div class="myChart">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.js"></script>
<canvas id="myChart"></canvas>
</div>
You can use align option:
var mybarChart = new Chart(ctx, {
type: 'bar',
responsive: true,
data: data,
options: {
legend: {
display: false,
position: 'bottom',
align: 'center'
},
var config = {
type: 'line',
data: {
labels: ["", "January-2021", ""],
datasets: [{
label: "month-year",
data: [0, 134335066, 0],
backgroundColor: "rgb(118, 101, 228)",
}],
options: {
legend: {
display: false,
position: 'bottom',
align: 'center'
},
},
scales: {},
};
refer to this

ChartJS: Horizontal Bar with multiple datasets not showing Bars

I have Horizontal Bar comparing Rooms & Guests target vs achieved.
Rooms has 3 data values (Available, Budget, Actual) and Guests has only 2 (Budget, Actual).
Below is the code generates the chart:
data = [{
label: 'Available',
backgroundColor: '#3366ff',
data: [5580]
}, {
label: 'Budget',
backgroundColor: '#009999',
data: [5000, 6500]
}, {
label: 'Actual',
backgroundColor: '#92d400',
data: [5200, 7245]
}];
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ["Rooms", "Guests"],
datasets: data
}
}
Issue with the above code is, Rooms Budget bar is not showing up.
It shows only when I add [5580,0] to the Guests Available data value; however there is no such Data for Guests like Rooms.
Here is the JSFiddle (https://jsfiddle.net/kingBethal/vtf17k84/8/).
5000 is the lowest value in your dataset and Chart.js is creating its scale starting at 5000:
Set the beginAtZero property to true and you'll see the expected bar:
let data = [{
label: 'Available',
backgroundColor: '#3366ff',
data: [5580]
}, {
label: 'Budget',
backgroundColor: '#009999',
data: [5000, 6500]
}, {
label: 'Actual',
backgroundColor: '#92d400',
data: [5200, 7245]
}];
let myChart = new Chart(document.getElementById('chart'), {
type: 'horizontalBar',
data: {
labels: ["Rooms", "Guests"],
datasets: data
},
options: {
scales: {
xAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="chart"></canvas>

Pushing data from json to Chart.js labels and data

I am using the Chart.js lib to make charts.
I have a json array that I am getting from a database.
Here is the console log of it: Data
I need to get the address, speed, and speed limit for every element in the list and use it in a chart.
My current code is as follows:
function ShowChart() {
var popCanvas = document.getElementById("speedLimitsChart");
console.dir(speeddata);
var labels = speeddata.map(function (e) {
return e.Adress;
});
var speed = speeddata.map(function (e) {
return e.Speed;
});
var speedlimits = speeddata.map(function (e) {
return e.SpeedLimits;
});
console.dir(labels);
var barChart = new Chart(popCanvas, {
type: 'bar',
data: {
datasets: [{
label: 'Speed',
data: speed,
backgroundColor: '#1E90FF'
}, {
label: 'Speed Limits',
data: speedlimits,
backgroundColor: '#B22222',
type: 'line'
}],
},
labels: labels
});
}
But in the result I only have the first element in my chart, and there are no labels.
Here is the output screen: Chart
I checked speed, speedlimits and labels and all of them have 2 elements. Can you please advise where my problem might be?
I found where is my problem
I need to write labels inside of data
Like this
var barChart = new Chart(popCanvas, {
type: 'bar',
data: {
labels: labels ,
datasets: [{
label: 'Speed',
data: speed,
backgroundColor: '#1E90FF'
}, {
label: 'Speed Limits',
data: speedlimits,
backgroundColor: '#B22222',
type: 'line'
}],
},
});

How to show bar labels in legend in Chart.js 2.1.6?

I'm creating charts using Chart.js and I want to show the labels for the bars in the legend, not the title of the dataset (there is only one), please see the below image as an example:
My current legend just looks like this:
I have looked through the docs but to no avail, I found them very confusing actually.
Here is my current code:
var chart_0 = new Chart($('#cp_chart_0'), {
type: 'bar'
, data: {
labels: ['Blue','Green','Yellow','Red','Purple','Orange']
, datasets: [{
label: 'Dataset 1'
, borderWidth: 0
, backgroundColor: ['#2C79C5','#7FA830','#7B57C3','#ED4D40','#EC802F','#1DC6D3']
, data: ['12','2','5','0','9','1']
}]
}
});
Thanks!
In one of the most recent releases of Chart.js 2.1.x, they added back this functionality. So go get the latest release first. Then insert the code below.
It is located under the options and legend. Here is how you use it:
options: {
legend: {
position: 'right'
}
}
Easiest way is to provide your data with multiple sets :
data: {
labels: ['total votes']
, datasets: [{
label: 'Blue'
, backgroundColor: ['#2C79C5']
, data: ['12']
},{
label: 'Green'
, backgroundColor: ['#7FA830']
, data: ['2']
},
...
]
}
But you can generate a custom labels using generateLabels - http://www.chartjs.org/docs/#chart-configuration-legend-configuration
Or even customise the whole legend, including formatting, with legendCallback - http://www.chartjs.org/docs/#chart-configuration-common-chart-configuration
This solution uses Chart.js version 3. You can pre-process your data using the Plugin Core API. The API offers different hooks that may be used for executing custom code.
I use the beforeInit hook to create individual datasets for each defined label/value pair. Note that the data of these new datasets are defined in point format (for instance [{ x: 1, y: 12 }]):
beforeInit: chart => {
let dataset = chart.config.data.datasets[0];
chart.config.data.datasets = chart.config.data.labels.map((l, i) => ({
label: l,
data: [{ x: i + 1, y: dataset.data[i] }],
backgroundColor: dataset.backgroundColor[i],
categoryPercentage: 1
}));
chart.config.data.labels = undefined;
}
Further you need to define a second x-axis that will contain the labels.
x1: {
offset: true,
gridLines: {
display: false
}
}
The labels on x1 need to be collected and defined programmatically each time the hidden state of a dataset changes. This can be done in the beforeLayout hook.
beforeLayout: chart => chart.options.scales.x1.labels = chart.config.data.datasets.filter((ds, i) => !chart.getDatasetMeta(i).hidden).map(ds => ds.label)
Please take a look at below runnable code and see how it works.
new Chart('chart', {
type: 'bar',
plugins: [{
beforeInit: chart => {
let dataset = chart.config.data.datasets[0];
chart.config.data.datasets = chart.config.data.labels.map((l, i) => ({
label: l,
data: [{ x: i + 1, y: dataset.data[i] }],
backgroundColor: dataset.backgroundColor[i],
categoryPercentage: 1
}));
chart.config.data.labels = undefined;
},
beforeLayout: chart => chart.options.scales.x1.labels = chart.config.data.datasets.filter((ds, i) => !chart.getDatasetMeta(i).hidden).map(ds => ds.label)
}],
data: {
labels: ['Blue', 'Green', 'Yellow', 'Red', 'Purple', 'Orange'],
datasets: [{
data: ['12', '2', '5', '0', '9', '1'],
backgroundColor: ['#2C79C5', '#7FA830', '#FFF200', '#ED4D40', '#800080', '#EC802F']
}]
},
options: {
interaction: {
intersect: true,
mode: 'nearest'
},
plugins: {
legend: {
position: 'right'
},
tooltip: {
callbacks: {
title: () => undefined
}
}
},
scales: {
y: {
beginAtZero: true
},
x: {
display: false
},
x1: {
offset: true,
gridLines: {
display: false
}
}
}
}
});
canvas {
max-width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.2.0/chart.min.js"></script>
<canvas id="chart" height="120"></canvas>

Categories

Resources