"TypeError: d is undefined" when transitioning on a bar chart with a mouseover event

"TypeError: d is undefined" when transitioning on a bar chart with a mouseover event

我正在努力将过渡添加到我的条形图中,它们从轴开始并上升到所需的高度。我让过渡工作,但鼠标悬停事件不再有效。如果我已经将数据附加到 plwdhBar 对象并稍后在代码中调用它,我很困惑为什么 d 未定义。

看过类似的解决方案后,似乎解决方案是调用条形图条一次,从数据中设置它们,然后添加过渡,然后添加鼠标悬停事件。

这是我目前拥有的:(工作过渡但不工作鼠标悬停,导致 showTooltip(d) 函数出错)

var plwdhBar = svg.append("g")
d3.csv("Data/"+name+".csv").then(function(dataset) {
    plwdhBar.selectAll("plwdhBar") //bar2
        .data(dataset)
        .enter()
        .append("rect")
        .attr("class","plwdhBar")
        .attr("width", 30)
        .attr("fill", bar2Color)
        .attr("x",(d)=>xScale(d.year)+(barW/2)-15)
        .attr("y", h-margin.bottom)
        .transition()
        .duration(200)
        .attr("y",(d)=>yBarScale(d.plwdh))
        .attr("height", (d)=>(h-yBarScale(d.plwdh)) -margin.bottom)
    plwdhBar.on("mouseover",function(d){
        showTooltip(d);
    }).on("mouseout",function(){
        removeTooltip();
    });
}

我也试过取出转换的代码行并制作它:

plwdhBar.transition()
    .duration(200)
    .attr("y",(d)=>yBarScale(d.plwdh))
    .attr("height", (d)=>(h-yBarScale(d.plwdh)) -margin.bottom)

然而,这也导致了 d

的未定义错误

所有情况下的错误都是 TypeError: d is undefined 并且在调用 removeToolTip(d) 函数时出现在第一个代码片段中,而在实现第二个代码片段的情况下错误出现在.attr("y",(d)=>yBarScale(d.plwdh))行。

这是您的 plwdhBar 变量:

var plwdhBar = svg.append("g");

仅此而已,仅此而已。没有数据绑定到它。请记住这一点,因为此信息对于了解这里的问题很重要。

然后你做:

plwdhBar.selectAll("plwdhBar")
    .data(dataset)
    .enter()
    .append("rect")
    //etc...

当然,这会附加您的矩形,如果您在该链中添加侦听器,它将起作用。但请注意这个 不会改变 plwdhBar 的事实,它一直只是 var plwdhBar = svg.append("g");,正如我们最初展示的那样。

因此,当您以后做...

plwdhBar.on("mouseover",function(d){
    showTooltip(d);
})

...你得到错误是因为,当然,这里没有数据。

解决方案:为您的选择命名

例如:

var foo = plwdhBar.selectAll("plwdhBar")
    .data(dataset)
    .enter()
    .append("rect")
    //etc...

现在你可以做:

foo.on("mouseover",function(d){
    showTooltip(d);
})

但是,有一个重要的建议:转换也有一个名为 on 的方法。所以,从主链中删除转换,否则你会得到另一个错误(与这个错误无关)。您可以单独添加过渡:

foo.transition()
    //etc...