Data visualization with Chart.js: An introduction
You can tell powerful stories with data. If you want to visualize data in a blog post, on your site, or in a presentation, there are a few libraries out there that can help you achieve stunning results with relatively little work. Chart.js is one of those libraries. When I’m teaching data at Hyper Island, this is one of the essential tools that’s included in the Data Strategist program. Although less flexible and capable than D3, it’s easier to wrap your head around and to get started with, yet powerful enough to cover more than just your basic needs. In this introductory tutorial we’ll build an interactive graph and get a brief overview of the framework’s cababilities.
What we’ll build
We’re going to create a simple but powerful responsive line graph, visualizing the world population during the last 500 years, and a prediction for 2050:
Number of earthlings (in millions)
We’ll customize the graph to use our own colors, and you’ll be able to click the legends to toggle the visibility of the corresponding lines, as well as hover the points for details. You can download the finished result or view the demo.
What you’ll need
No prior experience with either HTML, CSS or JavaScript is needed to go through this tutorial. Hi beginners 👋 some experience will help you grasp the nuances of what’s going on, but regardless of your level of expertize, coming out on the other side of the tutorial you’ll have a graph. All you need is a text editor (I highly recommend Sublime or Atom).
Wait, what’s Chart.js?
Chart.js is a community maintained open-source library (it’s available on GitHub) that helps you easily visualize data using JavaScript. It’s similar to Chartist and Google Charts. It supports 8 different chart types (including bars, lines, & pies), and they’re all responsive. In other words, you set up your chart once, and Chart.js will do the heavy-lifting for you and make sure that it’s always legible (for example by removing some uncritical details if the chart gets smaller).
In a gist, this is what you need to do to draw a chart with Chart.js:
- Define where on your page to draw the graph.
- Define what type of graph you want to draw.
- Supply Chart.js with data, labels, and other options.
…and you’ll get a beautiful, responsive, graph! Although we won’t dig too deep into changing the design of our graph in this tutorial, Chart.js graphs are highly customizable. As a rule, whatever you see you can affect, and although the charts look good without much customization, you’ll likely be able to realize all your (or someone else’s) design visions with some extra effort.
Step 1: Add Chart.js
First of we need to add Chart.js to our page so that we can use the library. For this project, I’ve prepared a simple playground with a HTML file with only the essentials. Download the starting point and open the folder, and you should see three files:
- index.html
- styles.css
- script.js
I’ve added some basic styling to style.css
, but script.js
is completely empty—this is where we’ll add the code to draw our graph in a moment. For now, open up index.html
in a text editor. To use Chart.js we need to link to the library inside of our head
. You could download the library and host it yourself, but the easiest (and probably fastest) way is to just use a CDN (content delivery network, in this instance a fancy way of saying “nice people who’re hosting the libraries we need”).
If you go to chartjs.org and click on Documentation, you’ll see a link to their recommended CDN. Follow the link, and look for the URL ending with Chart.min.js
. At the time of this writing, the latest version is 2.5.0
:
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
Copy and paste this row onto row 5 in index.html
. After pasting, your head
should look like so:
<head>
<title>World population</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
Step 2: Prepare a place in your HTML to render the chart
The last thing we need to prepare before we can start visualizing our data is to define an area in our HTML where we want to draw the graph. For Chart.js you do this by adding a canvas
element, and setting width
and height
to define the proportions of your graph.
On row 13 in index.html
, copy and paste this row to create your canvas element:
<canvas id="myChart" width="1600" height="900"></canvas>
Notice that we’ve added an id
(myChart
) to the canvas
element that we can later use to reference our designated graph element in JavaScript or CSS. What this ID is set to has no significance for Chart.js; you can name it whatever you want. What matters is that you use the exact same ID when you reference it in JavaScript or CSS. If you’re adding several graphs to a page, just make sure that every ID is unique (you could for example give your graphs more specific names, like populationChart
or regionChart
).
Step 3: Prepare the data
The data we’re using is from Wikipedia’s article on World population, and includes a world population prediction from UN’s World Population Prospects report. Here’s the raw data that we’ll be using:
World historical and predicted populations (in millions)
Region | 1500 | 1600 | 1700 | 1750 | 1800 | 1850 | 1900 | 1950 | 1999 | 2050 |
---|---|---|---|---|---|---|---|---|---|---|
Africa | 86 | 114 | 106 | 106 | 107 | 111 | 133 | 221 | 783 | 2478 |
Asia | 282 | 350 | 411 | 502 | 635 | 809 | 947 | 1402 | 3700 | 5267 |
Europe | 168 | 170 | 178 | 190 | 203 | 276 | 408 | 547 | 675 | 734 |
Latin America | 40 | 20 | 10 | 16 | 24 | 38 | 74 | 167 | 508 | 784 |
North America | 6 | 3 | 2 | 2 | 7 | 26 | 82 | 172 | 312 | 433 |
To draw lines and add labels along axes, Chart.js expects the data to be passed in the form of a set of arrays, like so: [10, 4, 7]
. We’re going to use 6 arrays in total: one for all the year labels to be shown along the X axis (1500-2050) and one array for each region containing the population data. So all we need to do is copy each row in our table above, seperate each value with a comma, and then end and start the list with []-brackets.
The table above, reformatted to arrays, looks like so:
// Our labels along the x-axis
var years = [1500,1600,1700,1750,1800,1850,1900,1950,1999,2050];
// For drawing the lines
var africa = [86,114,106,106,107,111,133,221,783,2478];
var asia = [282,350,411,502,635,809,947,1402,3700,5267];
var europe = [168,170,178,190,203,276,408,547,675,734];
var latinAmerica = [40,20,10,16,24,38,74,167,508,784];
var northAmerica = [6,3,2,2,7,26,82,172,312,433];
Copy all of these rows, and paste them into script.js
.
Step 4: Draw a line!
At last! We’ve arrived at the moment of truth. Visualizing data with Graph.js is pretty straightforward. All we need to do is define what graph we want to draw, and pass in the data that we want to visualize. Let’s start by drawing one single line to see if we can get it to work: below the data that you just pasted into script.js
, add these lines of JavaScript:
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: years,
datasets: [
{
data: africa
}
]
}
});
…open up index.html
in a browser, refresh and… tada! You created a graph! It’s not the prettiest, but hey, it’s rising and it’s looking all professional!
What’s happening in this bit of code? Let’s break it down. First, we locate the canvas
element that we added earlier to our index.html
file (notice "myChart"
):
var ctx = document.getElementById("myChart");
Then, using that canvas
element, we create a line chart (type: 'line'
), and pass along some of our data. labels: years
sets our array of years
(that we created earlier) for the labels along the x-axis, and data: africa
uses our africa
variable to draw the line.
For every line that we want to create, we add another object
to the datasets
array. On every object
we can make a range of adjustments: we can not only pass the data to draw the line, but we can change the name, change the beavior, and change the looks of the line.
Let’s try that right now. You may have noticed that our line is missing a label (it says undefined at the top of the graph), and it’s not very colorful. Boo! Let’s make it ✨👌
Step 5: Style the line
Start out by giving our first line a name. After data: africa
, add a comma and create a new row, and add label: "Africa"
:
data: africa,
label: "Africa"
To set the border color and remove the big gray area below the graph, add another comma after label: "Africa"
and add these two lines:
borderColor: "#3e95cd",
fill: false
Well ain’t that ✨👌 (refresh and you should see a blue line named Africa)!
Step 6: Add the rest of the data
All we need to do now is copy the code for Africa and paste it another four times, adding a comma after every }
. Go through the list of lines and make sure that you use all our region variables (asia
, europe
, etc.), and name the lines accordingly. Once you’re done, it should look something like this:
{
data: africa,
label: "Africa",
borderColor: "#3e95cd",
fill: false
},
{
data: asia,
label: "Asia",
borderColor: "#3e95cd",
fill: false
},
{
data: europe,
label: "Europe",
borderColor: "#3e95cd",
fill: false
},
{
data: latinAmerica,
label: "Latin America",
borderColor: "#3e95cd",
fill: false
},
{
data: northAmerica,
label: "North America",
borderColor: "#3e95cd",
fill: false
}
If you refresh, you should have a graph visualizing the earth’s population over time 🎉 Hooray!
The lines are all the same color though. You can pick any color that you want for a line, but to use the same color scheme as in my example graph, change the borderColor
value for each of the new regions: #8e5ea2
, #3cba9f
, #e8c3b9
, #c45850
.
And with that, you’re done! Your finished graph should look something like this.
Troubleshooting
Are you stuck somewhere? Is something not working? Don’t worry, that happens all the time. First of all, I recommend right-clicking somewhere on your page, selecting Inspect Element (or an equivelent), and then selecting the Console. If you’re using Safari and this option is not showing up: open Preferences, select Advanced, and at the very bottom, check Show Develop menu in menu bar.
As soon as something is not working, get into the habit of checking the console for errors. In this particular case, unfortunately, Chart.js has a tendency to not throw very useful errors. To overcome any obstacles that you can’t resolve by working with the Console, you can compare your code with the intended result after each step:
- Step 1: Add Chart.js (zip)
- Step 2: Prepare a place in your HTML to render the chart (zip)
- Step 3: Prepare the data (zip)
- Step 4: Draw a line! (zip)
- Step 5: Style the line (zip)
- Step 6: Add the rest of the data (zip)
Next steps
Isn’t it amazing how by visualizing data you can take a cluster of disconnected numbers and create small simple stories that are completely intuitive to grasp? If you want to go beyond line graphs and start playing around with different ways of visualizing data, I recommend reading through the Chart.js documentation, or using my collection of Chart.js examples to kickstart your project: 10 Chart.js example charts to get you started.