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

时间:2014-04-04 07:23:58

标签: javascript jquery chart.js

我正在使用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],
  }]
}

1 个答案:

答案 0 :(得分:4)

我有同样的问题并决定写它。请从我的分叉版本github上获取我的chart.js版本: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],
  }]
};
var opts = {
    scaleShowValues: true, 
    scaleValuePaddingX: 13,
    scaleValuePaddingY: 13
};
var chrt = document.getElementById('chrtDemo').getContext('2d');
new Chart(chrt).Bar(barChartData, opts);

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

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

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],
  }]
};