2👍
✅
Basically, you need to subtract the second value from the first one before the chart initializes, so that, it doesn’t draw the graph with combined values.
To accomplish so, you can use the following chart plugin …
plugins: [{
beforeInit: function(c) {
var data1 = c.data.datasets[0].data;
var data2 = c.data.datasets[1].data;
c.data.datasets[0].data = data1.map(function(e, i) {
return e - data2[i];
});
}
}]
add this plugin followed by your chart options.
UPDATE
use the following tooltips callback function to show the old values on tooltip’s label …
tooltips: {
callbacks: {
label: function(t, d) {
var dst1_label = d.datasets[t.datasetIndex].label + ': ' + (+t.yLabel + d.datasets[1].data[t.index]);
var dst2_label = d.datasets[t.datasetIndex].label + ': ' + t.yLabel;
if (t.datasetIndex === 0) return dst1_label;
else return dst2_label;
}
}
}
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: 'Sales',
data: [500, 300],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(255, 99, 132, 0.2)',
'rgba(255, 99, 132, 0.2)',
'rgba(255, 99, 132, 0.2)',
'rgba(255, 99, 132, 0.2)',
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(255,99,132,1)',
'rgba(255,99,132,1)',
'rgba(255,99,132,1)',
'rgba(255,99,132,1)',
'rgba(255,99,132,1)'
],
borderWidth: 2
}, {
label: 'Earning',
data: [100, 30],
backgroundColor: [
'rgba(255, 159, 64, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 159, 64, 1)',
'rgba(255, 159, 64, 1)',
'rgba(255, 159, 64, 1)',
'rgba(255, 159, 64, 1)',
'rgba(255, 159, 64, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 2
}]
},
options: {
scales: {
yAxes: [{
stacked: true,
ticks: {
beginAtZero: true
}
}],
xAxes: [{
stacked: true,
ticks: {
beginAtZero: true
}
}]
},
tooltips: {
callbacks: {
label: function(t, d) {
var dst1_label = d.datasets[t.datasetIndex].label + ': ' + (+t.yLabel + d.datasets[1].data[t.index]);
var dst2_label = d.datasets[t.datasetIndex].label + ': ' + t.yLabel;
if (t.datasetIndex === 0) return dst1_label;
else return dst2_label;
}
}
}
},
plugins: [{
beforeInit: function(c) {
var data1 = c.data.datasets[0].data;
var data2 = c.data.datasets[1].data;
c.data.datasets[0].data = data1.map(function(e, i) {
return e - data2[i];
});
}
}]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
Source:stackexchange.com