How to display data values ​​on Chart.js

I would like to ask if this is possible using Chart.js display data values? I want to print a graph.

Thanks for any advice.

+79
javascript
Jul 25 '15 at 21:33
source share
11 answers

Later editing: there is an official plugin for Chart.js 2.7.0+ to do this: https://github.com/chartjs/chartjs-plugin-datalabels

Original answer:

You can cycle through points / bars on the AnimationComplete and display values




preview

enter image description here




HTML

 <canvas id="myChart1" height="300" width="500"></canvas> <canvas id="myChart2" height="300" width="500"></canvas> 

script

 var chartData = { labels: ["January", "February", "March", "April", "May", "June"], datasets: [ { fillColor: "#79D1CF", strokeColor: "#79D1CF", data: [60, 80, 81, 56, 55, 40] } ] }; var ctx = document.getElementById("myChart1").getContext("2d"); var myLine = new Chart(ctx).Line(chartData, { showTooltips: false, onAnimationComplete: function () { var ctx = this.chart.ctx; ctx.font = this.scale.font; ctx.fillStyle = this.scale.textColor ctx.textAlign = "center"; ctx.textBaseline = "bottom"; this.datasets.forEach(function (dataset) { dataset.points.forEach(function (points) { ctx.fillText(points.value, points.x, points.y - 10); }); }) } }); var ctx = document.getElementById("myChart2").getContext("2d"); var myBar = new Chart(ctx).Bar(chartData, { showTooltips: false, onAnimationComplete: function () { var ctx = this.chart.ctx; ctx.font = this.scale.font; ctx.fillStyle = this.scale.textColor ctx.textAlign = "center"; ctx.textBaseline = "bottom"; this.datasets.forEach(function (dataset) { dataset.bars.forEach(function (bar) { ctx.fillText(bar.value, bar.x, bar.y - 5); }); }) } }); 



Violin - http://jsfiddle.net/uh9vw0ao/

+109
Jul 26 '15 at 1:21
source share

Here is the updated version for Chart.js 2.3

September 23, 2016: edited my code to work with v2.3 for line / line type.

Important: Even if you do not need animation, do not change the duration parameter to 0, otherwise you will get chartInstance.controller undefined.

 var chartData = { labels: ["January", "February", "March", "April", "May", "June"], datasets: [ { fillColor: "#79D1CF", strokeColor: "#79D1CF", data: [60, 80, 81, 56, 55, 40] } ] }; var opt = { events: false, tooltips: { enabled: false }, hover: { animationDuration: 0 }, animation: { duration: 1, onComplete: function () { var chartInstance = this.chart, ctx = chartInstance.ctx; ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily); ctx.textAlign = 'center'; ctx.textBaseline = 'bottom'; this.data.datasets.forEach(function (dataset, i) { var meta = chartInstance.controller.getDatasetMeta(i); meta.data.forEach(function (bar, index) { var data = dataset.data[index]; ctx.fillText(data, bar._model.x, bar._model.y - 5); }); }); } } }; var ctx = document.getElementById("Chart1"), myLineChart = new Chart(ctx, { type: 'bar', data: chartData, options: opt }); 
 <canvas id="myChart1" height="300" width="500"></canvas> 
+66
May 31 '16 at 15:43
source share

This animation option works on 2.1.3 on the histogram.

Slightly modified answer by @Ross

 animation: { duration: 0, onComplete: function () { // render the value of the chart above the bar var ctx = this.chart.ctx; ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily); ctx.fillStyle = this.chart.config.options.defaultFontColor; ctx.textAlign = 'center'; 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; ctx.fillText(dataset.data[i], model.x, model.y - 5); } }); }} 
+29
Jul 21 '16 at 21:17
source share

Based on the answer of @Ross answer for Chart.js 2.0 and above, I had to turn on a small setting to protect against the case when the column height is too suitable for the scale border.

Example

Histogram parameter animation attribute:

 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++) { var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model, scale_max = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._yScale.maxHeight; ctx.fillStyle = '#444'; var y_pos = model.y - 5; // Make sure data value does not get overflown and hidden // when the bar value is too close to max value of scale // Note: The y value is reverse, it counts from top down if ((scale_max - model.y) / scale_max >= 0.93) y_pos = model.y + 20; ctx.fillText(dataset.data[i], model.x, y_pos); } }); } } 
+18
Aug 05 '16 at 21:01
source share

I think that the best option to do this in chartJS v2.x is to use a plugin, so you do not have a large block of code in the settings. In addition, it prevents data from disappearing when you hover over the panel.

those. just use this code that registers a plugin that adds text after drawing a chart.

 Chart.pluginService.register({ afterDraw: function(chartInstance) { var ctx = chartInstance.chart.ctx; // render the value of the chart above the bar ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily); ctx.textAlign = 'center'; ctx.textBaseline = 'bottom'; chartInstance.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; ctx.fillText(dataset.data[i], model.x, model.y - 2); } }); } }); 
+17
Aug 03 '16 at 18:28
source share

If you use the chartjs-plugin-datalabels plugin, the following code parameter object will help

Make sure you import import 'chartjs-plugin-datalabels'; in your typescript file or add a link to <script src="chartjs-plugin-datalabels.js"></script> in your javascript file.

 options: { maintainAspectRatio: false, responsive: true, scales: { yAxes: [{ ticks: { beginAtZero: true, } }] }, plugins: { datalabels: { anchor: 'end', align: 'top', formatter: Math.round, font: { weight: 'bold' } } } } 
+8
May 17 '18 at 10:55
source share

Following this good answer , I would use these parameters for the histogram:

 var chartOptions = { animation: false, responsive : true, tooltipTemplate: "<%= value %>", tooltipFillColor: "rgba(0,0,0,0)", tooltipFontColor: "#444", tooltipEvents: [], tooltipCaretSize: 0, onAnimationComplete: function() { this.showTooltip(this.datasets[0].bars, true); } }; window.myBar = new Chart(ctx1).Bar(chartData, chartOptions); 

Bar chart

It still uses the tooltip system and its advantages (automatic positioning, patterning, ...), but hides decorations (background color, carriage, ...)

+7
Feb 25 '16 at 15:49
source share

From the chart.js examples (file Chart.js-2.4.0 / samples / data_labelling.html):

`` `// Define a plugin for providing data labels

  Chart.plugins.register({ afterDatasetsDraw: function(chartInstance, easing) { // To only draw at the end of animation, check for easing === 1 var ctx = chartInstance.chart.ctx; chartInstance.data.datasets.forEach(function (dataset, i) { var meta = chartInstance.getDatasetMeta(i); if (!meta.hidden) { meta.data.forEach(function(element, index) { // Draw the text in black, with the specified font ctx.fillStyle = 'rgb(0, 0, 0)'; var fontSize = 16; var fontStyle = 'normal'; var fontFamily = 'Helvetica Neue'; ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily); // Just naively convert to string for now var dataString = dataset.data[index].toString(); // Make sure alignment settings are correct ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; var padding = 5; var position = element.tooltipPosition(); ctx.fillText(dataString, position.x, position.y - (fontSize / 2) - padding); }); } }); } }); 

`` ``

+6
Feb 22 '17 at 12:39 on
source share

I would recommend using this plugin: https://github.com/chartjs/chartjs-plugin-datalabels

Labels can be added to your charts by simply importing the plugin into a js file, for example:

 import 'chartjs-plugin-datalabels' 

And can be configured using these documents: https://chartjs-plugin-datalabels.netlify.com/options.html

+6
Oct 18 '17 at 4:46 on
source share

Edited by @ajhuddy a bit. For bar charts only . My version adds:

  • Put out the values ​​in the animation.
  • Prevent clipping by positioning the value inside the panel if the panel is too high.
  • Does not blink.

Example

Bottom side: when you hover over a bar whose value is inside, the value may look a bit jagged. I did not find a solution to disable the effects of freezing. It may also be necessary to configure depending on your own settings.

Configuration:

 bar: { tooltips: { enabled: false }, hover: { animationDuration: 0 }, animation: { onComplete: function() { this.chart.controller.draw(); drawValue(this, 1); }, onProgress: function(state) { var animation = state.animationObject; drawValue(this, animation.currentStep / animation.numSteps); } } } 

Helpers:

 // Font color for values inside the bar var insideFontColor = '255,255,255'; // Font color for values above the bar var outsideFontColor = '0,0,0'; // How close to the top edge bar can be before the value is put inside it var topThreshold = 20; var modifyCtx = function(ctx) { ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily); ctx.textAlign = 'center'; ctx.textBaseline = 'bottom'; return ctx; }; var fadeIn = function(ctx, obj, x, y, black, step) { var ctx = modifyCtx(ctx); var alpha = 0; ctx.fillStyle = black ? 'rgba(' + outsideFontColor + ',' + step + ')' : 'rgba(' + insideFontColor + ',' + step + ')'; ctx.fillText(obj, x, y); }; var drawValue = function(context, step) { var ctx = context.chart.ctx; context.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; var textY = (model.y > topThreshold) ? model.y - 3 : model.y + 20; fadeIn(ctx, dataset.data[i], model.x, textY, model.y > topThreshold, step); } }); }; 
+4
Oct 06 '16 at 9:46 on
source share

Based on my experience, as soon as you add the chartjs-plugin-datalabels plugin (be sure to put the <script> after the chart.js tag on your page), your charts will start displaying values.

If you then choose, you can customize it to your needs. The setup here is clearly documented, but basically the format is similar to this hypothetical example:

 var myBarChart = new Chart(ctx, { type: 'bar', data: yourDataObject, options: { // other options plugins: { datalabels: { anchor :'end', align :'top', // and if you need to format how the value is displayed... formatter: function(value, context) { return GetValueFormatted(value); } } } } }); 
+3
Jan 24 '18 at 1:26
source share



All Articles