Project Bar Chart: mouseover argument

So I am trying to do the first project of the data visualisation courses and I managed to render my bar chart.

I tried to create a tooltip so that I can see the data when my mouse is on top of one of the bars and I pass the data into a function.

I thought I was going to use d[0] for the date and d[1] for GDP, but it keeps showing undefined.

I accidentally change the d to i, now it can show the data I wanted.

Now I am confused: d and i under the element “rect” should be the data and the corresponding index, but when the method is on(), it seems not working the way they supposed to? What am I doing wrong? Thank you for the help!
Here is my codepen link: https://codepen.io/kwan19961217/full/MWjMZgp

const req = new XMLHttpRequest();
req.open("GET", 'https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json');
req.send();
req.onload = function() {
  const json = JSON.parse(req.responseText);
  createTable(json.data);
}

function createTable(data) {
  const year = data.map(d => d[0].split("-")[0]);
  const h = 1000;
  const w = 1200;
  const padding = 100;
  const xScale = d3.scaleLinear()
                   .domain([d3.min(year, d => d), d3.max(year, d => d)])
                   .range([padding, w - padding])
  
  const yScale = d3.scaleLinear()
                   .domain([0, d3.max(data, d=> d[1])])
                   .range ([h - padding, padding])
  const tooltip = d3.select("body")
                    .append("div")
                    .attr("class", "tooltip")
                    .attr("id", "tooltip")
           
  
  const svg = d3.select("#table")
                .append("svg")
                .attr("width", w)
                .attr("height", h);
  svg.selectAll("rect")
     .data(data)
     .enter()
     .append("rect")
     .attr("class", "bar")
     .attr("x", (d, i) => xScale(1947 + i / 4))
     .attr("y", (d, i) => yScale(d[1]))
     .attr("width", 1)
     .attr("height", (d, i) => h - yScale(d[1])- padding)
     .attr("data-date", (d, i) => d[0])
     .attr("data-gdp", (d, i) => d[1])
     .on("mouseover", (d, i) => {tooltip.html(`Date: ${i[0]}
                                              GDP: ${i[1]}`)
                                       .attr("data-date", i[0])
                                       .attr("data-gdp", i[1])})
     .on("mouseout", (d, i) => tooltip.html("")
                                      .attr("data-date", "")
                                      .attr("data-gdp", "")
                                 );
  
  const yAxis = d3.axisLeft(yScale);
  const xAxis = d3.axisBottom(xScale);
  
  svg.append("g")
     .attr("transform", `translate(${padding} ,0)`)
     .attr("id", "y-axis")
     .call(yAxis);
  
  svg.append("g")
     .attr("transform", `translate(0, ${h - padding})`)
     .attr("id", "x-axis")
     .call(xAxis);
}

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