Stacked Bar Chart With Line Chart In Charts.js - javascript

I can do a standard bar chart with a line, but how can I do a stacked bar chart with the line?
Example, this is code I use for the bar chart with line, what edit/alteration should I make so that I can use this with a stacked bar chart? This is a sample of the stacked bar chart https://www.chartjs.org/samples/latest/charts/bar/stacked.html and this is an example of the bar chart with line https://www.chartjs.org/samples/latest/charts/combo-bar-line.html
var ctx = document.getElementById('myChart');
var config = {
type: 'bar',
options: {
legendCallback: function(chart) {
var text = [];
text.push('<ul class="' + chart.id + '-legend">');
var data = chart.data;
var datasets = data.datasets;
if (datasets.length) {
for (var i = 0; i < datasets.length; ++i) {
text.push('<li>');
if (datasets[i].type=='line') {
text.push('<span class="'+datasets[i].type+'" style="background-color:' + datasets[i].backgroundColor + '"></span>');
} else {
text.push('<span class="'+datasets[i].type+'" style="background-color:' + datasets[i].backgroundColor + '"></span>');
}
text.push(datasets[i].label);
text.push('</li>');
}
}
text.push('</ul>');
return text.join('');
},
legend: {
display: false,
},
scales: {
xAxes: [{
type: "category",
id: "axis-bar",
}, {
type: "time",
id: "axis-time",
display: false,
}, ],
},
},
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
datasets: [{
label: "Dataset1",
type: "line",
backgroundColor: "#0000FF",
borderColor: "#0000FF",
borderWidth: 1,
fill: false,
xAxisID: "axis-time",
data: [12296,12381,9141,24203,21987,21801,65394,91892,57645,44637,22631,17502]
},{
label: "Dataset2",
type: "bar",
backgroundColor: "#ff0000",
borderColor: "#ff0000",
borderWidth: 1,
fill: true,
xAxisID: "axis-bar",
data: [299405,244029,247191,329711,273855,441914,426271,471912,374388,366864,326155,277442]
}]
},
};
var myChart = new Chart(ctx, config);
var legend = myChart.generateLegend();
document.getElementById("legend").innerHTML = legend;

See Chart.js docs for reference:
https://www.chartjs.org/docs/latest/charts/bar.html#stacked-bar-chart
Say you added another dataset:
{
label: "Dataset3",
type: "bar",
backgroundColor: "#00ff00",
borderColor: "#00ff00",
borderWidth: 1,
fill: true,
xAxisID: "axis-bar",
data: [ 149703, 122015, 123596, 164856, 136928, 220957, 213136, 235956, 187194, 183432, 163078, 138721 ]
}
Solution
You need to add extra config to your X and Y axis scales:
scales: {
xAxes: [ { stacked: true }],
yAxes: [ { stacked: true }]
}
Example
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["< 1","1 - 2","3 - 4","5 - 9","10 - 14","15 - 19","20 - 24","25 - 29","> - 29"],
datasets: [{
label: "Dataset1",
type: "line",
backgroundColor: "#0000FF",
borderColor: "#0000FF",
borderWidth: 1,
fill: false,
yAxisID: "axis-time",
data: [12296,12381,9141,24203,21987,21801,65394,91892,57645,44637,22631,17502]
},{
label: "Dataset2",
type: "bar",
backgroundColor: "#ff0000",
borderColor: "#ff0000",
borderWidth: 1,
fill: true,
yAxisID: "axis-bar",
data: [
149703, 122015,
123596, 164856,
136928, 220957,
213136, 235956,
187194, 183432,
163078, 138721
]
},{
label: "Dataset3",
type: "bar",
backgroundColor: "#00ff00",
borderColor: "#00ff00",
borderWidth: 1,
fill: true,
yAxisID: "axis-bar",
data: [
149703, 122015,
123596, 164856,
136928, 220957,
213136, 235956,
187194, 183432,
163078, 138721
]
}],
},
options: {
tooltips: {
displayColors: true,
},
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true,
id: 'axis-bar'
}, {
stacked: true,
id: 'axis-time',
display: false,
}]
},
responsive: true,
maintainAspectRatio: false,
legend: { display: false },
legendCallback: function(chart) {
var text = [];
text.push('<ul class="' + chart.id + '-legend">');
var data = chart.data;
var datasets = data.datasets;
if (datasets.length) {
for (var i = 0; i < datasets.length; ++i) {
text.push('<li>');
if (datasets[i].type=='line') {
text.push('<span class="'+datasets[i].type+'" style="background-color:' + datasets[i].backgroundColor + '"></span>');
} else {
text.push('<span class="'+datasets[i].type+'" style="background-color:' + datasets[i].backgroundColor + '"></span>');
}
text.push(datasets[i].label);
text.push('</li>');
}
}
text.push('</ul>');
return text.join('');
}
}
});
var legend = myChart.generateLegend();
document.getElementById("legend").innerHTML = legend;
canvas{
background:#fff;
height:400px;
}
<script src="https://www.chartjs.org/dist/2.9.3/Chart.min.js"></script>
<div class="wrapper">
<canvas id="myChart"></canvas>
<div id="legend"></div>
</div>
I also created a CodePen with the same code that shows the stacked bars & line chart:
https://codepen.io/pzi/pen/GRoObmq

Related

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.

Combo Bar Line Chart with Chart.js

My line chart is not showing on my chart.js at all. What piece of the puzzle am i missing here?
Also here is a fiddle that shows my code, you can see the bar graph displays as expected but the line chart does not. https://jsfiddle.net/c50dfw3g/1/
I have never used this type of chart before so I am not certain how exactly to set it up. Thanks in advance to all who assist.
var ctx = document.getElementById('myChart');
var config = {
type: 'bar',
options: {
legendCallback: function(chart) {
var text = [];
text.push('<ul class="' + chart.id + '-legend">');
var data = chart.data;
var datasets = data.datasets;
if (datasets.length) {
for (var i = 0; i < datasets.length; ++i) {
text.push('<li>');
if (datasets[i].type=='line') {
text.push('<span class="'+datasets[i].type+'" style="background-color:' + datasets[i].backgroundColor + '"></span>');
} else {
text.push('<span class="'+datasets[i].type+'" style="background-color:' + datasets[i].backgroundColor + '"></span>');
}
text.push(datasets[i].label);
text.push('</li>');
}
}
text.push('</ul>');
return text.join('');
},
legend: {
display: false,
},
scales: {
xAxes: [{
type: "category",
id: "axis-bar",
}, {
type: "time",
id: "axis-time",
display: false,
}, ],
},
},
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
datasets: [{
label: "Dataset1",
type: "line",
backgroundColor: "#0000FF",
borderColor: "#0000FF",
borderWidth: 1,
fill: false,
xAxisID: "axis-time",
data: [12296,12381,9141,24203,21987,21801,65394,91892,57645,44637,22631,17502]
},{
label: "Dataset2",
type: "bar",
backgroundColor: "#ff0000",
borderColor: "#ff0000",
borderWidth: 1,
fill: true,
xAxisID: "axis-bar",
data: [299405,244029,247191,329711,273855,441914,426271,471912,374388,366864,326155,277442]
}]
},
};
var myChart = new Chart(ctx, config);
var legend = myChart.generateLegend();
document.getElementById("legend").innerHTML = legend;
Try using the same X-axis for both data sets:
scales: {
xAxes: [{
type: "category",
id: "axis-bar",
}/* Commenting out the second axis, {
type: "time",
id: "axis-time",
display: true,
}, */],
},
Now, we'll set the line dataset to use this X-axis:
datasets: [{
label: "Dataset1",
type: "line",
backgroundColor: "#0000FF",
borderColor: "#0000FF",
borderWidth: 1,
fill: false,
xAxisID: "axis-bar",
data: [12296,12381,9141,24203,21987,21801,65394,91892,57645,44637,22631,17502]
},
And here we go:
The issue is with the 'xAxisID' attributes.
You specify the x-axis id as: 'axis-bar' but then use a different id when specifying dataset 1 ('axis-time'), so it's not being plotted on the same graph.
Just use the same id in the datasets as you specify when defining the scale of the graph and you'll get both plots on the same chart and thus your desired result.

Change color of line along labels Chart.js

I am trying to change the colour and thickness of the lines along the Y and X axis.
I don't know what I am looking for in the documentation but have named them line in the code for now.
What is the line called and what should I name it for it to work?
The lines inside the red mark I want to keep but remove grid.
HTML
<canvas id="canvas-1"></canvas>
JS
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var lineChartData = {
labels : ['January','February','March','April','May','June','July'],
datasets : [
{
label: 'My First dataset',
labelColor : '#fff',
fontColor : '#fff' ,
backgroundColor : 'rgba(220,220,220,0.2)',
borderColor : 'rgba(220,220,220,1)',
pointBackgroundColor : 'rgba(220,220,220,1)',
pointBorderColor : '#fff',
data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
}
]
}
var options = {
responsive: true,
maintainAspectRatio: false,
legend: {
fontColor: "white",
},
scales: {
xAxes: [{
gridLines: {
display: true,
drawBorder: true,
color: "green",
},
ticks: {
fontColor: "white",
},
}],
yAxes: [{
stacked: true,
gridLines: {
display: true,
drawBorder: true,
color: "blue",
},
ticks: {
fontColor: "white",
beginAtZero: true,
}
}]
}
};
var ctx = document.getElementById('canvas-1');
var chart = new Chart(ctx, {
type: 'line',
data: lineChartData,
options: options
});
To change the color and thickness of lines (along x and y axis), set color and lineWidth property respectively, for both axis­'s grid-lines, like so :
scales: {
xAxes: [{
gridLines: {
display: false,
color: 'green',
lineWidth: 3
},
...
}],
yAxes: [{
gridLines: {
display: false,
color: '#07C',
lineWidth: 3
},
...
}]
}
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
var randomScalingFactor = function() {
return Math.round(Math.random() * 100)
};
var lineChartData = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
labelColor: '#fff',
fontColor: '#fff',
backgroundColor: 'rgba(220,220,220,0.2)',
borderColor: 'rgba(220,220,220,1)',
pointBackgroundColor: 'rgba(220,220,220,1)',
pointBorderColor: '#fff',
data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
}]
}
var options = {
responsive: true,
maintainAspectRatio: false,
legend: {
fontColor: "white",
},
scales: {
xAxes: [{
gridLines: {
display: false,
color: 'green',
lineWidth: 3
},
ticks: {
fontColor: "white",
},
}],
yAxes: [{
stacked: true,
gridLines: {
display: false,
color: '#07C',
lineWidth: 3
},
ticks: {
fontColor: "white",
beginAtZero: true,
}
}]
}
};
var ctx = document.getElementById('canvas-1');
var chart = new Chart(ctx, {
type: 'line',
data: lineChartData,
options: options
});
canvas { background: #222 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas-1"></canvas>
EDIT:
For those looking to change the generated graph line (not the grid lines):
The line options are for the line type graph, similar as you'll have a doughnut type and so on. I believe you figured that out, right?
A quick look in my code showed the option datasetStrokeWidth which you can use for the thickness. more info
The color option can be found under strokeColor for the style options.
As chart.js combines data- & style options, you're options will look something like this:
var lineChartData = {
line: {
datasets: [
{
strokeColor: '#15bedb'
}
]
}
};
var lineChartStyle = {
line: {
datasetStrokeWidth: 1
}
};
var ctx = document.getElementById('canvas-1');
var chart = new Chart(ctx, {
type: 'line',
data: lineChartData,
options: lineChartStyle
});

how to change the Y-axis values from float number to integer in chartjs?

i want to change Yaxis from real number to integer and here is image, and please help me solve this problem
here is my code
var lineChartData = {
labels: time,
datasets: [{
label: "Số người đăng kí ủng hộ",
borderColor: window.chartColors.red,
pointBackgroundColor: window.chartColors.red,
fill: false,
data: people_isProcessing
}, {
label: "Số người đã ủng hộ",
borderColor: window.chartColors.purple,
pointBackgroundColor: window.chartColors.purple,
fill: false,
data: people_isReceived
}]
};
and here is my option for my chart
window.onload = function() {
var chartEl = document.getElementById("chart");
window.myLine = new Chart(chartEl, {
type: 'line',
data: lineChartData,
options: {
title: {
display: true,
text: 'Kindmate - Chart Static Donate'
},
tooltips: {
enabled: true,
mode: 'index',
position: 'nearest',
custom: customTooltips
}
}
});
});
In your case, you can set stepSize property to 1 for y-axis ticks, to change the y-axis values from float number to integer.
options: {
scales: {
yAxes: [{
ticks: {
stepSize: 1
}
}]
},
...
}
ᴅᴇᴍᴏ
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr'],
datasets: [{
label: '# of votes',
data: [1, 2, 3, 4]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
stepSize: 1
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>
Try this:
window.onload = function() {
var chartEl = document.getElementById("chart");
window.myLine = new Chart(chartEl, {
type: 'line',
data: lineChartData,
options: {
title:{
display:true,
text:'Kindmate - Chart Static Donate'
},
tooltips: {
enabled: true,
mode: 'index',
position: 'nearest',
custom: customTooltips
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
callback: function(value) {if (value % 1 === 0) {return value;}}
}
}]
}
}
});

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