首页 > 解决方案 > 折线图末尾的范围

问题描述

是否可以在折线图的右侧放置一个范围来比较 2 条线的最后 2 点之间的距离?

在此处输入图像描述

标签: chart.jschart.js2

解决方案


这可以通过自定义插件对 canvas 进行直接绘制调用来实现,我在下面提供了一个示例。请注意,代码根据您的屏幕截图做了很多假设,应将其视为起点,而不是完美的直接解决方案。

let myChart = new Chart(document.getElementById('chart'), {
  type: 'line',
  data: {
    labels: ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
    datasets: [{
      label: 'Group1',
      data: [-1000, -2000, -2000, -3000, -4000, -3000, -5000],
      backgroundColor: '#F48496'
    }, {
      label: 'Group2',
      data: [-4000, -4000, -3000, -6000, -6000, -5000, -9000],
      backgroundColor: '#61B2E9'
    }]
  },
  options: {
    maintainAspectRatio: false,
    layout: {
      padding: {
        right: 100
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  },
  plugins: {
    afterRender: function(c) {
      let
        // calculate difference between values of last two points in first and second datasets.
        d = c.config.data.datasets[0].data[c.config.data.datasets[0].data.length - 1] - c.config.data.datasets[1].data[c.config.data.datasets[1].data.length - 1],
        // position of last point in first dataset.
        xy0 = c.getDatasetMeta(0).data[c.getDatasetMeta(0).data.length - 1]._model,
        // position of last point in second dataset.
        xy1 = c.getDatasetMeta(1).data[c.getDatasetMeta(1).data.length - 1]._model;

      c.ctx.save();

      // draw the line.
      c.ctx.strokeStyle = 'black';
      c.ctx.beginPath();
      c.ctx.moveTo(xy0.x + 10, xy0.y);
      c.ctx.lineTo(xy0.x + 15, xy0.y); // draw the upper horizontal line.
      c.ctx.lineTo(xy0.x + 15, xy1.y); // draw the vertical line.
      c.ctx.lineTo(xy1.x + 10, xy1.y); // draw the lower horizontal line.
      c.ctx.stroke();

      // draw the text.
      c.ctx.font = '20px sans-serif';
      c.ctx.fillStyle = 'black';
      c.ctx.fillText(
        d, // text
        c.chartArea.right + 25, // text x position
        xy0.y + ((xy1.y - xy0.y) / 2) // text y position
      );

      c.ctx.restore();
    }
  }
});
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="chart"></canvas>


推荐阅读