javascript - 缩放交互后如何向面积图添加工具提示
问题描述
我正在 D3 中创建一个面积图,其中包括两个主要功能:
1) 一个时间滑块,用于更改 x 轴上的日期范围并更新图表(类似于刷子缩放)
2) 悬停时出现的工具提示,以显示给定日期的确切值
这两个功能在图表加载时起作用,但是当我通过拖动幻灯片来更改 x 轴范围时,我遇到了一个问题:面积图通过放大新的轴和区域进行转换,但是当我悬停显示工具提示、工具提示位置和值与行/区域的新路径不匹配。
我尝试将创建工具提示对象(附加到focus
var)的所有代码包装在一个函数中,然后在移动滑块时调用该函数。我还尝试将 x 比例存储在一个变量中,该变量在时间滑块移动时更新,并将其传递给drawFocus()
函数。工具提示仍然出现在原始位置。
将链接粘贴到 bl.ock 以获取下面的完整代码,但我认为问题来自tipMove()
函数中的某些内容,每当用户将鼠标悬停在图表上时都会调用该函数。(current_x 存储时间滑块定义的 x 比例):
// function that adds tooltip on hover
function tipMove() {
// below code finds the date by bisecting and
// stores the x and y coordinate as variables
let x0 = current_x.invert(d3.mouse(this)[0]);
let i = bisectDate(data, x0, 1);
let d0 = data[i - 1];
let d1 = data[i];
let d = x0 - d0.date > d1.date - x0 ? d1 : d0;
// place the focus objects on the same path as the line
focus.attr('transform', `translate(${current_x(d.date)}, ${y(d.value)})`);
// position the x line
focus.select('line.x')
.attr('x1', 0)
.attr('x2', x(d.date))
.attr('y1', 0)
.attr('y2', 0);
// console.log(x0)
// position the y line
focus.select('line.y')
.attr('x1', 0)
.attr('x2', 0)
.attr('y1', 0)
.attr('y2', height - y(d.value));
// position the text
focus.select('text').text(d.value).transition() // slowly fade in the tooltip
.duration(100)
.style("opacity", 1);
// show the circle on the path
focus.selectAll('.focus circle')
.style("opacity", 1)
};
完整代码在这里:https ://blockbuilder.org/bendoesdata/99c2ca152f760b6d93c923ee9462f4fa
我希望工具提示在图表放大后跟随线条,而是工具提示跟随线条的原始路径(在剪辑路径中不再可见)。
解决方案
推荐阅读
- python - 数据框中字符串的连接
- docker - Docker compose build args 未传递给 dockerfile
- aws-lambda - 当从另一个 DynamoDB 表作为触发器调用时,Lambda 无法读取 DynamoDB 表
- javascript - 如何使用 Webrtc 和 Firebase 广播(从一个对等点到多个对等点)
- javascript - 以下 JQuery 是否可利用?
- next.js - 如何使用 graphql 在 next-auth 会话中添加额外数据
- uwp - WinUI 列表控件,允许动态项目大小、重新排序和虚拟化
- django - 在 AWS EC2 Amazon Linux 上启动 Django 开发服务器
- flutter - 启动时出现 Flutter LateInitializationError
- spring-boot - 在springboot的elasticsearch中存储@ManytoOne关系