D3 tooltips not accessing data (undefined)

I have implemented the tooltip but for some reason it’s just showing
“undefined $undefined Billion” as the tooltip so it isn’t accessing the variables that I have defined or not accessing them properly.

Haven’t found anything online that suggests I’ve done anything wrong which makes me think this is maybe something to do with the new version of d3 changing something… or I’m just missing something. Any help would be appreciated as I simply do not understand how the way I’ve done it is wrong.


//Design variables
var width = 800;
var height = 400;
var barWidth = width / 275;

//Chart creation
var svg = d3.select(".bar-chart").append("svg").attr("height", height + 60).attr("width", width + 100);
var barChart = svg.append("g");
var tooltip = d3.select(".bar-chart").append("div").attr("id", "tooltip").style("opacity", 0);
  .then(data => {
    //Data variables
    var gdp = data.data.map((item) => item[1]);
    var gdpMax = d3.max(gdp);
    var dates = data.data.map((item) => item[0]);
    var yScale = d3.scaleLinear().domain([0, gdpMax]).range([height, 0]);
    var xScale = d3.scaleTime().domain(d3.extent(dates, (d) => new Date(d))).range([0, width]);
    var axisX = d3.axisBottom().scale(xScale);
    var axisY = d3.axisLeft().scale(yScale);
      .attr("class", "bar")
      .attr("transform", "translate(50,20)")
      .attr("height", (d) => height - yScale(d))
      .attr("width", barWidth)
      .attr("x", (d, i) => barWidth * i)
      .attr("y", (d) => yScale(d))
      .attr("data-gdp", (d, i) => data.data[i][1])
      .attr("data-date", (d, i) => data.data[i][0])
      .on("mouseover", (d, i) => {
          .style("opacity", 1)
          .html(dates[i] + "<br>" + "$" + gdp[i] + "Billion")
      .on("mouseout", function () {
          .style("opacity", 0);

    //X axis
      .attr("id", "x-axis")
      .attr("transform", "translate(50," + (height + 20) + ")")

    //Y axis
      .attr("id", "y-axis")
      .attr("transform", "translate(50, 20)")
  .catch((error) => console.log(error));

Hi @aidansabin
Check the d3 v6 migration guide here. I suggest you console.log(i). You will notice it is the data itself not the index.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.