How do I create a legend for a bar chart? - javascript

How do I create legends like the following:
So far I have the following:
I can't figure out how to specify labels for the legend. They don't provide examples either.
https://www.chartjs.org/docs/latest/configuration/legend.html
So far I have the following code:
var topClickSourcesChart = new Chart('dashboard-click-source-chart', {
type: 'bar',
data: {
labels: ["Facebook","Google","NONE",],
datasets: [{
data: [10,5,3,],
backgroundColor: ['#4D90C3', '#866DB2', '#EA6F98', '#61BDF6', '#768BB7'],
}],
},
options: {
scales: {
xAxes: [{
display: false,
}]
},
legend: {
position: 'right',
labels: {
boxWidth: 10,
}
}
}
});

To show a legend you need to set the label property of a dataset, so the type of output you are expecting can be built by creating a chart from the code as shown below. Fiddle -> https://jsfiddle.net/6nkcx8sq/
var topClickSourcesChart = new Chart('dashboard-click-source-chart', {
type: 'bar',
data: {
labels: ["Number of users"],
datasets: [{
label: 'Facebook',
data: [10],
backgroundColor: '#4D90C3',
},
{
label: 'Instagram',
data: [15],
backgroundColor: '#866DB2',
},
{
label: 'Twitter',
data: [7],
backgroundColor: '#EA6F98',
}],
},
options: {
scales: {
xAxes: [{
display: false,
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
legend: {
position: 'right',
labels: {
boxWidth: 10,
}
}
}
});

I was able to get it with the following, but it was a pain in the ass for loops due to the backgroundColor having to be inside the dataset.
var topClickSourceChart = new Chart('dashboard-click-source-chart', {
type: 'bar',
data: {
labels: ["Facebook","Google","NONE",],
datasets: [
{label: "Facebook", data: [10]},{label: "Google", data: [5]},{label: "NONE", data: [3]},
]
},
options: {
scales: {
xAxes: [{
display: false,
}],
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
},
legend: {
position: 'right',
labels: {
boxWidth: 10,
}
}
}
});
if (topClickSourceChart.data.datasets.length > 0) topClickSourceChart.data.datasets[0].backgroundColor = '#4D90C3';
if (topClickSourceChart.data.datasets.length > 1) topClickSourceChart.data.datasets[1].backgroundColor = '#866DB2';
if (topClickSourceChart.data.datasets.length > 2) topClickSourceChart.data.datasets[2].backgroundColor = '#EA6F98';
if (topClickSourceChart.data.datasets.length > 3) topClickSourceChart.data.datasets[3].backgroundColor = '#61BDF6';
if (topClickSourceChart.data.datasets.length > 4) topClickSourceChart.data.datasets[4].backgroundColor = '#768BB7';
Here is the JSP/JSTL loop:
data: {
labels: [<c:forEach items="${clickSources}" var="cs">"${cs.key}",</c:forEach>],
datasets: [
<c:forEach items="${clickSources}" var="cs">{label: "${cs.key}", data: [${cs.value}]},</c:forEach>
]
},
I still could not find a way to make the top of the bars rounded.

Related

Chart JS Tooltip Currency Problem - Stacked Bar Chart

I use ChatJS and i want to add an € Symbol after every number in the Tooltip.
On my most charts it works perfectly but the Stacked Bar Chart makes me problems.
Here is an example Code like mine (Just a basic Example)
var barChart = new Chart(ctx_barChart, {
type: 'bar',
data: {
labels: ["Fruits"],
datasets: [{
label: [
["Apple"]
],
data: [12],
backgroundColor: 'blue',
barThickness: 80,
},
{
label: ["Banana"],
data: [15],
backgroundColor: 'red',
barThickness: 80,
},
]
},
options: {
maintainAspectRatio: false,
indexAxis: 'y',
responsive: true,
scales: {
x: {
stacked: true,
display: false,
},
y: {
stacked: true,
display: false,
mirror: true,
}
},
plugins: {
tooltip: {
callbacks: {
label: function(context) {
let label = context.dataset.label || '';
if (label) {
label += ': ';
}
if (context.parsed.y !== null) {
label += new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'EUR'
}).format(context.parsed.y);
}
return label;
}
}
},
legend: {
display: false
},
title: {
display: false,
},
},
},
});
The tooltips both show 0,00$, but not my Values 12 and 15. Anyone have an suggestiont?
You should use context.parsed.x instead of context.parsed.y since it's a horizontal bar chart.
Please take a look at your amended code and see how it works.
new Chart('barChart', {
type: 'bar',
data: {
labels: ["Fruits"],
datasets: [{
label: "Apple",
data: [12],
backgroundColor: 'blue',
barThickness: 80,
},
{
label: "Banana",
data: [15],
backgroundColor: 'red',
barThickness: 80,
},
]
},
options: {
maintainAspectRatio: false,
indexAxis: 'y',
responsive: true,
scales: {
x: {
stacked: true,
display: false,
},
y: {
stacked: true,
display: false,
mirror: true,
}
},
plugins: {
tooltip: {
callbacks: {
label: ctx => ctx.dataset.label + ': ' + new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(ctx.parsed.x)
}
},
legend: {
display: false
},
title: {
display: false,
},
},
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<canvas id="barChart" height="100"></canvas>

chartjs display data in one bar line with 3 different data sets in 3 different colors

I currently display my data like this:
Click here
but I would like to display the data like this:
Click here
The idea is that at the bottom it would show the summary of all three colors numbers combined, but once you hover it would show how much each color has.
If all is one bar, if red is 7, blue is 3, the red but be a lot more in the bar.
This is the code for version 1, done with chart js
var ctx = document.getElementById("myChart").getContext("2d");
var data = {
labels: ["Chocolate", "Vanilla", "Strawberry"],
datasets: [
{
label: "Blue",
backgroundColor: "blue",
data: [3, 7, 4]
},
{
label: "Red",
backgroundColor: "red",
data: [4, 3, 5]
},
{
label: "Green",
backgroundColor: "green",
data: [7, 2, 6]
}
]
};
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
barValueSpacing: 20,
scales: {
yAxes: [{
ticks: {
min: 0,
}
}]
}
}
});
const myChart = new Chart(
document.getElementById('myChart'),
config
);
your problem is the next, you are using a wrong config you must something like this:
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.6.0/dist/chart.min.js"></script>
<canvas id="MyChart" width="400" height="200"></canvas>
<script>
new Chart(document.getElementById("MyChart"), {
type: 'bar',
data: {
labels: [2017],
datasets: [{
label: "Chocolate",
type: "bar",
stack: "Base",
backgroundColor: "#eece01",
data: [30],
}, {
label: "Vanilla",
type: "bar",
stack: "Base",
backgroundColor: "#87d84d",
data: [-15],
}, {
label: "Strawberry",
type: "bar",
stack: "Base",
backgroundColor: "#f8981f",
data: [20],
}, {
label: "candy",
type: "bar",
stack: "Base",
backgroundColor: "#00b300",
backgroundColorHover: "#3e95cd",
data: [-10]
}]
},
options: {
plugins: {
title: {
display: true,
text: 'Chart.js Bar Chart - Stacked'
},
},
responsive: true,
interaction: {
intersect: false,
},
scales: {
x: {
stacked: true,
},
y: {
stacked: true
}
}
}
});
</script>
Now you just need to fix the styles and sizes of the graphic
If someone finds this, the solution is this:
const config = {
type: 'bar',
data: data,
options: {
plugins: {
title: {
display: true,
text: 'Chart.js Bar Chart - Stacked'
},
},
responsive: true,
scales: {
x: {
stacked: true,
},
y: {
stacked: true
}
}
}
};

Change Vertical Line and Color bar chart in bar chart.js

help me !
how to delete numeric data on the bar chart in bar chartjs
let datas_1 = [97,70,87,43,35,18];
let colorHex_1 = ['#ebeef3','#ebeef3','#ebeef3','#ebeef3','#ebeef3','#ebeef3'];
let labels_1 = ['10대','12대','30대','40대','50대','60대이상'];
var myBarChart = new Chart(ctx_1, {
type: 'horizontalBar',
data: {
datasets: [{
data: datas_1 ,
backgroundColor: colorHex_1,
borderWidth: 0,
barPercentage: 1,
}],
labels: labels_1,
},
options: {
responsive: true,
legend: {
display:false,
},
scales: {
xAxes: [{
display:false,
}],
yAxes: [{
gridLines:{
display:false,
color: "black"
},
maxBarThickness: 20,
}]
}
}
});
how to delete numeric data on the bar chart in bar chart.js
Working Demo: https://jsfiddle.net/usmanmunir/hz3gLj19/3/
Try this code:
let datas_1 = [97,70,87,43,35,18];
let colorHex_1 = ['#ebeef3', '#ebeef3', '#ebeef3', '#ebeef3', '#ebeef3', '#ebeef3'];
let labels_1 = ['10대', '12대', '30대', '40대', '50대', '60대이상'];
var ctx = document.getElementById("myChart");
var myBarChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
datasets: [{
data: datas_1,
backgroundColor: colorHex_1,
borderWidth: 0,
barPercentage: 1,
}],
labels: labels_1,
},
options: {
responsive: true,
legend: {
display: false,
},
scales: {
xAxes: [{
display: false,
}],
yAxes: [{
gridLines: {
display: false,
},
maxBarThickness: 20,
}]
}
}
});
Hope this helps.

Chart.js too slow rendering vertical stacked bars chart

I'm using chart.js API to render a several stacked vertical bars chart, but the performance is slow. I even made some changes such that all the content object was already processed by the server, and not the browser, but I realised the big majority of time comes from the final function new Chart(overallStatsChart, content);.
I also tried switching off animation, which slightly improved performance, but not that much.
Any ideas on how to improve performance, that is, initial loading?
var countryList = {"AR":"Argentina","AU":"Australia","BO":"Bolivia","BR":"Brasil","CA":"Canada","CL":"Chile","CN":"中国","CO":"Colombia","CR":"Costa Rica","CU":"Cuba","CZ":"Česká","DE":"Deutschland","DK":"Danmark","DO":"Rep. Dominicana","EC":"Ecuador","ES":"España","FI":"Suomessa","FR":"France","GR":"Ελλάδα","GT":"Guatemala","HU":"Magyarország","IE":"Ireland","IN":"India","IT":"Italia","JP":"日本","MX":"México","NI":"Nicaragua","NL":"Nederland","NO":"Norge","PA":"Panamá","PE":"Perú","PL":"Polska","PR":"Puerto Rico","PT":"Portugal","PY":"Paraguay","RO":"România","RU":"Россия","SE":"Sverige","SV":"El Salvador","TR":"Türkiye","UA":"Україна","UK":"United Kingdom","US":"USA","UY":"Uruguay","VE":"Venezuela"};
//populates country labels
var labels = [], size = 0;
for (var key in countryList){
labels.push(key);
size++;
}
var _data = function(i){
var arr = [];
for (var n=0; n<size; n++){
arr.push(n==i ? 1 : 0);
}
return arr;
};
var dataset = [], i=0;
for (var key in countryList){
dataset.push(
{
label: "depreciation",
data: _data(i),
backgroundColor: 'navy'
}, {
label: "insurance",
data: _data(i),
backgroundColor: 'blue'
}, {
label: "credit",
data: _data(i),
backgroundColor: 'aqua'
}, {
label: "inspection",
data: _data(i),
backgroundColor: 'teal'
}, {
label: "road taxes",
data: _data(i),
backgroundColor: 'olive'
}, {
label: "maintenance",
data: _data(i),
backgroundColor: 'green'
}, {
label: "repairs",
data: _data(i),
backgroundColor: 'lime'
}, {
label: "fuel",
data: _data(i),
backgroundColor: 'maroon'
}, {
label: "parking",
data: _data(i),
backgroundColor: 'yellow'
}, {
label: "tolls",
data: _data(i),
backgroundColor: 'orange'
}, {
label: "fines",
data: _data(i),
backgroundColor: 'red'
}, {
label: "washing",
data: _data(i),
backgroundColor: 'purple'
}, {
label: "maintenance",
data: _data(i),
backgroundColor: 'green'
}
);
i++;
}
var options = {
maintainAspectRatio: false,
legend: {
position: 'bottom', // place legend on the right side of chart
display: false, //do not display
labels : {
fontSize: 9,
fontColor: 'black'
}
},
scales: {
xAxes: [{
stacked: true, // this should be set to make the bars stacked
beginAtZero: true
}],
yAxes: [{
stacked: true, // this also..
beginAtZero: true
}]
},
animation: {
duration : 1000,
easing : 'linear'
}
};
var content = {
type: 'bar',
data: {
labels: labels,
datasets: dataset
},
options: options
};
//I made tests with timestamps and here it takes the biggest part of the time
new Chart(overallStatsChart, content);
.chart {
position: relative;
margin: auto;
}
#overallStatsChartDiv{
min-height: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<div class="chart" id="overallStatsChartDiv">
<canvas id="overallStatsChart"></canvas>
</div>
Now I get it :)
I was wrongly duplicating the data attributes, based on this answer.
Solution is quite simple, every data attribute can have directly all the values, without the need of introduction of zeros.
var countryList = {"AR":"Argentina","AU":"Australia","BO":"Bolivia","BR":"Brasil","CA":"Canada","CL":"Chile","CN":"中国","CO":"Colombia","CR":"Costa Rica","CU":"Cuba","CZ":"Česká","DE":"Deutschland","DK":"Danmark","DO":"Rep. Dominicana","EC":"Ecuador","ES":"España","FI":"Suomessa","FR":"France","GR":"Ελλάδα","GT":"Guatemala","HU":"Magyarország","IE":"Ireland","IN":"India","IT":"Italia","JP":"日本","MX":"México","NI":"Nicaragua","NL":"Nederland","NO":"Norge","PA":"Panamá","PE":"Perú","PL":"Polska","PR":"Puerto Rico","PT":"Portugal","PY":"Paraguay","RO":"România","RU":"Россия","SE":"Sverige","SV":"El Salvador","TR":"Türkiye","UA":"Україна","UK":"United Kingdom","US":"USA","UY":"Uruguay","VE":"Venezuela"};
//populates country labels
var labels = [], size = 0;
for (var key in countryList){
labels.push(key);
size++;
}
var _data = function(){
var arr = [];
for (var n=0; n<size; n++){
arr.push(1);
}
return arr;
};
var dataset = [
{
label: "depreciation",
data: _data(),
backgroundColor: 'navy'
}, {
label: "insurance",
data: _data(),
backgroundColor: 'blue'
}, {
label: "credit",
data: _data(),
backgroundColor: 'aqua'
}, {
label: "inspection",
data: _data(),
backgroundColor: 'teal'
}, {
label: "road taxes",
data: _data(),
backgroundColor: 'olive'
}, {
label: "maintenance",
data: _data(),
backgroundColor: 'green'
}, {
label: "repairs",
data: _data(),
backgroundColor: 'lime'
}, {
label: "fuel",
data: _data(),
backgroundColor: 'maroon'
}, {
label: "parking",
data: _data(),
backgroundColor: 'yellow'
}, {
label: "tolls",
data: _data(),
backgroundColor: 'orange'
}, {
label: "fines",
data: _data(),
backgroundColor: 'red'
}, {
label: "washing",
data: _data(),
backgroundColor: 'purple'
}, {
label: "maintenance",
data: _data(),
backgroundColor: 'green'
}
];
var options = {
maintainAspectRatio: false,
legend: {
position: 'bottom', // place legend on the right side of chart
display: false, //do not display
labels : {
fontSize: 9,
fontColor: 'black'
}
},
scales: {
xAxes: [{
stacked: true, // this should be set to make the bars stacked
beginAtZero: true
}],
yAxes: [{
stacked: true, // this also..
beginAtZero: true
}]
},
animation: {
duration : 1000,
easing : 'linear'
}
};
var content = {
type: 'bar',
data: {
labels: labels,
datasets: dataset
},
options: options
};
//I made tests with timestamps and here it takes the biggest part of the time
new Chart(overallStatsChart, content);
.chart {
position: relative;
margin: auto;
}
#overallStatsChartDiv{
min-height: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<div class="chart" id="overallStatsChartDiv">
<canvas id="overallStatsChart"></canvas>
</div>

chartjs: How to remove specific label

I have a Bar Chart with these data and options:
var data = {
labels: periodnames,
datasets: [
{
yAxisID: "bar-stacked",
data: rcash,
backgroundColor: "#FFCE56",
label:""
},
{
yAxisID:"bar-stacked",
data: pcash,
backgroundColor: "#FFCE56",
label: "cash"
}
]
};
var options = {
animation: {
animateScale: true
},
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [
{
display:false,
id: "line-axis",
},
{
id: "bar-stacked",
stacked: true,
}
]
}
}
finactivityGraphChart = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
The result chart is this:
My problem is that I don't want to show the first dataset's label. If I don't define it, it shows the yellow box with the value "undefine" next to it. I suppose that I must modify the Chart.js file. Any suggestions?
This could be achieved, using the filter function of legend­*'s* label.
see Legend Label Configuration
In short, add the following in your chart options ...
legend: {
labels: {
filter: function(label) {
if (label.text === 'cash') return true;
}
}
},
ᴅᴇᴍᴏ
var ctx = document.querySelector('#c').getContext('2d');
var data = {
labels: ['Jan', 'Feb', 'Mar'],
datasets: [{
yAxisID: "bar-stacked",
data: [1, 2, 3],
backgroundColor: "#FFCE56",
label: "gold"
}, {
yAxisID: "bar-stacked",
data: [-1, -2, -3],
backgroundColor: "#FFCE56",
label: "cash"
}]
};
var options = {
legend: {
labels: {
filter: function(label) {
if (label.text === 'cash') return true; //only show when the label is cash
}
}
},
animation: {
animateScale: true
},
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
display: false,
id: "line-axis",
}, {
id: "bar-stacked",
stacked: true,
}]
}
}
finactivityGraphChart = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script>
<canvas id="c"></canvas>

Categories