如何在Observable Plot中用JavaScript实现鼠标悬停高亮线条?
实现Observable Plot折线图的hover高亮效果
你的图表:

你的原始代码:
linePlot = Plot.plot({ marginLeft: 60, // 图表左侧留白 y: { type: "log", // 设置类型 }, marks: [ Plot.line(data, {x: "timestamp", y: "views", z:"artist", title: d=>`${d.artist}`,}) ] })
实现hover高亮的两种方案:
方案1:更改线条颜色+加粗
通过开启interactive交互,利用数据对象自动添加的hover属性,动态调整线条颜色和宽度:
linePlot = Plot.plot({ marginLeft: 60, // 图表左侧留白 y: { type: "log", // 设置类型 }, marks: [ Plot.line(data, { x: "timestamp", y: "views", z:"artist", title: d=>`${d.artist}`, interactive: true, // 开启hover交互 stroke: d => d.hover ? "#ff3300" : Plot.scale("color")(d.artist), // hover时用高亮红,否则用默认色 strokeWidth: d => d.hover ? 3 : 1.5 // hover时加粗线条 }) ] })
方案2:降低非hover线条透明度
这种方式视觉对比更柔和,突出当前hover的线条:
linePlot = Plot.plot({ marginLeft: 60, y: { type: "log" }, marks: [ Plot.line(data, { x: "timestamp", y: "views", z: "artist", title: d => `${d.artist}`, interactive: true, stroke: Plot.scale("color"), // 保持原颜色比例尺 opacity: d => d.hover ? 1 : 0.3, // 非hover线条透明度降低 strokeWidth: d => d.hover ? 3 : 1.5 // hover时加粗 }) ] })
说明:
- 开启
interactive: true后,当鼠标悬停在某条线上时,该线对应的数据对象会自动带上hover: true属性,其他线条的hover为false - 可以根据需求自定义高亮颜色、线条宽度或透明度参数
内容的提问来源于stack exchange,提问作者new student
相关产品推荐
相关产品推荐

