These are Scott Murray's D3 tutorials (see originals), updated to D3 v7. A note on the updates.

The power of data()

We left off with a simple bar chart, drawn with divs and generated from our simple data set.

Simple bar chart

This is great, but real-world data never looks like this. Let’s modify our data.

Bar chart

We’re not limited to five data points, of course. Let’s add more!

Bar chart

25 data points instead of five! How does D3 automatically expand our chart as needed?

Give 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.

Random Data

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.

Bar chart with random values Bar chart with random values Bar chart with random values

View the source, and you’ll see this code:

This code doesn’t use any D3 methods; it’s just JavaScript. Without going into too much detail, this code:

  1. Creates an empty array called dataset.
  2. Initiates a for loop, which is executed 25 times.
  3. Each time, it generates a new random number with a value between zero and 30.
  4. That new number is appended to the dataset array. (push() is an array method that appends a new value to the end of an array.)

Just for kicks, open up the JavaScript console and enter console.log(dataset). You should see the full array of 25 randomized data values.

Random values in console

Notice that they are all decimal or floating point values (14.793717765714973), not whole numbers or integers (14) like we used initially. For this example, decimal values are fine, but if you ever need whole numbers, you can use JavaScript’s Math.round() method. For example, you could wrap the random number generator from this line

as follows:

Try it out here, and use the console to verify that the numbers have indeed been rounded to integers:

Random integer values in console

Next we’ll expand our visual possibilities with SVG.