How to use Chart.js

How to use Chart.js

Image for post

Chart.js is a popular open source library that helps us to plot data in web applications. It is highly customizable, but configuring all of its options remains a challenge for some people. Let?s explore it, starting from a simple example and building upon it.

Basic implementation:To keep it simple, I am going to use the CDN version of the library. However, if you are planning on using it with React or Angular, I recommend that you use the npm package and install it via npm install chart.js –save.

We are also going to use jQuery to make the ajax requests.Our basic implementation will plot the revenues data of a restaurant for every day of the week.

Let?s start with the index.html

And myChart.js

Setting the type variable, we could change the line chart into a bar chart, or even a pie chart. All of the different types of charts can be seen here.

As you can see, datasets is an array. That means that we can plot two or more data series in the same chart. We will get back to this possibility later on in the article.

The result of our project so far is:

Image for post

What I don?t like about it:- The Y axis doesn?t start at 0. It starts at 12000, the lowest value in the series;- It is gray and I want other colors;- It doesn?t show data as currency: 20000 -> U$ 20,000.00

So, I made a few modifications:

line 1:float2dollar is a function which formats a float into a currency string:18000 -> U$ 18,000.00

line 14:boderColorand backgroundColor are properties which change the line and area colors.

line 22: beginAtZero: trueforces the axes to start at 0 and not at 12000.

line 23:callback of the ticks of the axes is called every time that a tick is rendered. The value variable is the default value displayed. When we override this callback, we can change the text which is displayed on the axis. Here, we call our float2dollar function.

We can already see the changes:

Image for post

Load data from an Ajax request:

To have a backend which allows us to make a GET request without much work, we will use the package json-server. It can simulate a REST server from a JSON file.

npm install json-server -save

On our node package.json, we will set the npm start script to run the json-server with a 2 seconds delay. Because the data is all local, we will have immediate responses. The artificial delay will help us to simulate a real internet connection.

?start?: ?json-server data.json –delay 2000?,

When we run the npm start script, the service will be available on port 3000.

For that to work, we need to create our data.json file.

We will also require a new div on the html to show a ?Loading? gif and an error message.

To make things more organized, we will create a function getChartData() to separate the ajax request from the button click.

After that we have our loading gif.

Image for post

Now, let?s try a chart with two data series:Suppose we want to compare the revenues of this week with those from last week. Let?s keep the current week?s series in blue and we?ll add last week?s series in gray.

The first thing we need to update is our data.json

Then, we need to change the myChart.js file:

The data that we send to the renderChart function will be an array of two arrays. The first (data[0]) will be the data from this week?s revenues and the second (data[1]) will be the data from the last week.

Finally, the datasets from the chart will have a second object: the series from last week.

The results are pretty nice and make it easy to visually compare the two weeks.

Image for post

Other types of charts:As mentioned earlier, Chart.js provides a wide variety of chart types.

The properties we study here are shared between different types of graphics, with some differences. In the pie chart, for example, instead of passing only one color per series, we may pass an array of colors, since different slices of the pie should have different colors.

Let?s also add a title to the chart using the text property of the title.

The result:

Image for post

Mixing chart typesChart.js allows us to mix two types of chart on the same canvas. Let?s go back to the restaurant example. Now we want to analyze how many clients we had every day, but still see the revenues.

In this example, we can use a bar chart for the clients mixed with a line chart for the revenues.

It is important to point out that, in this case, we will need to use a secondary Y axis. This is because the revenues will be numerically larger than the customers and therefore the bars would be very small on the revenues scale.

For that we will create another file, mixChart.js

To mix types you have to define a main type for the chart and, for the one that you want to change, you have to redefine the variable type inside the individual dataset. For our example, we set the main type as type: ?bar” but, inside the first dataset, we redefine type: ?line”.

yAxesis a property from scales, which is an object of options. This yAxes is actually an array and allows us to use multiple scales for different series. In this example we use two Y axes. For this reason, we need to give an id for each. The first Y axis has id:”revenues” and the second id:”clients”.

We?ve used position: ‘right’ on the client axis to show its ticks on the right side of the chart. To make things more readable, we also add a labelString to each axis, so people may know that the left axis is the revenues, and the right one is the number of clients.

Image for post

Now what?Actually a lot! As you can see, Chart.js is very customizable and we would still have to see many topics to cover all possibilities.

Some examples are:- Show stacked data;- Customize legends;- Customize the tooltips;- Two dimensional data types;- Interactions events (e.g., click);- Logarithmic scale;And more?

Also, there are plugins which improve the use of Chart.js. I think chartjs-plugin-datalabels is particularly useful and would recommend you to take a look at it.

You can check the files used on this article in our GitHub repository.

Let us know in the comments if you would like to read more about chart.js in the future.

24

No Responses

Write a response