28,14 €
Design interactive graphics and visuals for your data-driven applications using the popular open-source Chart.js data visualization library.
Key Features
Book 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
Who this book is for
The ideal target audience of this book includes web developers and designers, data journalists, data scientists and artists who wish to create interactive data visualizations for the Web. Basic knowledge of HTML, CSS, and JavaScript is required. No Canvas knowledge is necessary.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 254
Veröffentlichungsjahr: 2019
Copyright © 2019 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Kunal ChaudhariContent Development Editor:Pranay FereiraTechnical Editor: Diksha WakodeCopy Editor: Safis EditingProject Coordinator:Kinjal BariProofreader: Safis EditingIndexer:Manju ArasanGraphics:Alishon MendonsaProduction Coordinator: Nilesh Mohite
First published: February 2019
Production reference: 1280219
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78934-248-2
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Helder da Rocha has taught, written, and developed applications with Java and web technologies since 1995. In 1996, he wrote one of the first books in Portuguese about HTML and JavaScript. Since then he has created hundreds of presentations, tutorials, and course materials on Java, Java EE, programming tools, patterns, techniques, methodologies, HTML, CSS, JavaScript, SVG, XML, data visualization, Arduino, and the Internet of Things. He holds a master's 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 São Paulo, Brazil, where he works as an independent consultant, developer, and instructor, and is a frequent speaker at technological events.
Bruno Joseph D'mello is proactively working at Truckx as a full stack developer. He is a JS enthusiast and loves working with open source communities. He possesses more than 6 years' experience in web development. Bruno follows kaizen and enjoys the freedom of architecting new things at work. He is socially active via coaching web technologies or participating in other research projects and meetups. When not engaged with technology, Bruno likes to spend quality time traveling with family and friends.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Learn Chart.js
About Packt
Why subscribe?
Packt.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
Introduction
Data visualization
Chart types
Choosing a chart
Web-based visualizations
Why use a data visualization library?
Creating data visualizations for the Web
How to use this book
Summary
References
Technology Fundamentals
Essential JavaScript for Chart.js
Browser tools
JavaScript types and variables
Data structures used in charts
Arrays
Strings
Functions
Objects
Other technologies
HTML Document Object Model(DOM)
Cascading Style Sheets
JQuery fundamentals
HTML5 Canvas
Data formats
CSV
XML
JSON
Loading and parsing external data files  
Using a Web server
Loading files using standard JavaScript
Loading files using JQuery
Loading files using the standard Fetch API
Parsing JSON
Parsing CSV
Loading multiple files
Displaying a map
Extracting and transforming data
Online tools
Extracting data with XPath
Summary
Chart.js - Quick Start
Introduction to Chart.js
Installation and setup
Creating a simple bar chart
Setting up the graphics context
Creating a bar chart
Configuring colors, fonts, and responsiveness
Dataset configuration for bar charts
Options configuration
Text and fonts
Global defaults
Transitions, interactions, and tooltips
Transition duration
Updating charts
Tooltips
Working with larger and multiple datasets
Loading data
Horizontal bar chart
Adding extra datasets
Stacking bars
Summary 
References
Creating Charts
Line and area charts
Creating a simple line chart
Dataset configuration
Options configuration for line charts
Line charts with more than one dataset
Loading data from external files
Stacked area charts
Radar charts
Pie and doughnut charts
Creating a simple pie chart
Dataset properties for pie charts
Configuration options
How to show values in the slices
Preparing data for pie and doughnut charts
Changing the circumference
Pie and doughnut charts with multiple datasets
Polar area charts
Scatter and bubble charts
Creating a scatter chart
Revealing correlations with scatter charts
Scatter charts with large quantities of data
Bubble charts
Summary
References
Scales and Grid Configuration
Configuring scales
Cartesian configuration options
Cartesian axes, ticks, and grid lines
Numeric Cartesian scales
Linear scales
Logarithmic scales
Configuring axis titles
Configuring ticks
Configuring grid lines
Category scales
Configuring the axes
Configuring ticks
Configuring grid lines
Time scales
Configuring the time format
Configuring the axes
Configuring ticks
Configuring grid lines
Radial scales
Configuring point labels
Configuring ticks
Configuring grids and angle lines
Configuring advanced scales
Multiple Cartesian axes
Callbacks
The scale service
Summary
References
Configuring Styles and Interactivity
Default configuration
Global defaults
Scale defaults
Graphical elements
Chart defaults
Fonts
Selecting standard fonts
Using Web fonts
Colors, gradients, patterns, and shadows
Configuring colors
Color schemes and palettes
Gradients
Patterns
Shadows and bevels
Adding text elements and labels
Legends and labels
Titles
Adding labels to lines, bars, and slices
Interactions, data updates, and animations
Data updates
Events
Configuring animations
Summary
References
Advanced Chart.js
Tooltip configuration
Hovering interactions
Scriptable properties
Tooltip callbacks
Custom HTML tooltips
Advanced legend configuration
Generating labels
HTML legends
Displaying multiple charts
Rendering many charts on one page
Mixed charts
Overlaying a canvas
Extending Chart.js
Prototype methods
Creating plugins
Chart.js extensions
Summary
References
Other Books You May Enjoy
Leave a review - let other readers know what you think
Learn Chart.js will make visualization easy and attractive for websites that are data intensive. I will explain how to make complicated data simple, accessible, and intuitive, so that your users will be able to better understand your website.
This book is a practical introduction to creating and publishing your own interactive data visualization projects on the Web.
After reading this book, you will be able to create beautiful charts for the Web with Chart.js.
The book is for designers and artists who wish to create interactive data visualizations for the Web.
Basic knowledge of HTML, CSS, and JavaScript would be of great help.
Chapter 1, Introduction, introduces Chart.js and explains the basic concepts.
Chapter 2, TechnologyFundamentals, explains the various fundamentals and setups needed for Chart.js
Chapter 3, Chart.js - Quick Start, provides a quick start to creating web-based data visualizations with Chart.js. It will show you how to set up the library and configure a basic web page on which you can place a chart. We will walk through a complete step-by-step example, describing how to create a bar chart and configure it with labels, tooltips, titles, interactions, colors, animations, and more.
Chapter 4, Creating Charts, covers several charts that can be created with Chart.js to efficiently communicate quantitative information and relationships. The choice of a chart depends on the type of data, how each set of values is related to one another, and what kind of relationships you want to show.
Chapter 5, Scales and Grid Configuration, explains how to configure the look and feel of a chart so it reflects a desired layout or style, follow good practices of chart design, and tune its interactive and responsive behavior.
Chapter 6, Configuring Styles and Interactivity, explores configuration topics that you won't use as frequently and that may require additional coding, extensions, and integration with other libraries, such as tooltip behavior configuration, label generation, scripting, creating mixed charts, creating plugins, using the Chart.js API, and using HTML Canvas with Chart.js.
Chapter 7, Advanced Chart.js, will explore fonts, padding, axes, screen resizing, and responsiveness.
I recommend that you read the first chapter to make sure that you are up to speed with the basic concepts and fundamentals of Chart.js. In the next chapters, we will see the setup that Chart.js needs and the various visual representation techniques this book will teach us and their uses. There will be tutorials on using the different chart types, and we will explore their interactivity.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Learn-Charts.js. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
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 3, Chart.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
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.
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 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:
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:
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.
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.
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?
