【问题标题】:Range at the end of the line chart折线图末尾的范围
【发布时间】:2018-09-28 15:30:00
【问题描述】:

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

【问题讨论】:

  • 本来是不可能的,也没有任何chart.js插件可用..据我所知。但是,如果您对 HTML5 Canvas 有任何经验,您可以自己绘制。

标签: chart.js chart.js2


【解决方案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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多