Chart.JS is a powerful library to easily create interactive charts
I’ve got a confession to make. I love charts.
Charts help to break down complex correlations into nice and easily understandable visualizations. Charts can summarize large datasets to better visualize trends, correlations, and dependencies — and it's more fun than reading through tables.
Let’s take an example tackling the most important question of humanity and answer it with a chart visualization. Do you like doughnuts?
I asked 100 people to answer this question.
- 69 people said “YES”’
- 17 people said “YES, but only the ones with chocolate”
- 7 people couldn’t give an answer because they were eating doughnuts
- 5 people said “I am on diet, but I love them. I want a doughnut so bad right now!!!! GIVE ME DOUGHNUTS !”&%!==”!”§!”
- 2 people said “Doughnuts are the devil, but I love hell”
What could fit better than a doughnut chart to visualize this?
We need to set up a basic HTML file and follow two preparation steps. First, we need to include Chart.JS itself within a script tag and second, we need to add a canvas with an ID.
I like Chart.JS for its clean and easy maintenance. You can define everything you need for your chart creation in a JSON structure which makes it easy to define all different kinds of settings, labels, datasets, and magic. Let’s go through step by step.
We are generating the chart with the new Chart command in line 1 and put it into the HTML canvas (which was queried with the myDoughnutChart variable).
In line 2 we can define the type of the chart. In this case, we choose ‘doughnut’, but Chart.JS offers a lot of choices from classical bar charts to pie charts to special stuff like radar charts and much more.
In the data object, we can define the labels (line 4) and datasets (lines 5–8). The datasets array is very interesting and powerful. We can not only define the data itself (line 6), but also different kind of color settings (line 7). Additionally, we can define more than one dataset which is a very nice feature for bar charts, but however not really useful for doughnut charts.
Next to data, labels, and colors, we can specify various set of options. In this case, let’s keep it simple and only include a chart title “Do you like doughnuts?” (line 11–13).
If you are interested in different kinds of charts, options, settings, and more magic with Chart.JS you can watch my video below. The video takes you on a journey of creating the four charts from my title picture: one bar chart, one radar chart, one pie chart, and the doughnut chart, and you will learn a lot.