使用mouseover和mouseout时如何在多个折线图中显示每个变量名? (d3.js)

时间:2019-06-07 17:01:33

标签: javascript d3.js svg

当鼠标悬停在行上时,我想显示每个变量名称,这是文本,我使用mouseover和mouseout方法来触发它,但是在折线图上没有显示任何变量名称的文本,并且它也没有在控制台上不会弹出任何错误消息。

 var margin = {top: 10, right: 80, bottom: 30, left: 60},
      width = 960 - margin.left - margin.right,
     height = 600 - margin.top - margin.bottom; 

 svg.selectAll(".line")
    .data(sumstat)
    .enter()
    .append("path")
    .attr("fill", "none")
    .attr("stroke", function(d){ return color(d.key) })
    .attr("stroke-width", 1.5)
    .attr("d", function(d){
      return d3.line()
        .x(function(d) { return x(d.Year); })
        .y(function(d) { return y(+d.Price); })
        (d.values)
        })
    .on("mouseover", function(d, i) {
          svg.append("text")
            .attr("class", "title-text")
            .style("fill", function(d){ return color(d.key) })  //it will return the different colors based on different variable names   
            .text(d.key) //it will return the different variable names   
            .attr("text-anchor", "middle")
            .attr("x", (width-margin)/2)
            .attr("y", 5);
        })
    .on("mouseout", function(d) {
          svg.select(".title-text").remove();
        })

我希望变量名称(例如城市名称)是文本,当我使用鼠标将鼠标悬停在这条线上时,它将显示在折线图上;如果鼠标移至同一折线图上的另一条线,则它将显示当前的变量名(即先前的变量名)将消失。因此,我认为在这种情况下,它可以使用“ mouseover”和“ mouseout”方法,但是现在当鼠标悬停在每一行时它无法显示任何内容,并且也不会弹出任何错误消息。

0 个答案:

没有答案