how to display data values on Chart.js
我想问问是否可以使用Chart.js显示数据值?
我要打印图形。
感谢您的任何建议。
最新编辑:有一个Chart.js
原始答案:
您可以遍历AnimationComplete上的点/条并显示值
预览
HTML
1 2 | <canvas id="myChart1" height="300" width="500"></canvas> <canvas id="myChart2" height="300" width="500"></canvas> |
脚本
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | 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); }); }) } }); |
小提琴-http://jsfiddle.net/uh9vw0ao/
这是Chart.js 2.3的更新版本。
2016年9月23日:修改了我的代码,以适用于v2.3的线条/条形。
重要提示:即使不需要动画,也不要将duration选项更改为0,否则会得到chartInstance.controller是未定义的错误。
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 32 33 34 35 36 37 38 39 40 41 42 43 44 | 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 }); |
1 | <canvas id="myChart1" height="300" width="500"></canvas> |
此动画选项在条形图上适用于2.1.3。
稍作修改的@Ross答案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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); } }); }} |
如果您使用的插件为chartjs-plugin-datalabels,则以下代码选项对象会有所帮助
确保在typescript文件中导入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | options: { maintainAspectRatio: false, responsive: true, scales: { yAxes: [{ ticks: { beginAtZero: true, } }] }, plugins: { datalabels: { anchor: 'end', align: 'top', formatter: Math.round, font: { weight: 'bold' } } } } |
基于@Ross对Chart.js 2.0及更高版本的答案,我不得不进行一些微调以防止在条形的高度也偏向比例边界时出现这种情况。
条形图选项的
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 | 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's 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); } }); } } |
我认为在chartJS v2.x中执行此操作的最佳选择是使用插件,因此选项中没有大量代码。另外,它防止将数据悬停在条形上时数据消失。
即只需使用此代码,该代码将注册一个插件,该插件可在绘制图表后添加文本。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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); } }); } }); |
我建议使用此插件:https://github.com/chartjs/chartjs-plugin-datalabels
只需将插件导入js文件即可将标签添加到图表中,例如:
1 | import 'chartjs-plugin-datalabels' |
并且可以使用以下文档进行微调:https://chartjs-plugin-datalabels.netlify.com/options.html
遵循这个好答案,我将在条形图中使用以下选项:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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); |
这仍然使用了工具提示系统及其优点(自动定位,模板化...),但隐藏了装饰(背景色,插入符号...)
根据我的经验,一旦您添加了chartjs-plugin-datalabels插件(确保将
如果您选择此选项,则可以对其进行自定义以满足您的需求。此处明确记录了自定义内容,但基本上,格式类似于此假设示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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); } } } } }); |
来自chart.js示例(文件Chart.js-2.4.0 / samples / data_labelling.html):
```
//定义一个插件以提供数据标签
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 32 | 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); }); } }); } }); |
```
编辑了@ajhuddy的答案。仅用于条形图。我的版本添加:
- 淡入动画以获取值。
- 如果条形过高,可通过将值放置在条形内来防止剪切。
- 没有眨眼。
缺点:将鼠标悬停在其中具有值的条形上方时,该值可能看起来有些参差不齐。我还没有找到一种解决方案可以禁用悬停效果。根据您自己的设置,可能还需要调整。
配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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); } } } |
助手:
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 32 | // 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); } }); }; |