Jump to content
Slate Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate Marble
Slate Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate Marble
Sign in to follow this  
Rss Bot

Use Chart.js to turn data into interactive diagrams

Recommended Posts

In theory, creating diagrams is not difficult. Handling the trigonometry required for a pie chart is among the most classic jobs used for training programmers. There are a lot of diagramming libraries vying for developers' attentions right now, but in this article, we're going to focus on how to use open source tool Chart.js.

We will put the library through its paces, creating a set of printable diagrams from randomly generated data. Chart.js is an especially popular web design tool because it offers a unique trade-off between ease of use and advanced features, enabling you to create interactive charts and engaging infographics

With Chart.js, you can choose from eight different chart types to add to your websites with minimal effort. The recently-added animations module enriches the diagrams with snazzy-looking visuals. Let's get started.

Click the icon in the top right of each image to enlarge it.

01. Deploy the library

As use of Chart.js is widespread, you can find its minified version from various CDNs such as Cloudflare. Simply load it with a <script> tag, and ensure that a <canvas> object is nearby – Chart.js does its magic by using the rendering infrastructure provided in this widget.

02. Start initialisation

LqqsyuNehyJEUwLxpD99xi.jpg

First, load up the framework

When the framework is loaded, the next step involves getting a Canvas2D handle pointing at the <canvas> instance created in the preceding step. This can then be used to create a new instance of the Chart() class, which is responsible for data handling, rendering and interaction.

03. Add a data source

line chart

For our line chart, only one DataSet is required

Chart classes take a data pointer which provides one or more DataSet objects containing the actual measurement information. In the case of our line chart, only one DataSet is needed. It comes with the obligatory data element and a few optional parameters governing the actual display process.

04. Stop any flickering

Chart.js comes with sophisticated resizing logic, which – unfortunately – tends to get screen sizes wrong from time to time. Limiting the size of the <canvas> element via CSS, sadly, does not do the trick. Instead, both aspect ratio maintenance and responsivity must be disabled via the options field accompanying the Chart classes constructor.

05. Add layouts

To paraphrase Andrei Tupolev: now that the small one is flying, let us bring up the bigger one. The scaffolding shown accompanying this step 'multiplies' our diagram – instead of working with one Canvas element, we now create a total of four of them and arrange them on the screen in a fashion similar to a LeCroy oscilloscope. Sadly, this does not quite work out as intended.

06. Tame any rendering errors

oSvSvAJzjmZNwEqYLxfBGN.jpg

Wrapper <div> tags enforce a structure from the outside

The safest way to handle Chart.js diagrams in complex layouts involves using wrapper <div> tags. They enforce a structure from the outside, thereby ensuring that the internal layout engine can not do more harm than necessary. In this case, however, ensure to re-enable the responsivity feature.

07. Try bars

ubFMnGNpFbZ58UEkDoGuqD.jpg

Creating bar charts is simple

Always rendering line charts gets tedious quickly. Let's spruce things up by changing the type property to bar, thereby yielding bar diagrams such as the one shown in the figure accompanying this step. We promote the data field to 'global' scope in order to eliminate reuse.

08. Avoid pies

pie charts taking over the screen

Pie charts require special treatment if you don't want them to fill your whole screen

In theory, a pie chart can be rendered along the same lines. Remove the colour properties to prevent uniform appearance, and set the type property to pie. Sadly, this does not quite work out – when done, the pie chart will fill the entire screen. This is caused by a speciality of the pie renderer which uses the 'larger' of the two properties to determine pie radius.

09. Solve the problem

Open the 'index.js' file created in step 1. Begin by specifying the graph type as line and adding the data to be visually represented as shown below.

10. Let Chart.js rescale the diagram

Another approach to solve the problem involves re-disabling the maintainAspectRatio feature. This way, the diagramming engine is allowed to rescale the diagram as it sees fit, ensuring that the entire circle shows up on the screen.

Next page: Finish creating your interactive chart with Chart.js

11. Improve pie colouring

qEZuo2gXs4XSnSWaj6Tv4j.jpg

Adding patterns makes your charts accessible for colour blind users

Chart.js does not contain a random colour generator – if you don't provide a colour array, colours won't change. As designing systems based purely on colours is inefficient – many individuals suffer from colour blindness. A nice way around the problem is the patternomaly library.

12. Use patterns

Actually applying a pattern is not difficult. As shown above, simply instantiate them using the name from the figure and a colour screen to be used as a background. Ensure that the array contains enough elements to cover each member of the data field.

13. Address tooltip issues

RmmSkdAZWDA6TBQwYesX2j.jpg

The tooltip window cannot discern colour information at the moment

Running the program with enabled developer tools finds an interesting problem. When passing the mouse cursor over the chart elements, errors pop up. This is caused by the tooltip window, which is not able to discern colour information from pie elements loaded with a pattern.

14. Overwrite information

The problem at hand can be remedied by overriding parts of the tooltip's element. Chart.js lets you submit event handlers that get called as a tooltip window pops up – overwriting labelColor disables the snooping algorithm responsible for the emission of the warning seen before.

15. Add a title 

Especially when diagrams are intended for export or saving, adding a title improves the meaningfulness of the information displayed. The code shown next to this step takes care of the problem effectively – additional customisation, such as the choice of fonts, can be accomplished with additional parameters.

16. Add one more chart

H6PdR2VSawuJm89TiG56xi.jpg

Make sure you include the Labels array at this point

So far, our diagrams were limited to one bit of information at a time. Adding a second 'level' to a data field motivates Chart.js to create a chart made up of more than one data set. The Labels array is important, as its omission makes the program skip parts of the data.

17. Populate the data array

Generating the label's array can get tedious. If your information is sourced from somewhere where ordinal information is readily available, the data array can also be populated with an array of Point[] fields. In this case, use the syntax shown below.

18. Adjust placement of charts

The above-mentioned spacing problem makes positioning diagrams difficult. Chart.js addresses this problem via the padding attribute found in the options field – it allows you to declare a keep-out zone on each of the four margins of the container, thereby constraining rendering.

19. Set the layout globally

Assigning layout settings to each diagram is tedious. A smarter approach involves the Chart.defaults.global element. It exposes the default settings Chart.js will use for new diagrams, and can save a lot of code if multiple diagrams are to be hosted next to one another.

20. Look at examples

The Chart.js developers provide a set of examples to show the framework in action. Take a look at the various options – the source code, usually, is commented well. The library also comes with extremely detailed documentation. Simply open it in a browser of choice, and navigate to the sector which interests you the most.

This article was originally published in creative web design magazine Web Designer. Buy issue 281 or subscribe here.

Read more:

View the full article

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

×