如何在数据集切换后在工具提示中添加数据

时间:2016-08-22 10:39:28

标签: javascript d3.js

我的图表中有两个数据集,我通过点击段落切换它们(我稍后会在那里绘制按钮)。数据集具有不同的维度,因此我希望根据所选数据集在工具提示中相互替换。我可以调整工具提示一次

   .on("mouseover", function(d, i) {
    var tickDate = d3.select(d3.selectAll(".axis .tick text")[0][i]).data()[0];
    console.log (tickDate);
    var formatDate = RU.timeFormat("%B %Y");
    var tooltipDate = formatDate(tickDate);
    //Get this bar's x/y values, then augment for the tooltip
    var xPosition = parseFloat(d3. select(this). attr("x")) + ((barWidth - barPadding) / 2);
    var yPosition = parseFloat(d3. select(this). attr("y")) / 2 + h / 2;
    //Update the tooltip position and value
    d3.select("#tooltip" )
      .style("left" , xPosition + "px")
      .style("top" , yPosition + "px")
      .select("#value")
      .text(d + " DIMENSION1");
    d3.select("#tooltip" )
      .select("#label")
      .text(tooltipDate);
    //Show the tooltip
    d3.select("#tooltip" ).
      classed("hidden" , false);
    d3.select(this)
      .attr("fill", "orange");
  })

但切换后我无法刷新它。现在两种情况都有文字“DIMENSION1”,我的目的是切换后的文字“DIMENSION2”,并在选择初始数据集后返回“DIMENSION1”。

这是我的小提琴:https://jsfiddle.net/anton9ov/dw1xp1ux/

1 个答案:

答案 0 :(得分:1)

这里有几个问题:

  • 通过创建一个调用过渡的函数transition(dataset, dimension)来避免代码重复

  • 更改数据集时,您不会更新mouseover事件。因此,每次更新数据时都要调用鼠标悬停功能

    svg.selectAll("rect").on("mouseover", function(d, i) {
           // Your mouseover function
        }); 

看到这个小提琴https://jsfiddle.net/bfz97hdw/ (我还修复了颜色问题)

相关问题