ttmt
ttmt

Reputation: 4984

D3 - Stacked bar chart, show all values in tooltip

I have a stackblitz here - https://stackblitz.com/edit/bar-tooltip?embed=1&file=src/app/bar-chart.ts&hideNavigation=1

When you hover over the bars the tooltip shows the value for that section of the stacked bar.

Is it pssible to hover anywhere on the bar and show all 3 values in the tooltip.

Upvotes: 0

Views: 1586

Answers (1)

Shashank
Shashank

Reputation: 5670

Here's one approach to do that:

In the mouseover function, use the bound data's data attribute to fetch all the key values.

.on("mousemove", (d:any)=>{
    var html = '';
    that.keys.forEach(function (k) {
      html += k + ': ' + d.data[k] + '<br/>';
    });
    d3.select('.chart-tooltip')
        .html(html.trim())
}); 

And for the above to work, I assigned the keys to a variable like this:

private keys = ['one', 'two', 'three'];

Also tweaked the CSS a bit:

.chart-tooltip{
  background: red;
  color: white;
  width: 80px;
  height: auto;
}

And here's a fork of your code with the above changes:

https://stackblitz.com/edit/bar-tooltip-zcqvvt?file=src/app/bar-chart.ts

Hope this helps.

Upvotes: 1

Related Questions