我正在尝试使用 react-chartjs-2 创建一个折线图,当将鼠标悬停在图表中的数据点上时,该折线图有一条垂直线。如下图所示:
Chart requirements
我尝试使用 chartjs-plugin-annotation 插件,但结果喜忧参半。我设法创建了一条静态线,但不了解它的工作原理或原因。我应该如何实现这一目标?我有事吗?
const data = {
labels: [...week(d)],
datasets: [
{
...
data: [10000, 9500, 7000, 4500, 2500, 1500, 500, 0],
}
]
};
var line = [{
type: "line",
mode: "vertical",
// ???
scaleID: "y-axis-0",
value: -20000,
borderColor: "#2984c5",
borderWidth: 1,
}];
const options = {
tooltips: {
xPadding: 20,
yPadding: 10,
displayColors: false,
bodyFontSize: 16,
bodyFontStyle: 'bold',
},
annotation: {
annotations: line,
},
scales: {
yAxes: [{
gridLines: {
drawBorder: false,
tickMarkLength: 0,
},
ticks: {
fontSize: 14,
padding: 15,
max: data.maxY,
min: 0,
maxTicksLimit: 6,
fontColor: "#485465"
}
}],
xAxes: [{
ticks: {
padding: 5,
fontSize: 14,
fontColor: "#485465",
},
gridLines: {
display: false,
},
},
],
},
responsive: false,
}
我可以在这里找到我的完整代码:https://codesandbox.io/s/y28mk3rn4z
最佳答案
只要仔细研究一下这个确切的东西,这就会让你到达那里!它不会填充线的任何一侧,但会创建垂直线!
componentWillMount() {
Chart.pluginService.register({
afterDraw: function (chart, easing) {
if (chart.tooltip._active && chart.tooltip._active.length) {
const activePoint = chart.controller.tooltip._active[0];
const ctx = chart.ctx;
const x = activePoint.tooltipPosition().x;
const topY = chart.scales['y-axis-1'].top;
const bottomY = chart.scales['y-axis-1'].bottom;
ctx.save();
ctx.beginPath();
ctx.moveTo(x, topY);
ctx.lineTo(x, bottomY);
ctx.lineWidth = 2;
ctx.strokeStyle = '#e23fa9';
ctx.stroke();
ctx.restore();
}
}
});
}
同样对于拥有多个数据集的任何人,您可以一次将其添加到所有行的工具提示选项中。
tooltips: {
mode: 'x'
},
关于reactjs - 悬停在图表上时 react-chartjs-2 垂直线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55300288/