Reputation: 1095
I want to create a chart using Chart JS. By default there is no stacked bar chart, but in the official documentation they list this extension: https://github.com/Regaddi/Chart.StackedBar.js
What I want to achieve though, is not necessarily a stacked bar chart. Here is an example:
So my data is the red, and I would like to fill in the rest with up to max value with black.
My problem is that I cannot format the tooltip when I hoover over a bar. Ideally I would like to format it such that only the red dataset is shown.
Here is my code:
var barChartData = {
labels : [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31],
datasets : [
{
fillColor : "rgba(0,12,4,1)",
strokeColor : "rgba(220,220,220,0.8)",
highlightFill: "rgba(0,0,0,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data : [8, 5, 15, 23, 20, 0, 11, 20, 25, 15, 10, 0,
0, 0, 10, 12, 25, 20, 15, 25, 0, 5,
5, 3, 0, 0, 0, 7, 15, 12, 0,]
},
{
fillColor : "rgba(192,12,4,1)",
strokeColor : "rgba(220,220,220,0.8)",
highlightFill: "rgba(192,12,4,0.5)",
highlightStroke: "rgba(220,220,220,1)",
data : [17, 20, 10, 2, 5, 0, 14, 5, 0, 10, 15, 25,
0, 0, 15, 13, 0, 5, 10, 0, 25, 20,
20, 22, 25, 0, 0, 18, 10, 13, 25,]
},
]
};
window.onload = function(){
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx).StackedBar(barChartData, {
responsive : true,
tooltipFillColor: "rgba(0,0,0,0.8)",
multiTooltipTemplate: "<%= 'Used MB' %> : <%= value %>",
scaleOverride : true,
scaleSteps : 5,
scaleStepWidth : 5,
scaleStartValue : 0,
barValueSpacing : 3,
barShowStroke: false
});
};
Any ideas how this is possible? Or is it possible to create this with only a simple bar chart?
I cannot figure out how the multiTooltipTemplate: "<%= 'Used MB' %> : <%= value %>",
formatting works.
Please don't suggest other libraries, I am interested in Chart JS.
Upvotes: 0
Views: 1658
Reputation: 41075
You can extend your chart to do this.
Preview
Script
Chart.types.Bar.extend({
name: "BarAlt",
draw: function () {
Chart.types.Bar.prototype.draw.apply(this, arguments);
var ctx = this.chart.ctx;
var scale = this.scale;
ctx.save();
ctx.fillStyle = 'black';
this.datasets[0].bars.forEach(function (bar, i) {
if (bar.value != 0) {
ctx.beginPath();
ctx.moveTo(bar.x - bar.width / 2, bar.y);
ctx.lineTo(bar.x + bar.width / 2, bar.y);
ctx.lineTo(bar.x + bar.width / 2, scale.startPoint);
ctx.lineTo(bar.x - bar.width / 2, scale.startPoint);
ctx.closePath();
ctx.fill();
}
})
ctx.restore();
}
});
and then
window.myBar = new Chart(ctx).BarAlt(barChartData, {
...
You can change the tooltipFillColor
if you feel that the tooltip doesn't stand out from the black background.
Fiddle - http://jsfiddle.net/o0geemtp/
Upvotes: 1