javascript 如何使用chart.js在图形条上方显示值标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22856209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:53:47  来源:igfitidea点击:

How to display value labels above graph bars using chart.js

javascriptjquerychart.js

提问by user3496929

I am using chart.js,i want to show the label value above the bars, so how do it?

我正在使用chart.js,我想在条形上方显示标签值,那么怎么做呢?

var barChartData = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [{
    fillColor: "rgba(220,220,220,0.5)",
    strokeColor: "rgba(220,220,220,1)",
    data: [65, 59, 90, 81, 56, 55, 40],
  }]
}

回答by kerbasaurus

I had the same problem and decided to write it. Please get my version of chart.js from my forked version on github: Chart.js

我有同样的问题,并决定写它。请从我在 github 上的分叉版本获取我的 chart.js 版本:Chart.js

You can pass the following options:

您可以传递以下选项:

var barChartData = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [{
    fillColor: "rgba(220,220,220,0.5)",
    strokeColor: "rgba(220,220,220,1)",
    data: [65, 59, 90, 81, 56, 55, 40],
  }]
};
var opts = {
    scaleShowValues: true, 
    scaleValuePaddingX: 13,
    scaleValuePaddingY: 13
};
var chrt = document.getElementById('chrtDemo').getContext('2d');
new Chart(chrt).Bar(barChartData, opts);

scaleValuePaddingX and scaleValuePaddingY will shift the value position so you can fine-tune it.

scaleValuePaddingX 和 scaleValuePaddingY 将移动值位置,以便您可以对其进行微调。

You can also pass a dataset of colors to color each bar individually:

您还可以传递颜色数据集来分别为每个条形着色:

var barChartData = {
  labels: ["January", "February", "March"],
  datasets: [{
    fillColor: ["rgba(220,220,220,0.5)", "rgba(220,220,220,0.5)", "rgba(220,220,220,0.5)"],
    strokeColor: ["rgba(220,220,220,1)", "rgba(220,220,220,1)", "rgba(220,220,220,1)"],
    data: [65, 59, 90],
  }]
};