Data Visualization with D3 - Use Dynamic Scales

Tell us what’s happening:
How come the solution here for the domain on the yScale is

d3.scaleLinear()
.domain([0, d3.max(dataset, (d) => d[1])])

??

The part I’m confused about is on the callback function , why is it d[1]? Doesn’t that refer to the dataset array at index 1? … Which would be the array [109, 280]? … Don’t we need the max of all the numbers in the dataset arrays?

Your code so far

<body>
  <script>
    const dataset = [
                  [ 34,    78 ],
                  [ 109,   280 ],
                  [ 310,   120 ],
                  [ 79,    411 ],
                  [ 420,   220 ],
                  [ 233,   145 ],
                  [ 333,   96 ],
                  [ 222,   333 ],
                  [ 78,    320 ],
                  [ 21,    123 ]
                ];

    const w = 500;
    const h = 500;

    // Padding between the SVG boundary and the plot
    const padding = 30;

    // Create an x and y scale

    const xScale = d3.scaleLinear()
                    .domain([0, d3.max(dataset, (d) => d[0])])
                    .range([padding, w - padding]);

    // Add your code below this line

    const yScale = undefined;


    // Add your code above this line

    const output = yScale(411); // Returns 30
    d3.select("body")
      .append("h2")
      .text(output)
  </script>
</body>

Your browser information:

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

Challenge: Data Visualization with D3 - Use Dynamic Scales

Link to the challenge:

The callback function in this case is used to get the property you want to find the max of for each iterable item in the array if that makes sense, might be clearer looking at an example if you were trying to find the max of an array of objects rather than an array of arrays:

const cats = [
  { name: "Deb", age: 2 },
  { name: "Garfield", age: 10 },
  { name: "Luna", age: 5 },
]

d3.max(cats, (cat) => cat.age) // 10

hope this helps

you are viewing d[1] incorrectly causing your confusion, d[1] is actually the second number in each inner array

//lets look at this
d3.max(dataset, d => d[1])
// d3.max takes our array dataset and and looks at each data array (d) ex [109, 280]
// the function then looks at the 1 index, the second number, giving 280

in short, d is each element in the dataset, not the dataset itself.
Hope this helped! Happy Coding!

Esta incompleta yScale

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