This video is available to students only

Extra credit

We talk about how to generalize our code, and change it so that we draw multiple histograms for different metrics.

Extra credit#

Let's generalize our histogram drawing function and create a chart for each weather metric we have access to! This will make sure that we understand what every line of code is doing.

Generalizing our code will also help us to start thinking about handling dynamic data — a core concept when building a dashboard. Drawing a graph with a specific dataset can be difficult, but you get to rely on values being the same every time your code runs. When handling data from an API, your charting functions need to be more robust and able to handle very different datasets.

Finished histogram

Here's the good news: we won't need to rewrite the majority of our code! The main difference is that we'll wrap most of the chart drawing into a new function called drawHistogram().

Which steps do we need to repeat for every chart? Let's look at our checklist again.

  1. Access data

  2. Create dimensions

  3. Draw canvas

  4. Create scales

  5. Draw data

  6. Draw peripherals

  7. Set up interactions

All of the histograms will use the same dataset, so we can skip step 1. And every chart will be the same size, so we don't need to repeat step 2 either. However, we want each chart to have its own svg element, so we'll need to wrap everything after step 2 .

In the next section, we'll cover ways to make our chart more accessible. We'll be working on the current version of our histogram - make a copy of your current finished histogram in order to come back to it later.

Let's do that — we'll create a new function called drawHistogram() that contains all of our code, starting at the point we create our svg. Note that the finished code for this step is in the /code/03-making-a-bar-chart/completed-multiple/draw-bars.js file if you're unsure about any of these steps.


This page is a preview of Fullstack D3 Masterclass

No discussions yet