如何在Chart.js中为每个点添加垂直线和标签?

时间:2020-04-18 04:39:30

标签: javascript charts chart.js

如何为每个点添加一条垂直线,并使所选数据显示为5.5k标签,如下面的屏幕截图所示?

Chart with vertical lines

1 个答案:

答案 0 :(得分:0)

您可以使用Plugin Core APIcanvas上直接绘制自己的线条。它提供了可用于执行自定义代码的不同钩子。在下面的代码片段中,我使用了afterDraw钩子来绘制垂直线直到数据集中的各个点。

const data = [65, 0, 80, 81, 56, 85, 40];

new Chart(document.getElementById("myChart"), {
  type: 'line',
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      xAxis.ticks.forEach((value, index) => {
        var x = xAxis.getPixelForTick(index);
        var yTop = yAxis.getPixelForValue(data[index]);
        ctx.save();
        ctx.strokeStyle = '#aaaaaa';
        ctx.beginPath();
        ctx.moveTo(x, yAxis.bottom);
        ctx.lineTo(x, yTop);
        ctx.stroke();
        ctx.restore();
      });
    }
  }],
  data: {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
      label: "My First dataset",
      data: data,
      fill: false
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        gridLines: {
          display: false
        }
      }],    
      xAxes: [{
        gridLines: {
          display: false
        }
      }]    
    }
  }  
});
<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js'></script>
<div style="width: 75%">
  <canvas id="myChart" height="90"></canvas>
</div>