How to add multiple tool tips to a bar chart

2019-08-01 20:32发布

I've been working with a D3 svg chart with built in tool tips (using the d3-tip library I believe). The original code can be seen here: http://bl.ocks.org/Caged/6476579

I've successfully been able to customize it for the most part, but I need to add a second mouseover effect; so that when you mouseover a bar it not only opens the tool tip, but also another tip or layer in the upper right corner of the chart.

I tried to do something like the following, but it doesn't seem to work. Am I just missing something in my syntax? Or will this strategy not work at all?

var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    return "<strong>Frequency2:</strong> <span style='color:red'>" + d.frequency2 + "</span>";
  })

//adding second tool tip
var tip2 = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-40, 0])
  .html(function(d) {
    return "<strong>Other Variables:</strong> <span style='color:red'>" + d.frequency2 + "</span>";
  })

and then

  svg.selectAll(".bar")
      .data(data)
    .enter().append("rect")
      .attr("class", "bar")
      .attr("x", function(d) { return x(d.letter); })
      .attr("width", x.rangeBand())
      .attr("y", function(d) { return y(d.frequency2); })
      .attr("height", function(d) { return height - y(d.frequency2); })
      .on('mouseover', tip.show, tip2.show)
      .on('mouseout', tip.hide, tip2.hide);

The chart still works, but now neither tool tip shows.

1条回答
Evening l夕情丶
2楼-- · 2019-08-01 21:27

What you're doing right now...

.on('mouseover', tip.show, tip2.show)

... will not work. In selection.on, the third argument is the capture:

selection.on(typenames[, listener[, capture]])

Thus, the solution is wrapping both tip and tip2 in another function:

.on("mouseover", function() {
    tip.show();
    tip2.show();
})

Here is a demo (hover over the circle):

var svg = d3.select("svg");

var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 20])
  .html("<strong>Frequency2:</strong> <span style='color:red'>foo</span>")

var tip2 = d3.tip()
  .attr('class', 'd3-tip')
  .offset([90, 20])
  .html("<strong>Other Variables:</strong> <span style='color:red'>bar</span>")

svg.call(tip)
svg.call(tip2)

d3.select("circle").on("mouseover", function() {
  tip.show();
  tip2.show();
}).on("mouseout", function() {
  tip.hide();
  tip2.hide();
});
.d3-tip {
  line-height: 1;
  font-weight: bold;
  padding: 12px;
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  border-radius: 2px;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.7.1/d3-tip.min.js"></script>
<svg>
  <circle cx="50" cy="70" r="20" fill="teal"></circle>
</svg>

查看更多
登录 后发表回答