Menu

How to Create a Pie Chart Using Chart.js

How to Create a Pie Chart Using Chart.js

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>

Step 3: Configure and Render the Chart

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:

  1. 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.

  2. 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)
  3. 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
  4. 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.
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.

Community Comments

No comments posted yet

Code Your Own Classic Snake Game – The Right Way

Master the fundamentals of game development and JavaScript with a step-by-step guide that skips the fluff and gets straight to the real code.

Ad Unit

Current Poll

Help us and the community figure out what the latest trends in coding are.

Total Votes:
Q:
Submit

Add a comment