Chart.js is a simple yet powerful JavaScript library for visualizing data. One of its most commonly used chart types is the pie chart, ideal for showing proportional data. Here's a concise guide to creating a pie chart with Chart.js.
Step 1: Include Chart.js
You can use Chart.js directly via CDN, which is the easiest way to get started:
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
Alternatively, if you're working in a project with npm:
npm install chart.js
Step 2: Add a Canvas Element
In your HTML, insert a canvas element where the pie chart will be rendered:
<canvas id="myPieChart" width="300" height="300"></canvas>
Now create a JavaScript block to initialize and configure your pie chart:
const ctx = document.getElementById('myPieChart').getContext('2d');
const data = {
labels: ['Red', 'Blue', 'Yellow'],
datasets: [{
label: 'Color Distribution',
data: [30, 50, 20],
backgroundColor: ['#ff6384', '#36a2eb', '#ffcd56'],
borderWidth: 1
}]
};
const config = {
type: 'pie',
data: data,
options: {
responsive: true,
plugins: {
legend: {
position: 'bottom'
}
}
}
};
new Chart(ctx, config);
The implementation follows these key steps:
First, it gets a reference to the HTML canvas element with the ID 'myPieChart' and its 2D rendering context, which is where the chart will be drawn.
Next, it defines the data object containing:
labels
: Text labels for each segment ('Red', 'Blue', 'Yellow')
datasets
: An array containing a single dataset object with:
label
: The dataset name ('Color Distribution')
data
: Numeric values that determine the size of each pie segment (30, 50, 20)
backgroundColor
: Colors for each segment using hex values
borderWidth
: Width of the border around each segment (1 pixel)
The config object specifies:
type
: Chart type ('pie')
data
: The data object defined earlier
options
: Configuration settings including:
responsive
: Makes the chart resize with its container
plugins.legend.position
: Places the legend at the bottom of the chart
Finally, it creates a new Chart instance using the canvas context and configuration, which renders the pie chart on the page.
Conclusion
That’s it. You now have a clean, responsive pie chart rendered in your browser. Chart.js handles the heavy lifting, offering customization for tooltips, legends, interactivity, and more.
Walter Guevara is a Computer Scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.
Last updated on:
AD: "Heavy scripts slowing down your site? I use
Fathom Analytics because it’s lightweight, fast, and doesn’t invade my users privacy." -
Get $10 OFF your first invoice.