Combo Bar Line Chart with Chart.js - javascript

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.

Related

Stacked Bar Chart With Line Chart In Charts.js

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

Modify the information box of the scatter chart in Chart.JS

I'm working with a scatter chart in chart.js and I need to modify the info what I show when I'm above a point. I think the box that contains this information is called tooltip.
Below I show what I have now,
What I want to do is modify the first one, and put 14:52 like the x-axis.
In the x-axis was easy,
options: {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom',
ticks: {
callback: function(value, index, values) {
var time = String(value);
if (time.length == 3){
time = '0' + time;
}
var hour = time[0] + time[1];
var min = time[2] + time[3];
var label = hour + ':' + min;
return label;
}
}
}]
}
}
And I suppose here I have to use the same function, but I don't know where. I'm not able to access to the box with the information, isn't its name tooltips? For example, I'm doing the code below but nothing change.
tooltips:{
title: "New title"
}
How can I modify that box?
Thank you very much
The title and other items on the tooltip can be customized using callback functions. The correct syntax looks as follows.
tooltips:{
callbacks: {
title: (tooltipItem, data) => "New title"
}
}
Please also have a look on the following more complex sample derived from https://www.chartjs.org/samples/latest/tooltips/callbacks.html. It should make no difference whether you work with a scatter or a line chart.
new Chart(document.getElementById('myChart'), {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
borderColor: 'red',
backgroundColor: 'red',
data: [15, 22, 18, 28, 8, 13, 24],
fill: false,
}, {
label: 'My Second dataset',
borderColor: 'blue',
backgroundColor: 'blue',
data: [5, 31, 15, 22, 19, 29, 12],
fill: false,
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js Line Chart - Custom Information in Tooltip'
},
tooltips: {
mode: 'index',
callbacks: {
title: (tooltipItem, data) => data.labels[tooltipItem[0].index],
footer: (tooltipItems, data) => {
var sum = 0;
tooltipItems.forEach(function(tooltipItem) {
sum += data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
});
return 'Sum: ' + sum;
},
},
footerFontStyle: 'normal'
},
hover: {
mode: 'index',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
show: true,
labelString: 'Month'
}
}],
yAxes: [{
display: true,
scaleLabel: {
show: true,
labelString: 'Value'
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="100"></canvas>

DIsplay Ajax data in Highchart js

Please i have this ajax code working fine but my problem is how to display it on highchart. This is the ajax code
function ajaxGetRadiologyRecord() {
let urlPath = 'http://' + window.location.hostname + ':8000/radiology/get-patient-radiology-record';
let request = $.ajax({
method: 'GET',
url: urlPath,
});
request.done(function( response ) {
console.log(response);
let months = response.months;
let monthlyRecord = response.monthly_record_count;
});
}
when i log the response am having the data in an array. i.e the months and the records. I kept both is seperate variables months and monthlyRecord.
here is the js highchart code
Highcharts.chart('container', {
chart: {
type: 'column',
events: {
load: ajaxGetRadiologyRecord()
}
},
title: {
text: ''
},
xAxis: {
categories: [
'Jan',
'Feb',
'Masr',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
],
crosshair: true
},
yAxis: {
min: 0,
title: {
text: ''
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f}</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
exporting: {
enabled: false
},
credits: {
enabled: false
},
legend: {
enabled: false
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0,
borderRadius: 2
}
},
series: [{
name: 'Patients',
data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1],
color: {
linearGradient: {
x1: 0,
x2: 0,
y1: 0,
y2: 1
},
stops: [
[0, 'rgba(153, 153, 153, 0.5)'],
[1, '#f3f4f4']
]
}
}]
});
My problem now is how to replace the categories array with the months from ajax and data[] with monthlyRecord from the ajax. Thanks.
there are different ways, but you can do this way,
var chart = Highcharts.chart('container', {
chart: {
type: 'column',
events: {
load: ajaxGetRadiologyRecord()
}
},
. . .
series: [
{
name: 'Patients',
data: []
}
]
});
define your series here , can define multiple series
function ajaxGetRadiologyRecord() {
let urlPath = 'http://' + window.location.hostname + ':8000/radiology/get-patient-radiology-record';
$.ajax({
method: 'GET',
url: urlPath,
});
request.done(function( response ) {
console.log(response);
chart.addSeries({
name: "Patients",
data: response.monthly_record_count
});
});
}

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;}}
}
}]
}
}
});

Categories