Search icon
Subscription
0
Cart icon
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
$9.99 | ALL EBOOKS & VIDEOS
Over 7,000 tech titles at $9.99 each with AI-powered learning assistants on new releases
Learn Chart.js
Learn Chart.js

Learn Chart.js: Create interactive visualizations for the Web with Chart.js 2

By Helder da Rocha
$22.99 $9.99
Book Feb 2019 284 pages 1st Edition
eBook
$22.99 $9.99
Print
$32.99
Subscription
$15.99 Monthly
eBook
$22.99 $9.99
Print
$32.99
Subscription
$15.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now
Table of content icon View table of contents Preview book icon Preview Book

Learn Chart.js

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
Left arrow icon Right arrow icon

Key benefits

  • Harness the power of JavaScript, HTML, and CSS to create interactive visualizations
  • Display quantitative information efficiently in the form of attractive charts by using Chart.js
  • A practical guide for creating data-driven applications using open-source JavaScript library

Description

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.

What you will learn

Learn how to create interactive and responsive data visualizations using Chart.js Learn how to create Canvas-based graphics without Canvas programming Create composite charts and configure animated data updates and transitions Efficiently display quantitative information using bar and line charts, scatterplots, and pie charts Learn how to load, parse, and filter external files in JSON and CSV formats Understand the benefits of using a data visualization framework

Product Details

Country selected

Publication date : Feb 28, 2019
Length 284 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781789342482
Category :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Feb 28, 2019
Length 284 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781789342482
Category :

Table of Contents

14 Chapters
Title Page Chevron down icon Chevron up icon
Copyright and Credits Chevron down icon Chevron up icon
About Packt Chevron down icon Chevron up icon
Contributors Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
1. Introduction Chevron down icon Chevron up icon
2. Technology Fundamentals Chevron down icon Chevron up icon
3. Chart.js - Quick Start Chevron down icon Chevron up icon
4. Creating Charts Chevron down icon Chevron up icon
5. Scales and Grid Configuration Chevron down icon Chevron up icon
6. Configuring Styles and Interactivity Chevron down icon Chevron up icon
7. Advanced Chart.js Chevron down icon Chevron up icon
1. Other Books You May Enjoy Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.