parastoo
parastoo

Reputation: 382

adding tooltip to group bar chart d3 v4

I'm working on this reference and I changed it according to my data. I need to add a tooltip to each bar according to its value.

Can someone tell me how I can do that?

I've tried this example but could not make it work.

  svg.selectAll(".bar")
      .data(data)
    .enter().append("rect")
      .attr("class", "bar")
      .attr("x", function(d) { return x(d.letter); })
      .attr("width", x.rangeBand())

//I don't know how to show each value on its bar

      .attr("y", function(d) { return y(d.frequency); })
      .attr("height", function(d) { return height - y(d.frequency); })
      .on('mouseover', tip.show)
      .on('mouseout', tip.hide)

This is a Plunker I created.

Upvotes: 2

Views: 1943

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102219

Here are the steps:

First, reference the library:

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.7.1/d3-tip.min.js"></script>

Then, create the tooltip:

var tip = d3.tip()
    .attr('class', 'd3-tip')
    .offset([-10, 0])
    .html(function(d) {
        console.log(d)
        return "<strong>Name:</strong>" + d.key + "<br><strong>Value:</strong>" + d.value;
    });

Finally, call it:

svg.call(tip);

Here is the updated plunker: http://plnkr.co/edit/sVrtBsfn2eGbCbhbNZ4j?p=preview

Upvotes: 2

Related Questions