I have a stacked bar chart that shows years on the X axis, total numbers on the Y axis, and the rect segments are colored by item type. A sample of my data array looks like this:
Item, Tonnes, Year
Wheat, 38913, 2020
Sugar, 23463, 2020
Rice, 23524, 2020
Wheat, 38913, 2019
Sugar, 23463, 2019
Rice, 23524, 2019
The formatted data used by D3 looks like this:
0: {year: 1995, Animal and Vegetable Oil: 38913, total: 3168499, Bananas: 25259, Beverages: 69583, …}
1: {year: 1996, Animal and Vegetable Oil: 44523, total: 3577090, Bananas: 30500, Beverages: 46411, …}
On hover, I'd like to retrieve the colored segment's item and tonnes integer so that I can pass them to a tooltip on hover. But my code seems to only retrieve the year and not the item.
The important part of my D3 code looks like this:
// Set up stack method
const stack = d3.stack().keys(tonnesKeys).order(d3.alphabetical)
// Data, stacked
const series = stack(formattedData);
// Create SVG element
const svg = d3
.select("#mainChart")
.append("svg")
.attr("width", width)
.attr("height", height);
// Add a group for each row of data
const groups = svg
.selectAll("g")
.data(series)
.enter()
.append("g")
.attr("class", "axis")
.call(xAxis)
.call(yAxis)
.style("fill", (_, i) => colors(i))
// Add a rect for each data value
groups
.selectAll("rect")
.data((d) => d)
.enter()
.append("rect")
.attr("x", (_, i) => xScale(i))
.attr("y", (d) => yScale(d[1]))
.attr("height", (d) => yScale(d[0]) - yScale(d[1]))
.attr("width", xScale.bandwidth())
};
The stacked bar chart looks like this:

I would love to achieve a tooltip that shows the item and the int on hover:

Thank you for your time and helping someone who is learning D3,