Chart Libraries
A chart library turns data into charts without you drawing every bar and axis by hand. The canvas and SVG lessons showed how charts are drawn underneath; libraries add axes, scales, legends, tooltips, animation, responsiveness and many chart types. The three most widely used general-purpose libraries are Chart.js (simple, canvas-based charts with little code), D3 (a toolkit for building any custom visualization from data), and Plotly (interactive scientific and business charts). This is an overview lesson: which to choose, how each looks in code, and what to watch for.
In One Minute
- Chart.js: give it a canvas and a configuration object; you get a good-looking, responsive, animated chart. Best for standard dashboards.
- D3: binds data to DOM (usually SVG) elements and provides scales, axes, shapes and transitions. Best for custom or unusual visualizations; more code.
- Plotly: one call creates interactive charts (zoom, pan, hover) including 3D and statistical charts. Best for data exploration; larger download.
- Install with npm (
npm install chart.js) and import, or load from a CDN with<script>. - Libraries don't make charts accessible automatically: add text alternatives or a data table.
Choosing a Library
| Chart.js | D3 | Plotly | |
|---|---|---|---|
| Renders with | Canvas | SVG (or canvas), you choose | SVG and WebGL |
| Code for a basic bar chart | About 10 lines | 30 to 60 lines | About 5 lines |
| Chart types | 8 built-in types plus plugins | Anything you can build | 40+ including 3D, maps, statistical |
| Customization | Options and plugins | Total control | Extensive options |
| Interactivity | Tooltips, legend toggling | You build it | Zoom, pan, hover, export built in |
| Approximate size (minified, gzipped) | Moderate | Modular: import only what you use | Large |
| License | MIT | ISC | MIT |
| Choose it for | Business dashboards, admin pages | Custom data journalism, unusual layouts | Analytics, scientific data, exploration |
There are other good options: Apache ECharts (feature-rich, canvas), Vega-Lite (charts described as JSON specifications), Observable Plot (D3's concise high-level companion), and Google Charts (hosted, no install). The same questions apply to all: how much code, how much control, how big a download, and how accessible.
Chart.js
Chart.js draws on a <canvas>. You describe the chart with a configuration object of type, data and options:
<canvas id="totals" aria-label="Payments by grade" role="img"></canvas>
<script type="module">
import Chart from "chart.js/auto";
new Chart(document.querySelector("#totals"), {
type: "bar",
data: {
labels: ["Grade 9", "Grade 11", "Grade 12"],
datasets: [{ label: "Payments ($)", data: [165, 85, 300], backgroundColor: "seagreen" }],
},
options: {
responsive: true,
plugins: { legend: { display: false } },
scales: { y: { beginAtZero: true, ticks: { callback: (v) => `$${v}` } } },
},
});
</script>Changing the chart type to "line", "pie" or "doughnut" is a one-word change. To update a chart, change chart.data and call chart.update().
D3
D3 (Data-Driven Documents) doesn't have chart types. It gives you building blocks: selections that bind data to elements, scales that map data values to pixels, axes, shapes and transitions:
import * as d3 from "d3";
const data = [{ label: "Grade 9", total: 165 }, { label: "Grade 11", total: 85 }, { label: "Grade 12", total: 300 }];
const width = 360, height = 200, margin = { top: 10, right: 10, bottom: 30, left: 40 };
const x = d3.scaleBand().domain(data.map((d) => d.label)).range([margin.left, width - margin.right]).padding(0.3);
const y = d3.scaleLinear().domain([0, d3.max(data, (d) => d.total)]).nice().range([height - margin.bottom, margin.top]);
const svg = d3.select("#chart").append("svg").attr("viewBox", [0, 0, width, height]).attr("role", "img");
svg.selectAll("rect")
.data(data)
.join("rect")
.attr("x", (d) => x(d.label))
.attr("y", (d) => y(d.total))
.attr("width", x.bandwidth())
.attr("height", (d) => y(0) - y(d.total))
.attr("fill", "seagreen");
svg.append("g").attr("transform", `translate(0,${height - margin.bottom})`).call(d3.axisBottom(x));
svg.append("g").attr("transform", `translate(${margin.left},0)`).call(d3.axisLeft(y).tickFormat((v) => `$${v}`));The central idea is selectAll(...).data(...).join(...): one element per data item, created, updated or removed to match the data. That pattern is powerful enough to build anything, from bar charts to network diagrams and maps, which is also why D3 takes the longest to learn.
Plotly
Plotly creates an interactive chart from traces (data series) and a layout in one call:
<div id="plot"></div>
<script type="module">
import Plotly from "plotly.js-dist-min";
Plotly.newPlot("plot", [
{ type: "bar", x: ["Grade 9", "Grade 11", "Grade 12"], y: [165, 85, 300], marker: { color: "seagreen" } },
], {
title: { text: "Payments by grade" },
yaxis: { tickprefix: "$" },
}, { responsive: true });
</script>The result supports hover tooltips, zooming, panning and downloading as an image without any extra code.
Loading a Library
| Way | Example | When |
|---|---|---|
| npm and a bundler | npm install chart.js, then import Chart from "chart.js/auto" | Real projects (the modules chapter explains bundlers) |
| CDN with an ES module | import Chart from "https://cdn.jsdelivr.net/npm/chart.js@4/+esm" | Quick prototypes |
CDN <script> tag | <script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script> (defines a global Chart) | Older pages, no build step |
Accessibility of Charts
Charts carry information visually. Every chart, whatever the library, needs:
- A text alternative: a summary of what the chart shows ("Grade 12 paid the most, $300").
- The data itself: a table, visible or toggleable, for people who need exact numbers or use screen readers.
- Color that isn't the only signal: patterns, labels or direct annotations, and enough contrast.
- Keyboard access to any interaction (tooltips, filters).
Chart.js renders to a canvas, which screen readers can't read, so its aria-label and fallback content matter most. Plotly and D3 produce SVG, which can carry labels, but still need summaries.
When You Don't Need a Library
For a small, fixed chart (a few bars, a progress ring, a sparkline), hand-written SVG or canvas, as in the last two lessons, is often less code than configuring a library, adds no download, and gives full control over accessibility. Reach for a library when you need axes with nice tick values, many chart types, legends, tooltips, zooming, or frequent data updates.
In Practice
The Fee Tracker uses plain SVG for its small dashboard bars, and would switch to a library for its reports page. The data preparation is the same either way, and it's plain, testable JavaScript:
const payments = [
{ grade: 9, amount: 120 }, { grade: 11, amount: 85 }, { grade: 9, amount: 45 }, { grade: 12, amount: 300 },
];
const totals = Object.entries(Object.groupBy(payments, (p) => p.grade))
.map(([grade, list]) => ({ label: `Grade ${grade}`, total: list.reduce((s, p) => s + p.amount, 0) }))
.toSorted((a, b) => a.label.localeCompare(b.label, "en-US", { numeric: true }));
const chartJsData = { labels: totals.map((t) => t.label), datasets: [{ data: totals.map((t) => t.total) }] };
const summary = `Payments by grade: ${totals.map((t) => `${t.label} $${t.total}`).join(", ")}.`;
console.log(JSON.stringify(chartJsData));
console.log(summary);{"labels":["Grade 9","Grade 11","Grade 12"],"datasets":[{"data":[165,85,300]}]}
Payments by grade: Grade 9 $165, Grade 11 $85, Grade 12 $300.Keeping data preparation separate from drawing means you can test it, switch chart libraries later, and produce the accessible summary from the same numbers. (localeCompare with numeric: true sorts "Grade 9" before "Grade 11".)
Common Mistakes
Choosing D3 for a standard chart. It's a toolkit; Chart.js or Plotly produce standard charts with far less code.
Loading unpinned CDN scripts. A changed file changes your site. Pin versions and use integrity hashes, or install with npm.
Shipping a chart without a text alternative. Add a summary and a data table.
Mixing data processing into chart code. Prepare data in plain functions you can test.
Practice
Challenge: Turn this list of monthly totals into the labels and data arrays a chart library expects, and build a one-sentence summary naming the highest month.
Show solution
const monthly = [{ month: "Jan", total: 1250 }, { month: "Feb", total: 980 }, { month: "Mar", total: 1430 }];
const labels = monthly.map((m) => m.month);
const data = monthly.map((m) => m.total);
const top = monthly.reduce((a, b) => (b.total > a.total ? b : a));
console.log(labels, data);
console.log(`Highest month: ${top.month} with $${top.total.toLocaleString("en-US")}.`);['Jan', 'Feb', 'Mar'] [1250, 980, 1430]
Highest month: Mar with $1,430.Key Takeaways
| Need | Choose |
|---|---|
| Standard dashboard chart, little code | Chart.js |
| Custom or unusual visualization | D3 |
| Interactive exploration, 3D, statistics | Plotly |
| A few bars or a progress ring | Plain SVG or canvas |
Was this tutorial helpful?