Chart.js仅绘制y轴直到点

问题描述 投票:-1回答:1

我想知道如何仅将y轴绘制到一个数据集的点。如本例所示:

enter image description here

到目前为止,我已经通过在数据集中添加反向白色背景来尝试使用hacky版本,但是由于我在x轴上有一些偏移,因此白色背景突然切开,并且Y轴上的线条被隐藏了。

有人知道如何遍历每条网格线并指定正确的长度吗?

chart.js chart.js2
1个回答
0
投票

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

const data = [1, 3, 2];
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.getPixelForValue(undefined, index);         
         var yTop = yAxis.getPixelForValue(data[index]);                  
         ctx.save();
         ctx.setLineDash([10, 5]);
         ctx.strokeStyle = '#888888';
         ctx.beginPath();
         ctx.moveTo(x, yAxis.bottom);             
         ctx.lineTo(x, yTop);
         ctx.stroke();
         ctx.restore();
      });      
    }
  }],
  data: {
    labels: ["A", "B", "C"],
    datasets: [{
      label: "My First Dataset",
      data: [1, 3, 2],
      fill: false,
      borderColor: "rgb(75, 192, 192)",
      lineTension: 0.3
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        offset: true,
        gridLines: {
          color: 'white'
        }
      }],
      yAxes: [{
        ticks: {
          beginAtZero: true,
          max: 4,
          stepSize: 1
        }
      }]
    }
  }  
});
canvas {
  max-width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" width="10" height="10"></canvas>
© www.soinside.com 2019 - 2024. All rights reserved.