[英]d3 v4 getting data for bar graph tooltip
I am able to get a tooltip to work by defining the text but for the life of me I cannot get the tooltip to print text from a data file. 我可以通过定义文本来获得工具提示,但是我一生都无法从数据文件中打印文本。 I feel like I am messing up defining d.value even though it is being graphed just fine but I also wonder if there is something with v4 that I don't know about. 我觉得我在搞乱d.value的定义,尽管它被绘制得很好,但是我也想知道v4是否存在我不知道的东西。 I've tried moving the var statement all over the place but nothing seems to help. 我尝试将var语句移到各处,但似乎无济于事。 It usually ends up being a "Cannot read property of undefined" error. 它通常最终是“无法读取未定义的属性”错误。 Any thoughts on what I'm doing wrong? 对我在做什么错有任何想法吗? Thanks. 谢谢。
var tooltip = d3.select("body")
.append("div")
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "hidden")
.text("This works just fine");
/* .text(function(d) { return d.value; }); */
d3.tsv("15.tsv", type, function(error, data) {
if (error) throw error;
x.domain([0, d3.max(data, function(d) { return d.value; })]);
y.domain(data.map(function(d) { return (d.gamedate); }))
.paddingInner(0.1)
.paddingOuter(0.5);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.append("text")
.attr("class", "label")
.attr("transform", "translate(" + width + ",0)")
.attr("y", 15)
.style("text-anchor", "end")
.text("Game Score");
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", 0)
.attr("height", y.bandwidth())
.attr("y", function(d) { return y(d.gamedate); })
.attr("width", function(d) { return x(d.value); })
.on("mouseover", function(d){
return tooltip.style("visibility", "visible");})
.on("mousemove", function(d){return tooltip.style("top", (event.pageY-10)+"px").style("left",(event.pageX+400)+"px");})
.on("mouseout", function(d){return tooltip.style("visibility", "hidden");})
I think the main issue is that event
variable is not defined in the scope of the mousemove
function. 我认为主要问题是在mousemove
函数的范围内未定义event
变量。 You can get the mouse values by doing the following: 您可以通过执行以下操作来获取鼠标值:
.on("mousemove", function(d) {
const [xMouse, yMouse] = d3.mouse(this);
tooltip.style("top", (yMouse) + "px")
.style("left", (xMouse) + "px")
.text(`Gamedate ${d.gamedate} with value ${d.value}`)
})
I made a JSbin in order to show how I got it to work, the data is mocked. 我制作了一个JSbin ,以演示如何使其工作,并模拟了数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.