Book Image

Learn Chart.js

By : Helder da Rocha
Book Image

Learn Chart.js

By: Helder da Rocha

Overview of 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.
Table of Contents (14 chapters)
Title Page
Copyright and Credits
About Packt

Updating charts

You can use JavaScript functions and libraries to change your data dynamically, but the changes will not be reflected immediately in your chart. After changing data, you have to call update() in order to redraw it. For this, you will need a variable reference to the chart object, as follows:

const ch = new Chart("ocean-volume-bar-chart", {...});

The following example toggles the data in the chart, replacing the values in the dataset with a different array, and changing labels, titles, and colors. The toggle() function is registered as a click event listener on the canvas. Whenever you click anywhere in the canvas it will run, change the values of several properties, and call update(),which forces the chart to transition to the new data and appearance, as follows:

const labels = ["Arctic", "North Atlantic", "South Atlantic", "Indian",
                "North Pacific", "South Pacific", "Southern"];

 const area   = [15558,41900,40270,70560,84000,84750,21960];   // km2 * 10^3