Chart.js - Writing labels inside horizontal bars?

Is there a way in Chart.js to write labels inside horizontal bars in the "horizontalBar" table? As in something like:

this graph

Is something like this possible in Chart.js?

Thanks!

+7
javascript labels
source share
4 answers

Now there is a "mirror" option to make a shortcut inside the panel.

Example configuration "options" for a horizontal chart chart:

 options: { scales: { yAxes: [{ticks: {mirror: true}}] } } 

Doc: http://www.chartjs.org/docs/latest/axes/cartesian/#common-configuration

+9
source share

As for the original solution for displaying the data value using the Canvas fillText() HTML5 method in animation onComplete , the code below will help you what you need:

The key to custom displaying any data related to the chart is checking the chart data set as shown below in this.data.datasets . I did this by checking where the different values ​​in this dataset are located, as well as the position to place them for the fillText method.

Checking Chart Dataset: Image

Script (Chart.js 2.0 and higher):

 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/

+3
source share

You can achieve this effect in chartjs 2.0+ by rotating the labels 90 degrees and applying a negative pad so that the labels move inside the bar. Something like that:

 new Chart(document.getElementById(id), { type: 'bar', data: data, options: { scales: { xAxes: [ { ticks: { autoSkip: false, maxRotation: 90, minRotation: 90, padding: -110 } } ] } } }); 

See the type documentation for more information.

+1
source share

There seems to be no direct choice right now. A possible implementation is column / column iteration using hookAnimationComplete. You can view this question for detailed explanations for displaying data values ​​on Chart.js

I would like you to recall that this has a drawback. Since it uses onAnimationComplete, whenever the animation happens on the chart, the values ​​will disappear for a second and reappear.

0
source share

All Articles