Home Data Learn Chart.js

Learn Chart.js

By Helder da Rocha
books-svg-icon Book
eBook $22.99 $15.99
Print $32.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $22.99 $15.99
Print $32.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Introduction
About this book
Chart.js is a free, open-source data visualization library, maintained by an active community of developers in GitHub, where it rates as the second most popular data visualization library. If you want to quickly create responsive Web-based data visualizations for the Web, Chart.js is a great choice. This book guides the reader through dozens of practical examples, complete with code you can run and modify as you wish. It is a practical hands-on introduction to Chart.js. If you have basic knowledge of HTML, CSS and JavaScript you can learn to create beautiful interactive Web Canvas-based visualizations for your data using Chart.js. This book will help you set up Chart.js in a Web page and show how to create each one of the eight Chart.js chart types. You will also learn how to configure most properties that override Chart’s default styles and behaviors. Practical applications of Chart.js are exemplified using real data files obtained from public data portals. You will learn how to load, parse, filter and select the data you wish to display from those files. You will also learn how to create visualizations that reveal patterns in the data. This book is based on Chart.js version 2.7.3 and ES2015 JavaScript. By the end of the book, you will be able to create beautiful, efficient and interactive data visualizations for the Web using Chart.js.
Publication date:
February 2019
Publisher
Packt
Pages
284
ISBN
9781789342482

 

Chapter 1. Introduction

This is a book about data visualization using JavaScript with Chart.js, one of the most popular data visualization libraries, and also one of the easiest to use. Chart.js provides ready-to-use interactive visualizations for your data with minimal coding. After loading your data into a standard JavaScript array, you can add styles and other configuration using simple object-based declarative structures. Chart.js automatically scales your data, generates ticks and grid lines, creates interactive tooltips, and fits the available space, making your chart automatically responsive. It's a great way to start creating data visualizations for the Web.

Chart.js is free, open source, and maintained by an active community of developers on GitHub. As a data visualization library, it is in second place on GitHub in terms of the number of stars it has. First place belongs to D3.js, a much larger and complex library with a steep learning curve. You still need to know JavaScript, HTML, and CSS to use Chart.js, but you don't have to be a guru. Besides JavaScript, it's also based on other Web standards, such as DOM, CSS, and Canvas. Charts are automatically rendered in Canvas and control all canvas configuration, resizing, and pixel ratios. The only thing you need to know about Canvas is how to include a <canvas> tag in your page and obtain a context, but Canvas knowledge can be useful in advanced charts.

This book assumes you know some JavaScript, HTML, and CSS. The next chapter provides a quick refresher on specific topics and the main technologies you are likely to encounter while learning Chart.js. You can skip it and jump straight to Chapter 3Chart.js – Quick Start, if you wish. This chapter provides a brief introduction to data visualization and data visualization frameworks, and gives an overview of the rest of the book.

This chapter will cover the following topics:

  • Data visualization
  • Why use a data visualization library?
  • How to use this book
 

Data visualization


Visual representations provide data with contexts that stimulate the viewer's brain, revealing information that is usually not obvious from tabular data. It's normally much more natural to capture the substantive content of data using visual artifacts. Charts and maps are a powerful, clear, and effective means to tell stories through data. They can pack huge quantities of information in small spaces and make it easier to compare data, provide insights, and reveal trends, relationships, causality, and other patterns hidden in the numbers.

Charts reveal and emphasize data by attracting the viewer's attention. They can simplify complex data sets to foster discovery and comprehension, helping viewers to analyze and reason about data in different contexts. But they can also exaggerate, mislead, and even lie. A visually attractive chart is important, but designers should discover how to achieve a balance between form and function.

Data visualization is both an art and a science. A chart does not need to explain everything. It doesn't always have to be precise. It may be directed toward a specific audience, which should provide the context necessary to understand and decode it.

Chart types

Data visualization usually refers to the visual display of quantitative information, as in statistical and information charts, plots, data maps, and so on. but it can include any kind of visual representation of data, such as mathematical graphics, path networks (subway systems, roads, electronic circuit diagrams), word clouds, musical and sound representations, timelines, geographical information systems, chemical and atomic diagrams, or any other way of coding of data using visual artifacts.

 

 

You can create any type of visualization if you use a data-driven library such as D3.js. A charting library such as Chart.js, which comes with a set of pre-configured formats, is more limited, but much easier to use.

Chart.js supports eight basic types of chart:

  • Bar (horizontal and vertical)
  • Line/area (including stacked)
  • Radar (radial line)
  • Polar area (radial bar)
  • Scatter
  • Bubble
  • Pie
  • Doughnut

It doesn't offer support for network diagrams, trees, or geographical maps, but you can create Chart.js visualizations that share data with other graphics. In Chapter 4, Creating Charts, we will create a bubble chart, representing populations of cities around the world, and plot them on a map with Chart.js.

Choosing a chart

Choosing a chart requires knowing your data. Charts are a means of communication aimed at revealing information, so the main question is: what do you want to show? Once you've answered that question, you should analyze your data and discover what kind of data you have. Data values used in visualizations can usually be classified as one of these three types:

  • Quantitative: A value that can be measured or counted (a number, a length, an area, an angle)
  • Ordinal: A value can be ranked or compared (color saturation, area, angle, length, words)
  • Nominal: A category (a name)

What is the purpose of you chart? Do you wish to reveal relationships, trends, or causality? What kind of relationship do you wish to emphasize? Do your variables relate to time or space?

 

Visualizations can be organized into categories, which make it easier to choose the kind of chart you need. Most charts and maps can be placed in one of these categories:

  • Time-series (plots a single variable over a period of time). For example, a line chart that demonstrates a trend.
  • Temporal/linear (categories placed in a time-line). For example, a series of events.
  • Spatial/planar/volumetric (categories distributed in a spatial map). For example, a cartogram or choropleth with data distributed on a geographical map.
  • Comparison (categories associated with quantities are compared and ranked during a single period). For example, a bar chart that compares values.
  • Part-to-whole (categorical subdivisions as ratio to a whole). For example, a pie chart with slices as percentages.
  • Correlation (comparing two or more variables). For example, a scatterplot comparing two variables, or a bubble chart comparing three.

In his classic book, The Visual Display of Quantitative Information, Edward Tufte defines some aspects that can be used to measure the quality and integrity of visualizations. They are the following:

  • Data-ink ratio: The amount of ink (or pixels) dedicated to the data shown
  • Chartjunk: Visual garbage that is irrelevant to the data shown (and that frequently get in the way)
  • Lie factor: A number that measures the integrity of a visualization; for example, charts that lie by not representing proportions and lengths with enough precision

The data-ink ratio can be improved by removing chart-junk such as unnecessary lines and labels from charts. Sometimes the lines are important for context, but in interactive Web visualizations you can be very minimalistic. You can always provide details of demand with tooltips or other interactive resources.

Communication is deeply affected by the way humans perceive graphics, and may be improved or distorted by optical illusions. There are no charts with a lie factor of zero, but an adequate choice can improve it significantly. A bad choice increases the lie factor and can induce viewers to false perceptions.

Position and length are best for representing quantitative information. Direction and angles come next, then area, volume, curvature, and finally shadows, saturation, and color. Since lengths and positions are easier to perceive and compare than angles and areas, data in a bar chart is perceived with greater accuracy than the same data in a pie chart. Consider the following pie chart, which compares the areas of continents:

A pie chart comparing areas of continents

Now look at the exact same data represented in a bar chart:

A bar chart comparing areas of continents

Which one is clearer? While the pie chart is good for showing proportions, angles are much harder to compare. Differences in length are much easier to compare and a bar chart is better in this case. But it would probably be clearer to use a pie chart to compare two values as part of a whole, such as the area of one continent compared to the remaining area, to reveal the proportion of land it occupies compared to the rest of the planet.

To have both proportions and lengths, you might be tempted to try a single stacked bar chart, but it still rates worse than the simple bar chart, since stacked bars aren't as easy to compare as when they are placed side-by-side:

A stacked bar chart comparing areas of continents

Of course, you can choose a chart for other reasons, but it's important to know what you lose and gain in each case. Analytic and exploratory visualizations require a high degree of accuracy, but you might want to use a more attractive visualization at the price of losing some accuracy if you need to capture the attention of your audience.

 

Web-based visualizations

When Edward Tufte wrote his classic books on data visualization, most of it was intended for printed media. Today, you can create visualizations that use data that can be updated in real time, with dynamic interfaces that allows interaction by the user. The design guidelines for web-based visualizations are different. They can and should be dynamic and interactive. Interactive charts can pack in much more information by hiding the details, which can be requested by the user on demand. Charts are sometimes rendered as overviews or sparklines, only revealing details through strategies such as zooming and brushing.

 

Why use a data visualization library?


Actually, you don't need any coding to create fantastic and interactive visualizations for the web. You can always use a charting service. There are many; some are paid, others are free. They offer configuration screens and data transformation tools that allow you to create all kinds of beautiful charts. Popular services include Google Charts, Tableau, Infogram, and Plotly. If they fully satisfy your data visualization needs, you don't really need this book.

But if you know HTML, CSS, and JavaScript, you don't need to use these platforms. Web standards provide all the tools you need to create any sophisticated graphics, with no restrictions imposed by a platform or a plan. Using web standards also facilitates the integration of your visualizations with web applications, frontend frameworks (such as React, Angular, and Vue) and backend web services (such as resources and data provided by RESTful services).

But do you really need to use a library like Chart.js? Can't you just use standard JavaScript, HTML, CSS, and Canvas?

Creating data visualizations for the Web

You don't really need any libraries or frameworks to create and display interactive and animated data visualizations on the Web. Plain standard HTML, CSS, and JavaScript already do that for you. Basic HTML provides structural elements that can be styled with CSS to display simple graphical elements such as colored rectangles. That means you can create a basic static bar chart just applying different widths in CSS to div elements.

 

 

Take a look at the following HTML and CSS code:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #data {
            width: 600px;
            border: solid black 1px;
            padding: 10px;
        }
        .label {
            display: inline-block;
            width: 60px;
        }
        .bar {
            display: inline-block;
            background: red;
            margin: 2px 0;
            text-align: right;
            padding-right: 5px;
            color: white;
        }
        #data .bar1 { width: 500px; }
        #data .bar2 { width: 200px; }
        #data .bar3 { width: 300px; }

    </style>
</head>
<body>

<h1>Bar chart</h1>
<div id="data">
    <div><span class="label">Item 1</span><span class="bar bar1">50</span></div>
    <div><span class="label">Item 2</span><span class="bar bar2">20</span></div>
    <div><span class="label">Item 3</span><span class="bar bar3">30</span></div>
</div>

</body>
</html>

If you run it in a web browser, you get the following chart:

A simple static bar chart created with just HTML and CSS

Of course, this is not the best way to draw a bar chart. The numbers were inserted somewhat arbitrarily in the HTML, and the lengths are defined by CSS width properties. You have to calculate the scales yourself. It's easy to make a mistake and reveal the wrong numbers. This is just to illustrate that all the graphical tools already exist in HTML and CSS. All we need is a library that generates that code for us.

Since the Document Object Model (DOM) allows scripting languages to access and change style attributes of an element, widths can be specified in JavaScript and can even respond to events or change with time, allowing the creation of interactive graphics with animation. Adding the following JavaScript function to the previous chart, you can the change value, length, and colors of the bars when the user clicks on the chart using standard DOM commands:

 <div id="data" onclick="changeData()">...</div>
 <script>
     function changeData() {
         let chart = document.getElementById("data");
         let elements = chart.children;
         let values = [5, 35, 15];
         for(let i = 0; i < values.length; i++) {
             let labelElement = elements[i].children[1].innerText = 
             values[i];
             elements[i].children[1].style.background = "blue";
             elements[i].children[1].style.width = values[i] * 10 + "px";
         }
     }
 </script>

 

The following screenshot shows the same chart as the preceding one after clicking, with new colors and values:

An interactive bar chart created with the standard DOM, CSS, HTML, and Javascript

But you don't have to use div and CSS to draw bars. Since HTML5, you can also use the Canvas API—a complete graphical library that can be used to create any kind of graphics, not just rectangles. The following example displays the same data as a pie chart using only standard HTML and no extra libraries:

<canvas id="chart" height="200" width="400"></canvas>

<script>
    const canvas = document.getElementById('chart');
    const ctx = canvas.getContext('2d');
    const rad = Math.min(canvas.height, canvas.width) / 2;

    const data = [100, 100, 100];
    const comp = n => Math.floor(Math.random() * 255);
    const colors = function() {
        return "rgba("+comp()+","+comp()+","+comp()+",0.5)";
    };

    let angle  = 0.0;
    let total  = data.reduce((a, b) => a + b, 0);

    for (var i = 0; i < data.length; i++) {
        ctx.fillStyle = colors();
        ctx.strokeStyle = 'white';
        ctx.lineWidth = 4;
        ctx.beginPath();
        ctx.moveTo(rad, rad);
        ctx.arc(rad, rad, rad, angle, angle + 
               (Math.PI * 2 * (data[i]/total)), false);
        ctx.lineTo(rad, rad);
        ctx.fill();
        ctx.stroke();
        angle += Math.PI * 2 * (data[i] / total);
    }
</script>

You can download all these code examples from the GitHub repository for this chapter. See the last section for details. The result is shown as follows:

A simple pie chart created using HTML Canvas

You can make even nicer pie charts in Chart.js without writing a single line of Canvas code, and you won't have to worry about calculating angles in radians or adjusting scales to fit the page. You also get free tooltips with far fewer lines of code than we used previously. Chart.js may not satisfy all your data visualization needs, but it certainly is a great way to start. You can then apply your knowledge of HTML and JavaScript and extend it with plugins, integrate with other charting solutions, or migrate to a larger and unrestricted library such as D3.js.

 

How to use this book


This book was designed as a practical hands-on guide on how to create data visualizations with Chart.js. It doesn't cover all aspects of Chart.js, but does cover most of the features you are likely to use to create visualizations. All eight Chart.js charts are covered, exploring different configurations and applications using external data obtained from public repositories.

Each chapter covers fundamental concepts. Each concept is always illustrated with a simple code example, but more complex examples that might require extra JavaScript programming are also presented in each chapter, and include solutions to real-world problems, such as downloading, parsing, and filtering a data file to convert it into a format usable by Chart.js.

Code listings are used throughout the book, but most of the time, they focus on a specific feature and show only a fragment of the full code. But you can download the full listing. All the code examples used in the book are available from a public GitHub repository located at: https://github.com/PacktPublishing/Learn-charts.js.

There is a folder for each chapter in the repository, named Chapter01Chapter02, and so on. Each code listing and every image generated by code contains a relative reference to a file located in the corresponding folder for each chapter. You can try out all the code examples as you learn. You can also use it in any way you like, since it's free and open source.

Here's a brief summary of each chapter:

Chapter 2, Technology Fundamentals, covers technology fundamentals, data formats, and also explores some techniques for loading and parsing files. It gives a general background on topics used by Chart.js, such as JavaScript, CSS, DOM, and Canvas. You may skip these sections if you wish.

Chapter 3, Chart.js – Quick Start, includes a quick start and overview of several Chart.js features. It shows how to set up a web page to use Chart.js and how to create your first chart. You will learn a bit of everything Chart.js has to offer. It also introduces the bar chart type (vertical and horizontal).

Chapter 4Creating Charts, covers all other chart types available: line/area, radar, polar area, pie, doughnut, scatter, and bubble. It also shows how to load and parse external CSV and JSON data from public data portals and use them to create real-world visualizations.

Chapter 5, Scales and Grid Configuration, focuses on configuring scales, axes, and grid lines for all charts. You will learn how to use radial grids and Cartesian grids with linear, logarithmic, category, and time axes.

Chapter 6Configuring Styles and Interactivity, deals with configuration of several properties, for which Chart.js already provides defaults: fonts, titles, and labels. It also explores some neat labeling plugins and color schemes, which are important for accessible charts. This chapter also shows how to configure transitions, animations, and interactions.

Chapter 7, Advanced Charts.js, covers some advanced features that you will are less likely to use on a regular basis, since Chart.js already provides good defaults. These include tooltip configuration, creating custom legends, mixed charts, how to display multiple charts on a single page, overlaying Chart.js on a Canvas, and creating plugins.

I believe the book covers the most important topics in Chart.js. It leaves out some advanced programming topics, several plugins, and integration with front-end frameworks, which are also not covered. 

I am not affiliated with Chart.js in any way and this book does not replace the official Chart.js documentation, which is the ultimate reference guide on the topic. The documentation is community-maintained and freely available at www.chartjs.org/docs/latest. There are also many samples that explore its main features that are also part of the documentation at www.chartjs.org/samples/latest.

When writing this book, I did my best to provide the most accurate information possible. All code listings were tested, and additional efforts were made to guarantee that all code examples are properly referenced in the book and work as expected. This book is based on Chart.js version 2.7.3. I expect that the examples should continue working with any 2.x version, but there is a small possibility that some code may not work as expected if you are using a later version.

The Chart.js community is very active on GitHub and StackOverflow. If you have any questions about Chart.js, you can submit a question on stackoverflow.com and you will probably have an answer within a few hours or less.

I hope you enjoy this book and have as much fun as I had when learning Chart.js.

 

Summary


This chapter provided a quick introduction to data visualization topics and introduced Chart.js, the JavaScript library with which you will learn to create responsive interactive visualizations for the web. We also demonstrated how standard web technologies provide all you need to create charts for the web, and how a data visualization library such as Chart.js can be beneficial.

In the next chapter, we will cover the fundamentals of some standard technologies used by Chart.js—data formats and data manipulation techniques—but if you want to start using Chart.js right away, you can skip it and jump straight to Chapter 3, Chart.js – Quick Start.

 

 

 

References


Books and websites:

  • Edward R. Tufte. The Visual Display of Quantitative Information. Graphics Press, 1997
  • Isabel Meirelles. Design for Information. Rockport Publishers, 2013
  • Stephen Few. Data Visualization: past, present and future. Perceptual Edge, 2007
  • David Kahneman. Thinking Fast and Slow. Farrar, Straus and Giroux. 2011
  • Ben Bederson and Ben Schneiderman. The Craft of Information Visualization. 2003
About the Author
  • Helder da Rocha

    Helder teaches, writes and develops applications with Java and Web technologies since 1995. In 1996 he wrote one of the first books in Portuguese about HTML and JavaScript, and since then he created hundreds of presentations, tutorials, and course materials on Java, Java EE, programming tools, patterns, techniques, methodologies, HTML, CSS, JavaScript, SVG, XML and related technologies, data visualization, Arduino and Internet of Things. He holds a masters degree in Computer Science. He also has a background in the visual arts and design and has some of his artwork in permanent museum exhibits. He lives in Brazil, where he works as an independent consultant, developer and instructor and a frequent speaker at technological events.

    Browse publications by this author
Latest Reviews (1 reviews total)
Great to understand, easy to learn
Learn Chart.js
Unlock this book and the full library FREE for 7 days
Start now