We left off with a simple bar chart, drawn with
divs and generated from our simple data set.
This is great, but real-world data never looks like this. Let’s modify our data.
We’re not limited to five data points, of course. Let’s add more!
25 data points instead of five! How does D3 automatically expand our chart as needed?
data() ten values, and it will loop through ten times. Give it one million values, and it will loop through one million times. (Just be patient.)
That is the power of
data() — being smart enough to loop through the full length of whatever data set you throw at it, executing each method below it in the chain, while updating the context in which each method operates, so
d always refers to the current datum at that point in the loop.
That may be a mouthful, and if it all doesn’t make sense yet, it will soon. I encourage you to save the source code from the sample HTML pages above, tweak the
dataset values, and note how the bar chart changes.
Remember, the data is driving the visualization — not the other way around.
Sometimes it’s fun to generate random data values, for testing purposes or pure geekiness. That’s just what I’ve done here. Notice how each time you reload the page, the bars render differently.
View the source, and you’ll see this code:
forloop, which is executed 25 times.
push()is an array method that appends a new value to the end of an array.)
console.log(dataset). You should see the full array of 25 randomized data values.
Math.round() method. For example, you could wrap the random number generator from this line
Try it out here, and use the console to verify that the numbers have indeed been rounded to integers:
Next we’ll expand our visual possibilities with SVG.