【问题标题】:Chart.js draw y-axis only up to pointChart.js 仅绘制 y 轴直到点
【发布时间】:2020-02-13 01:21:11
【问题描述】:

我想知道如何仅将 y 轴绘制到一个数据集的点。就像在这个例子中一样:

到目前为止,我已经尝试了一个 hacky 版本,在数据集上添加了一个反转的白色背景,但是因为我在 x 轴上有一些偏移,所以白色背景突然切割,并且 Y 轴线变得隐藏了。

有谁知道如何遍历每条网格线并给出正确的长度?

【问题讨论】:

    标签: chart.js chart.js2


    【解决方案1】:

    您可以使用Plugin Core API 在canvas 上直接绘制自己的线条。它提供了不同的钩子,可用于执行自定义代码。在下面的代码 sn-p 中,我使用 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>

    【讨论】:

    • 非常感谢您的回答!我以另一种方式解决了它以供我使用(通过降低不透明度,因此您不会注意到线条重叠),但我接受了答案,因为对于其他有类似问题的人来说,这是一个更好的解决方案! :)
    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 2020-05-10
    相关资源
    最近更新 更多