problem with multiple datasets in chart.js - chart.js

I'm trying to use chart.js to create a bar chart that shows the number of ad impressions in an ad buy by publication. The desired chart would show a bar for each publication representing the number of impressions for the ad on that website.
I thought that this needs to happen as multiple datasets, one for each publication, where each dataset contains one data point. Here's the code I'm using for this approach:
var chartData_webbanner_300x600 = {
labels: ["Publication 1", "Publication 2"],
datasets: [
{
label: "Publication 1",
backgroundColor: "#971317",
data: [30000]
},
{
label: "Publication 2",
backgroundColor: "#0b72ba",
data: [40000]
},
]
};
window.onload = function() {
var ctx_webbanner_300x600 = document.getElementById('chart_webbanner_300x600').getContext('2d');
window.myBar = new Chart(ctx_webbanner_300x600, {
type: 'bar',
data: chartData_webbanner_300x600,
options: {
title: {
display: true,
text: 'Web Banner Impressions'
},
responsive: true,
}
});
}; //window.onload = function()
The resulting chart only shows one bar. Here's a screenshot:
I also tried this as a single dataset, but had no luck there. This is the approach I tried with that:
var chartData_webbanner_300x600 = {
labels: ["Total Impressions"],
datasets: [
{
label: ["Publication 1", "Publication 2"],
backgroundColor: ["#971317","#0b72ba"],
data: [30000,40000]
}
]
};
window.onload = function() {
var ctx_webbanner_300x600 = document.getElementById('chart_webbanner_300x600').getContext('2d');
window.myBar = new Chart(ctx_webbanner_300x600, {
type: 'bar',
data: chartData_webbanner_300x600,
options: {
title: {
display: true,
text: 'Web Banner Impressions'
},
responsive: true,
}
});
}; //window.onload = function()
Here's how that is displaying (with no bars):
Please let me know if you have any ideas on what I'm doing wrong. Thank you for taking the time to help!

I was able to get it working with this code:
var graphData = {
labels: ['Publication 1', 'Publication 2'],
datasets: [{
label: 'Impressions',
data: [30000, 40000],
backgroundColor: [
"#971317",
"#0b72ba"
],
}, ]
};
var ctx_webbanner_300x600 = document.getElementById('chart_webbanner_300x600').getContext('2d');
var chr = new Chart(ctx_webbanner_300x600, {
data: graphData,
type: 'bar',
options: {
scales: {
yAxes: [{
display: true,
ticks: {
beginAtZero: true // minimum value will be 0.
}
}]
}
}
});
This is based on what I found here Setting specific color per label in chart.js and here How to set max and min value for Y axis - which overcame a problem where the scale was starting at the lowest value in my data set.

Related

ChartJS Choropleth Focusing On US and Not The Entire Earth?

I created this chartJS map to showcase the distribution of registrations for this course. However, i can only see US in the map. Is there an issue with the library or should i use a different project ?
Thank you in Advance
Here is the code:
fetch('https://unpkg.com/world-atlas/countries-50m.json').then((r) => r.json()).then((data) = {
const countries = ChartGeo.topojson.feature(data, data.objects.countries).features;
const dataCountries = <?= json_encode($WorldMapData) ?>;
const chart = new Chart(canvas.getContext("2d"), {
type: 'choropleth',
data: {
labels: countries.map((d) => d.properties.name),
datasets: [{
label: 'Course Registrations',
data: countries.map((d) => ({
feature: d,
value: dataCountries[dataCountries.indexOf(d.properties.name) + 1],
})),
}]
},
options: {
legend: {
display: true
},
scale: {
projection: 'equalEarth'
},
geo: {
colorScale: {
display: true,
position: 'bottom',
quantize: 1,
legend: {
position: 'bottom-right',
},
},
},
}
});
});
This is what I see:
enter image description here
I tried to get a map showcasing the entire earth but it is only showing US.

Add space Between Columns in Bar chart. chartjs

I'm creating graphs using chart js V 2.9.3.
When I create the graph with a small amount of data it renders data perfectly but when the amount of data is increasing, the chart becomes Crowded.
A graph has two columns in single label.
I'm also not able to set the labels without rotation.
var config = {
type: 'bar',
data: {
labels: _datesForLabel,
datasets: _chartDataWithOptions,
},
options: {
tooltips: {
},
plugins: {
colorschemes: {
scheme: 'office.Waveform6'
}
},
scales: {
yAxes: [{
ticks: {
min: 0,
}
}],
xAxes: [{
barThickness: 40,
maxBarThickness: 40,
barPercentage: 1.0,
categoryPercentage: 1.0,
ticks: {
min: 0,
},
}]
}
}
};
myBarChart = new Chart(ctx, config);
These are the options I used.
given is the screenshot of the output
output Image
can anyone help me with this.
thank you
Remove this barThickness: 40, (40 in pixels). In your case "No space/room" for such width = overlaps & broken layout.
https://www.chartjs.org/docs/latest/charts/bar.html#barthickness
Basic snippet (Base on your code) (change barThickness barPercentage barPercentage):
https://www.chartjs.org/docs/latest/charts/bar.html#barpercentage-vs-categorypercentage
var canvas = document.getElementById("myChart");
var ctx = canvas.getContext("2d");
var _datesForLabel = ["2020-02-10",
"2020-02-13",
"2020-02-17",
"2020-02-18",
"2020-02-19",
"2020-02-20",
"2020-02-21",
"2020-02-22",
"2020-02-23",
"2020-02-24",
"2020-02-25",
"2020-02-26",
"2020-02-27",
"2020-02-28",
"2020-02-29",
"2020-03-01",
"2020-03-02",
"2020-03-03",
"2020-03-04",
"2020-03-05",
"2020-03-07",
"2020-03-08",
"2020-03-09",
"2020-03-10","2020-02-10",
"2020-02-13",
"2020-02-17",
"2020-02-18",
"2020-02-19",
"2020-02-20",
"2020-02-21",
"2020-02-22",
"2020-02-23",
"2020-02-24",
"2020-02-25",
"2020-02-26",
"2020-02-27",
"2020-02-28",
"2020-02-29",
"2020-03-01",
"2020-03-02",
"2020-03-03",
"2020-03-04",
"2020-03-05",
"2020-03-07",
"2020-03-08",
"2020-03-09",
"2020-03-10"]
var _chartDataWithOptions =[];
_chartDataWithOptions.push({
label:"dataseries1",
data:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24],
backgroundColor:"blue"
})
_chartDataWithOptions.push({
label:"dataseries2",
data:[2,3,4,5,6,7,8,9,10,12,13,11,10,19,14,12,11,18,26,23,21,28,24,2,3,4,6,9,1,2,1,11,12,13,14,15,16,17,18,19,20,21,22,23,11,22,4,6,3,6],
backgroundColor:"red"
})
var config = {
type: 'bar',
data: {
labels: _datesForLabel,
datasets: _chartDataWithOptions,
borderSkipped: 'top'
},
options: {
// responsive: true,
tooltips: {
// mode: ''
},
plugins: {
colorschemes: {
scheme: 'office.Waveform6'
}
},
scales: {
yAxes: [{
ticks: {
min: 0,
}
}],
xAxes: [{
// barThickness: 40, // number (pixels) or 'flex'
maxBarThickness: 40,
barPercentage: 1,/* change this */
categoryPercentage: 0.5,/* change this */
ticks: {
min: 0,
},
}]
}
}
};
myBarChart = new Chart(ctx, config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" ></script>
<div style="height: 500px; width: 100%;">
<canvas id="myChart" ></canvas>
</div>
About "set labels without rotation" - again "no room" - by maxRotation: 0, - full answer + example her: Chart Js Change Label orientation on x-Axis for Line Charts
"To much points/data" issue:
For now "no way" to auto group data - one idea is to use
stacked: true ("save room") - or manually filter your data (Show fewer points - related StackOverflow Q: Chartjs 2 scaling lots of data points).
Related Github feature request: https://github.com/chartjs/Chart.js/issues/4053

Is it possible to define data attributes for each dataset value in a Chart.js chart?

Is it possible to define HTML5 data attributes for each dataset value in a Chart.js chart? The goal is to enhance the default tooltip information (e.g. X-axis value & Y-axis value) with additional information related to the target dataset value.
In the example below, a chart is displayed that plots the total number of diapers used by 6 children. When the tooltip displays, it says the name of the child and the number of diapers. I would like the tooltip to display age and gender, as well, and figured the tooltip callback could get these from data attributes attached to each dataset value.
I've reviewed the Chart.js documentation and searched online forums, like StackOverflow, without success.
var myChart = new Chart(document.getElementById('myChart'), {
type: 'bar',
data: {
labels: ['Gabriel', 'Zelie', 'Santiago', 'Serafina', 'Berenice', 'Pia'],
datasets: [{ label: 'Diapers', data: [1050, 1224, 1382, 1166, 1471, 0] }]
},
options: {
legend: { display: false },
scales: { yAxes: [{ ticks: { beginAtZero: true } }] },
title: { display: true, text: 'Total Diapers Used' },
tooltips: {
titleFontSize: 18,
callbacks: {
label: function(tooltipItem, data) {
var defaultLabel = data.datasets[tooltipItem.datasetIndex].label + ': ' + tooltipItem.yLabel;
var age = "Age: <age>";
var gender = "Gender: <gender>";
var labels = [defaultLabel, age, gender];
return labels;
}
}
}
}
});
</script>
It depends how you structure your data. In my example I made an object that contains all the data.
let dataObject = {
Gabriel: {
diapers: 40,
age: 4
},
// Same structure here...
Zelie: {...},
Santiago: {...},
Serafina: {...},
Berenice: {...},
Pia: {...}
}
This way you can easily access your data in your tooltip with
tooltips: {
callbacks: {
label: function(tooltipItem, data){
return ['Name: '+tooltipItem.label, 'Diapers: '+tooltipItem.value, 'Age: '+dataObject[tooltipItem.label].age]
}
}
}
You should get all the information you need in the jsbin.
https://jsbin.com/qiyeyohavo/1/edit?html,js,output

How to add a second set of labels to a Chart.js doughnut chart?

I have a doughnut graph created using Chart.js with two datasets. The graph displays the number of employees in offices around the world, with the second dataset breaking this down into permanent and contract employees.
There's a jsfiddle of this running here: https://jsfiddle.net/tetsujin1979/tt3ch8z7/
The "labels" attribute of the options for the graph contains the names of the offices, but since there is only one array of labels, they are repeated for the second dataset, and appear on the mouseover text for it.
var config = {
type: 'doughnut',
data: {
datasets: [
{
data: [124,231,152,613,523],
backgroundColor: [chartColors.red, chartColors.orange, chartColors.yellow, chartColors.green, chartColors.blue],
label: 'Offices'
},
{
data: [60,64,100,131,71,81,337,276,405,118],
backgroundColor: [chartColors.purple, chartColors.grey],
label: 'Permanent/Contract'
}
],
labels: ['London', 'New York', 'Paris', 'Moscow', 'Mumbai']
}
};
var ctx = document.getElementById('employees-graph').getContext('2d');
var employeesGraph = new Chart(ctx, config);
Is it possible to specify a second array of labels for the permanent/contract dataset so the hover text displays the values from this second
Add a labels array to both of the datasets
var config = {
type: 'doughnut',
data: {
datasets: [
{
data: [124,231,152,613,523],
backgroundColor: [chartColors.red, chartColors.orange, chartColors.yellow, chartColors.green, chartColors.blue],
label: 'Offices',
labels: ['London', 'New York', 'Paris', 'Moscow', 'Mumbai']
},
{
data: [60,64,100,131,71,81,337,276,405,118],
backgroundColor: [chartColors.purple, chartColors.grey],
label: 'Permanent/Contract',
labels: ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
}
]
}
};
And add the following to the options:
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var index = tooltipItem.index;
return dataset.labels[index] + ": " + dataset.data[index];
}
}
}
}

ChartJS Update specific bar's background colour

I would like to update specific column background colour but I couldn't do this. Seem like it is very easy but all the solution I tried out from google doesn't work. The code is as below.
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels : ["A","B","C","D","E"],
datasets: [{
data : [<?php echo $graph_data;?>],
backgroundColor: "rgba(0,0,220,0.5)",
borderColor: "rgba(0,0,220,1)",
borderWidth: 2
}]
}
});
//I would like to achieve something like this, let's say change the first and second bar's background color
myChart.datasets[0].bars[0].fillColor = "rgba(220,0,0,0.5)";
myChart.datasets[0].bars[1].fillColor = "rgba(220,0,0,0.5)";
myChart.update();
I had an old code which run succesfully under version 1.0.1-beta.4, but now I world like to use the latest version 2.5.0, and then I faced this issue.
Thanks for any helps!
You can just pass an array to the backgroundColor bar chart dataset property (instead of a single color) where the position in the array maps to the position in the data array.
For example, if you have 3 bars and want all 3 to be a different color, just pass an array to backgroundColor where all 3 elements have a different color value.
var ctx = document.getElementById("canvas").getContext("2d");
var myBar = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Car", "Bike", "Walking"],
datasets: [{
label: 'Fuel',
backgroundColor: [
chartColors.red,
chartColors.blue,
chartColors.yellow],
data: [
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
]
}]
},
options: {
title: {
display: true,
text: "Chart.js - Different Bar Colors"
},
tooltips: {
mode: 'index',
intersect: false
},
legend: {
display: false,
},
responsive: true,
}
});
Here is a codepen example demonstrating this.