reactjs - 将鼠标悬停在图表上时 react-chartjs-2 垂直线
问题描述
我正在尝试使用 react-chartjs-2 创建一个折线图,当将鼠标悬停在图表中的数据点上时,它有一条垂直线。如下图所示:
我尝试使用 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'
},
推荐阅读
- oracle - 基于前一列值的列值
- ruby-on-rails - Rails 的 Cronjobs 在切换到 asdf 后停止工作
- python - 如何在此函数中修复浮点除法零错误?
- dictionary - 报表生成器 MAP 参数
- python - 运行片刻后,无法在 selenium python 中运行此 url,显示“aw,snap”
- arrays - 使用提供的字符集进行字典排序
- javascript - 使用jquery单击li后如何在li中添加鼠标悬停?
- scala - Scala集合映射var到另一个值
- javascript - React Hooks 和States 遇到问题。尝试制作密码强度计
- ios - 使用 AWS Amplify 隔离用户数据