In Chart.js, is there any way to write the labels inside of the horizontal bars in a "horizontalBar"
chart? As in something like:
Is anything similar to this possible in Chart.js?
Thanks!
In Chart.js, is there any way to write the labels inside of the horizontal bars in a "horizontalBar"
chart? As in something like:
Is anything similar to this possible in Chart.js?
Thanks!
There is now on option "mirror" to make the label appear inside the bar.
Example of "options" config for a horizontalBar chart :
options: {
scales: {
yAxes: [{ticks: {mirror: true}}]
}
}
Doc : http://www.chartjs.org/docs/latest/axes/cartesian/#common-configuration
With reference to the original solution to displaying data value by using HTML5 Canvas fillText()
method in the animation
's onComplete
, the code below will get you what you need:
The key to custom-displaying any chart related data is inspecting the chart's dataset as in this.data.datasets
below. I did this by inspecting where the different values are in this dataset, as well as the position to place them for the fillText method.
Inspecting the chart's dataset: Image
Script (Chart.js 2.0 & up):
var barOptions = {
events: false,
showTooltips: false,
legend: {
display: false
},
scales:{
yAxes: [{
display: false
}]
},
animation: {
onComplete: function () {
var ctx = this.chart.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'left';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
left = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._xScale.left;
ctx.fillStyle = '#444'; // label color
var label = model.label;
ctx.fillText(label, left + 15, model.y + 8);
}
});
}
}
};
jsFiddle: http://jsfiddle.net/jfvy12h9/
You can achieve this effect in chartjs 2.0 + by rotating the labels 90 degrees and applying negative padding, so that the label moves up inside the 'bar'. Something like this:
new Chart(document.getElementById(id), {
type: 'bar',
data: data,
options: {
scales: {
xAxes: [
{
ticks: {
autoSkip: false,
maxRotation: 90,
minRotation: 90,
padding: -110
}
}
]
}
}
});
See the tick configuration documentation for more information.
It seems like there is no direct option for this right now. A possible implementation is iterating over bars/columns by using onAnimationComplete hook. You can view this question for detailed explanations how to display data values on Chart.js
I would like you remind that this has a drawback. Since it uses onAnimationComplete, whenever an animation happens on chart, values will be disappear for a second and appear again.