Data Visualization with D3 - Dynamically Set the Coordinates for Each Bar

I am curious why do we multiply by 30 instead of adding by 30? I checked the results of adding by 30 to see it is incorrect but I am not sure why?

Tell us what’s happening:
Describe your issue in detail here.

Your code so far

<body>
  <script>
    const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];

    const w = 500;
    const h = 100;

    const svg = d3.select("body")
                  .append("svg")
                  .attr("width", w)
                  .attr("height", h);

    svg.selectAll("rect")
       .data(dataset)
       .enter()
       .append("rect")
       .attr("x", (d, i) => {
         // Add your code below this line
       return i * 30  


         // Add your code above this line
       })
       .attr("y", 0)
       .attr("width", 25)
       .attr("height", 100);
  </script>
</body>

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36

Challenge: Data Visualization with D3 - Dynamically Set the Coordinates for Each Bar

Link to the challenge:

The reason for multiplying by 30 instead of adding by 30 is to create a fixed spacing between each bar on the x-axis.

Thank you that makes sense. So would adding them compound each number on the x-axis?

1 Like

If you were to add 30 instead of multiplying by 30, it would result in a compound effect where each subsequent bar’s x-coordinate would be incremented by an additional 30 units.By using multiplication, you ensure that each bar’s x-coordinate is spaced out evenly by a fixed amount. In this case, each bar is positioned at an x-coordinate that is a multiple of 30.This ensures that the bars are evenly spaced out horizontally, creating a clear distinction between them. If you were to add 30 instead, the bars would be stacked directly next to each other, resulting in a different visual representation.

1 Like

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