折线图末端的范围

时间:2018-09-28 15:30:01

标签: chart.js chart.js2

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

enter image description here

1 个答案:

答案 0 :(得分:1)

这可以通过制作direct draw calls to the 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>