Charts #
Charts turn complex data into clear visuals, revealing trends and comparisons at a glance.
Due to the complexity of charting needs, there is no single reusable component provided; instead, using Chart.js is recommended. Below are a short instruction and examples on how to get started with Chart.js presented.
Chart.js #
Chart.js is a free JavaScript library for making HTML-based charts. It is one of the simplest visualization libraries for JavaScript, and comes with the many built-in chart types:
- Area Chart
- Bar Chart
- Bubble Chart
- Doughnut and Pie Chart
- Line Chart
- Mixed Chart Types
- Polar Area Chart
- Radar Chart
- Scatter Chart
For more detailed information see the official documentation.
Installation #
To use the package in a project with a bundler, install it via npm:
npm install chart.js
Optionally, you can include Chart.js from a CDN by adding the following to the beginning of your HTML file:
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
Usage #
Chart.js renders into an HTML <canvas> element. Add a canvas where you want the chart to appear:
<canvas id="myChart"></canvas>
Typical Chart Syntax (Bar Chart in this case):
const myChart = new Chart("myChart", {
type: "bar",
data: {},
options: {}
});
The data property contains the labels as well as one or more datasets and the options property configures plugins (e.g., legend, title, tooltip), scales, interaction behavior, and more.
Examples #
In the following, several chart types and features are shown using Chart.js. Note that all values are fictitious and only displayed for visual purposes.
Practical tips #
- Selecting the canvas:
new Chart("myChart", ...)works if the element exists. Alternatively, usedocument.getElementById('myChart')to pass the element directly (as shown in examples). - Destroy before re-create: If you redraw charts in single-page apps or on data updates, call
chart.destroy()before creating a new instance to avoid memory leaks and overlapping canvases. - Updating data: Update values and call
chart.update()to re-render without recreating the chart. - Color and accessibility: Use high-contrast colors and consider patterns or markers for users with color vision deficiencies.
- Tooltips and formatting: Use
tooltip.callbacksandticks.callbackto format values (e.g.,currency,percentages). - Scales: For time-series data, consider the time scale and adapters. For logarithmic data, use the
logarithmicscale type. - Responsive layout: Control chart size via CSS on the canvas or parent container. For fixed height, set height on the
canvas or configure
maintainAspectRatioin options. - Bundlers: When importing with npm, you’ll typically do
import { Chart, registerables } from 'chart.js';Chart.register(...registerables);before creating charts.