Skip to content
Chart.js

Pie Chart

Pie chart with per-slice colors and legend positioning.

By EZ4Code Team
chartpie

Code

const ctx = document.getElementById('pieChart').getContext('2d');
new Chart(ctx, {
  type: 'pie',
  data: {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple'],
    datasets: [{
      data: [12, 19, 3, 5, 2],
      backgroundColor: [
        'rgba(255, 99, 132, 0.7)',
        'rgba(54, 162, 235, 0.7)',
        'rgba(255, 206, 86, 0.7)',
        'rgba(75, 192, 192, 0.7)',
        'rgba(153, 102, 255, 0.7)'
      ],
      borderWidth: 1,
      borderColor: '#fff'
    }]
  },
  options: {
    plugins: {
      legend: { position: 'right', labels: { padding: 15 } }
    }
  }
});

Explanation

Renders proportions as pie slices; the data array's relative values determine slice angles and backgroundColor as an array colors each slice individually. The legend plugin supports top/right/bottom/left positions with configurable label padding. Pie charts work best with fewer than seven categories for readability.

More Chart.js Snippets