ttmt
ttmt

Reputation: 4984

D3 - tooltip to show all values

I have a codepen here - https://codepen.io/anon/pen/rJWeLP

Its a stacked bat chart with a tooltip, when you hover over different blocks it shows the value of that block.

I'm trying to think of a way to show all the vlaues for the differnt blocks in the same tooltip.

So when you hover over the column it will show 3 values for the three blocks in that column.

It is possible to do this with the current way I have built the svg.

.on("mouseover", function() { tooltip.style("display", null); })
.on("mouseout", function() { tooltip.style("display", "none"); })
.on("mousemove", function(d) {
    let xPosition = d3.mouse(this)[0];
    let yPosition = d3.mouse(this)[1];
    tooltip.attr("transform", "translate(" + xPosition + "," + yPosition + ")");
    tooltip.select("text").text(d[1] - d[0]);
});

Upvotes: 1

Views: 628

Answers (1)

Zackary Ridall
Zackary Ridall

Reputation: 41

What I would do is create a separate tooltip array. Looking at your code your it appears that your tooltip is the height of each rectangle in a column so I did something like this:

// This is a messy way to build the tooltip array
var tooltips = [];
stackedSeries.forEach((column) =>{
  let yValues = [];
  column.forEach((point) =>{
    yValues.push(point[1]);
  });
  yValues.sort((a, b) =>{return a - b}) 
  for(let i = 0; i < yValues.length; i++){
    if(i == 0)
      continue;    
    yValues[i] = yValues[i] - yValues[i-1];
  }
  tooltips.push(yValues);
})

Afterwards you can view all the tooltips in the column by adding an i parameter to your mousemove function and using the array we just created.

// Use this for your mousemove function
             function(d,i) {
                let xPosition = d3.mouse(this)[0];
                let yPosition = d3.mouse(this)[1];
                tooltip.attr("transform", "translate(" + xPosition + "," + yPosition + ")");
                tooltip.select("text").text(tooltips[i]);
            });

Upvotes: 1

Related Questions