Get Started with Dataviz Using Chart.js

This week we are introducing Glitch Challenges — a fun new way to get started making apps with Glitch. Every two weeks we will share a new starter app and a few challenges to help you get started making the app your own. For our first Challenge: Data Visualization using Chart.js!

Chart.js is a JavaScript library for making interactive charts and graphs. It provides tools for creating eight different types of charts with any data you want, each with a bunch of customizations to make them pretty, functional, and informative.

For our Chart.js Starter App, we created a bar chart and a pie chart showing population data by continent (courtesy Wikipedia).

In the next section, we describe how the code in this app works. Feeling comfortable with the app? Skip down to "The Challenge" section!

How it works

The code powering this app is in three files: index.html, style.css, and script.js. These three files work together to create the interactive chart experience on the page.

Index.html

index.html contains the scaffolding of the app — the main structure for the elements on the page. This includes a div element for each chart with an empty canvas element inside of it:

<div class="chart-container">
  <canvas id="barChart" aria-label="A bar chart showing continental population" role="img">
  </canvas>
</div>
<div class="chart-container">
  <canvas id="pieChart" aria-label="A pie chart showing continental population" role="img">
  </canvas>
</div>

index.html also contains a link to the Chart.js library in the head section of the document. This link must be included in order to use any of the Chart.js functionality in our app.

<!-- import Chart.js library via CDN, per Chart.js documentation -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.js" defer></script>

Style.css

style.css contains styling information for the page. This is where the purple border around the charts is defined as well as the positioning rules for the div elements that contain the charts.

canvas {
  border: 1px solid purple;
}

.chart-container {
  position: relative;
  height: 40%;
  width: 100%;
  max-width: 600px;
  margin: 10px;
}

Script.js

script.js is where the chart logic lives. The file starts with a data variable that houses an object containing continents and their populations.

// create an object with world population data
const data = {
  'Africa': 1216,
  'Asia': 4436,
  'Europe': 738,
  'North America': 579,
  'Oceania': 39.9,
  'South America': 422
};

While it is common to store data in an object like this (with key-value pairs representing data points), sometimes a JavaScript library will require the data to be structured in a different way in order for it to do its job — in this case, make a chart. Chart.js expects the data to be broken into two arrays, or lists: a list of the "labels" for the data (the keys in the data object) and a list of the "data" associated with those labels (the values in the data object).

If we were to type out these arrays manually, it would look like this:

const continents = ['Africa', 'Asia', 'Europe', 'North America', 'Oceania', 'South America'];
const populations = [1216, 4436, 738, 579, 39.9, 422];

But instead of copy-pasting these arrays directly into the code, in this app we create them dynamically from the data object. This way, if the data changes in the future, the only thing that has to be updated is the data object and the arrays will automagically contain the correct information.

To create these arrays from the data object, we can use some of JavaScript's built-in functionality. Object.keys will return an array of the keys in an object — in this case, an array of continents names, which is what we want for continents. Then, we run a forEach loop over the continents array and add each continent's population value to a separate array called populations.

// create an array of continents to use as labels for the charts
const continents = Object.keys(data);
// now continents = ['Africa', 'Asia', 'Europe', 'North America', 'Oceania', 'South America']

// create an array of populations to use as data values by looping
// through the continents and adding each new value to the array
const populations = [];
continents.forEach((continent) => {
  populations.push(data[continent]);
});
// now populations = [1216, 4436, 738, 579, 39.9, 422]

Bar Chart

Now that the data is in a good format, it's time to make some charts! For the first chart, we create a variable bar (but it could be called anything) and set it to target the HTML element where we want to place the chart. In this case, it's the canvas element with id barChart. Then we create a new Chart and tell it where it's going to live on the page by passing bar as the first parameter.

// initialize a chart and put it in the 'barChart' div
const bar = document.getElementById('barChart').getContext('2d');
const barChart = new Chart(bar, { /* ... */ });

barChart needs more information than just where it's supposed to go in the HTML to make the chart we want. The second parameter to Chart is an object that contains all of the options we want to be included in our chart. These include:

  • type -- the type of chart we're making
  • data -- an object containing the data for drawing the chart
  • options -- additional options

The structure for this object is defined in the Chart.js documentation. Note that the value of an object can itself be another object!

In this chart, we want to specify the data to be visualized. Inside the data object, we set the value of labels to the continents array and define a dataset with populations as the data being charted. We also add styling information, like the color of the bars, the color of the borders, and how wide the borders should be. Lastly, we include options to make sure that the bar chart starts its y-axis at 0.

// initialize a chart and put it in the 'barChart' div
const bar = document.getElementById('barChart').getContext('2d');
const barChart = new Chart(bar, {
  type: 'bar', // make it a bar chart
  data: {
    labels: continents, // use the array of continents as labels
    datasets: [{
      label: 'Population (in millions)',
      data: populations, // use the array of populations to draw bars
      backgroundColor: 'rgba(255, 99, 132, 0.2)', // make the bars translucent red
      borderColor: 'rgba(255, 99, 132, 1)', // make the borders of the bars opaque red
      borderWidth: 1 // set the border width to 1 pixel
    }]
  },
  options: {
    // the y-axis should start at 0
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero:true
        }
      }]
    },
  }
});

Pie Chart

The last bit of script.js creates a pie chart, which is a similar process to creating a bar chart. Can you spot the differences?

// initialize a chart and put it in the 'pieChart' div
const pie = document.getElementById('pieChart').getContext('2d');
const pieChart = new Chart(pie, {
  type: 'pie', // make it a pie chart
  data: {
    labels: continents, // use the array of continents to label each 
    datasets: [{
      data: populations, // use the array of populations to draw pie slices
      // set each pie slice to a translucent color
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ],
      // set the border of each pie slice to the same color as the background
      // of the slice but opaque
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderWidth: 1 // set border width to 1 pixel
    }]
  }
});

All together now:

  • index.html is where we create the skeleton for what's going to appear on the page
  • style.css includes styling information for the page
  • script.js is where the data is defined and charts are created

The Challenge

Like all Glitch apps, you can remix the Chart.js Starter App and customize it to your heart's content. But for those of us who are just learning to code, it can be hard to get started — especially with a library we've never used before! That's where our challenge comes in.

We challenge you to a footrace... around the world!

Just kidding. Our challenge to you is to take the Chart.js starter app and give it your own personal spin. In particular, we are looking to see if you can do any of the following:

  • Replace the data in the starter app with data you find fun or interesting. (If you don't have a dataset in mind, check out Awesome Public Datasets to get some inspiration!)
  • Change the chart colors to match your favorite color palette — bonus points if you add a link to your color inspiration in the README!
  • Use the same data (populations by continent or your own) to create a different type of chart and add it to the page
  • Add custom chart behavior using Chart.js Configurations

After you've made the app your own, submit it using the form below. Please send us a link even if you couldn't get it to work or it's not your favorite thing — we want to see it!

If you have any questions or need help, reach out to us on Twitter @glitch or post your question in the support forums.

Bonus: tips and tricks

Feeling stuck? Fear not! Here are some tips and tricks to help you get started.

  • For this exercise, try to find simple data with just a few data points. More than 10 data points on either of these charts will make them hard to read!
  • You may have to convert your data from CSV to an object. For this project, there should be few enough data points that you can convert it manually by typing your data in the object format. If you want to automate the conversion process, you can do so by finding a CSV-to-JSON converter online.
  • To find some color inspiration, check out Color Hunt to see thousands of color palettes.