在每个圆环图Chart.js上显示值

时间:2017-04-25 16:48:08

标签: javascript chart.js

我正在用chart.js做一个图形,我可以把图形工作但我想在图表的每个弧上显示值,但我不能。 我看到了我在互联网上看到的一切,没有任何帮助。

我没有工具提示,而是希望每个弧上都有数据。这可能吗?

我的代码:

var randomScalingFactor = function() {
return Math.round(Math.random() * 100);
};
var car = {
labels: ["January", "February", "March", "April", "May"],
datasets: [{
    data: [
      randomScalingFactor(),
      randomScalingFactor(),
      randomScalingFactor(),
      randomScalingFactor(),
      randomScalingFactor(),
    ],
    backgroundColor: [
        window.chartColors.red,
        window.chartColors.orange,
        window.chartColors.yellow,
        window.chartColors.green,
        color(window.chartColors.black).alpha(0.4).rgbString()
    ],borderColor: [
      'white',
      'white',
      'white',
      'white',
      'white'
    ],
    borderWidth: 5,

}],

  };


window.onload = function() {
var ctx = document.getElementById("chart-area").getContext("2d");
window.myDoughnut = new Chart(ctx, {
  type: 'doughnut',
  data: car,
  showDatapoints: true,
  options: {
    scaleShowLabels: true,
      responsive: true,
      legend: {
          position: 'bottom',
      },
      title: {
          display: true,
          text: 'Idades',
          fontSize:20
      },
      animation: {
          animateScale: true,
          animateRotate: true
      }
  }
});

};

这就是我所拥有的: http://imgur.com/FpICd3d

这是我假装的: http://imgur.com/UX09lbM

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

是的!这绝对可能。

虽然您可以创建自己的插件,但我建议使用名为 Chart.PieceLabel.js 的ChartJS 插件,这样就可以了更容易完成。

用法 在图表选项中添加以下内容

pieceLabel: {
    mode: 'value'
}

var randomScalingFactor = function() {
    return Math.round(Math.random() * 100);
};
var ctx = document.getElementById("chart-area").getContext("2d");
var myDoughnut = new Chart(ctx, {
    type: 'doughnut',
    data: {
        labels: ["January", "February", "March", "April", "May"],
        datasets: [{
            data: [
                randomScalingFactor(),
                randomScalingFactor(),
                randomScalingFactor(),
                randomScalingFactor(),
                randomScalingFactor(),
            ],
            backgroundColor: ['#ff3d67', '#ff9f40', '#ffcd56', '#4bc0c0', '#999999'],
            borderColor: 'white',
            borderWidth: 5,
        }]
    },
    showDatapoints: true,
    options: {
        tooltips: {
            enabled: false
        },
        pieceLabel: {
            mode: 'value'
        },
        responsive: true,
        legend: {
            position: 'bottom',
        },
        title: {
            display: true,
            text: 'Idades',
            fontSize: 20
        },
        animation: {
            animateScale: true,
            animateRotate: true
        }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<script src="https://cdn.rawgit.com/emn178/Chart.PieceLabel.js/master/build/Chart.PieceLabel.min.js"></script>
<canvas id="chart-area"></canvas>