ChartJS:在悬停时在两个数据点之间画线

时间:2021-01-08 15:14:59

标签: javascript vue.js chart.js vue-chartjs

enter image description here

大家好,我已经创建了图中所示的图表。

有谁知道在尝试将鼠标悬停在任一数据(红线)上时如何在同一索引的数据集之间画一条线。

我在 VueJS 组件上使用 ChartJS

1 个答案:

答案 0 :(得分:1)

Plugin Core API 提供了一系列可用于执行自定义代码的钩子。您可以使用 CanvasRenderingContext2D.stroke() 直接在 import copy temp_df = copy.copy(original_df) 上画线。

在下面的代码片段中,我使用 canvas 钩子并绘制线条,以防工具提示以其他方式显示。请参阅 afterDraw 文档中的 addPlugin 以了解如何在 vue-chart.js 中添加此类内联插件。

Vue.js
var chart = new Chart('canvas', {
  type: 'line',
  plugins: [{
    afterDraw: chart => {
      if (chart.tooltip._active && chart.tooltip._active.length) {
        const ctx = chart.ctx;
        ctx.save();
        const activePoint = chart.tooltip._active[0];
        const x = activePoint.tooltipPosition().x; 
        const yAxis = chart.scales['y-axis-0'];
        const value1 = chart.data.datasets[0].data[activePoint._index];
        const value2 = chart.data.datasets[1].data[activePoint._index];
        const y1 = yAxis.getPixelForValue(value1);
        const y2 = yAxis.getPixelForValue(value2);
        ctx.beginPath();
        ctx.moveTo(x, y1);
        ctx.lineTo(x, y2);
        ctx.lineWidth = 2;
        ctx.strokeStyle = 'green';
        ctx.stroke();
        ctx.restore();
      }
    }
  }],
  data: {
    labels: ['A', 'B', 'C', 'D', 'E', 'F'],
    datasets: [{
        data: [13, 10, 12, 13, 9, 12],
        backgroundColor: 'rgba(255, 99, 132, 0.2)',
        borderColor: 'rgb(255, 99, 132)',
        fill: false
      },
      {
        data: [10, 7, 9, 10, 6, 9],
        backgroundColor: 'rgba(255, 159, 64, 0.2)',
        borderColor: 'rgb(255, 159, 64)'
      }
    ]
  },
  options: {
    legend: {
      display: false
    },
    tooltips: {
      enabled: false
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});