How Can I Calculate A Value And Place It Inside The Last Bar In A Chart.js Bar Chart?
Since it seems impossible or highly difficult (no working answers here) to place a label above the last bar on a bar chart, I would like to now know how to place a label inside the
Solution 1:
In your animation.onComplete
callback, you can get the previous dataset with the following code :
// `dataset` here -----------------------------------------┐// is the current dataset you are working on |// (since you loop through all of them in your callback) Vvar previousDataset = chartInstance.config.data.datasets[dataset._meta[Object.keys(dataset._meta)[0]].controller.index - 1];
Now that you can access the previous dataset, you can also get its value. Follows the full callback to make it more understandable :
var forecastOptions = {
tooltips: {
enabled: true
},
animation: {
duration: 500,
easing: "easeOutQuart",
onComplete: function() {
var ctx = this.chart.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function(dataset) {
for (var i = 0; i < dataset.data.length; i++) {
// We get the previous dataset herevar previousDataset = dataset._meta[Object.keys(dataset._meta)[0]].controller.chart.config.data.datasets[dataset._meta[Object.keys(dataset._meta)[0]].controller.index - 1];
var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
var scale_max = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._yScale.maxHeight;
ctx.fillStyle = '#444';
var y_pos = model.y - 5;
if ((scale_max - model.y) / scale_max >= 0.93)
y_pos = model.y + 20;
// If the previous dataset is not `undefined` (actually exists) ..if(typeof previousDataset !== "undefined") {
// We write the data, with the difference with the previous one
ctx.fillText(dataset.data[i] + " (" + (dataset.data[i] - previousDataset.data[i]) + ")", model.x, y_pos);
}
else {
// We only write the data
ctx.fillText(dataset.data[i], model.x, y_pos);
}
}
});
}
}
};
You can see this callback working on this jsFiddle, and here is its result :
Note: Feel free to comment if you need any small changes such as a percentage difference instead.
Post a Comment for "How Can I Calculate A Value And Place It Inside The Last Bar In A Chart.js Bar Chart?"