JavaScript Chart.js

Chart.js is a popular, free, open-source JavaScript library for creating interactive and responsive charts. It uses the HTML Canvas element to render charts and supports various chart types including bar, line, pie, doughnut, and more.

What is Chart.js?

Chart.js is a simple yet flexible charting library that makes it easy to create beautiful data visualizations. It is lightweight, supports 8 chart types, and is responsive out of the box.

Getting Started with Chart.js
// Include Chart.js via CDN:
// <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

// Or install via npm:
// npm install chart.js

// HTML: <canvas id="myChart"></canvas>

// Basic chart creation:
// const ctx = document.getElementById('myChart');
// const chart = new Chart(ctx, {
//   type: 'bar',
//   data: { ... },
//   options: { ... }
// });

console.log('Chart.js Features:');
console.log('  - 8 chart types');
console.log('  - Responsive and retina-ready');
console.log('  - Interactive (hover, click events)');
console.log('  - Animations built-in');
console.log('  - Plugin system for extensions');

Bar Charts

Bar charts display data as rectangular bars with heights proportional to the values. They are great for comparing values across categories.

Creating a Bar Chart
// const ctx = document.getElementById('barChart');
// const barChart = new Chart(ctx, {
//   type: 'bar',
//   data: {
//     labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
//     datasets: [{
//       label: 'Sales ($)',
//       data: [1200, 1900, 1500, 2100, 1800],
//       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
//     }]
//   }
// });

const barData = {
  labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
  values: [1200, 1900, 1500, 2100, 1800]
};

console.log('Bar Chart Data:');
barData.labels.forEach(function(label, i) {
  const bar = '#'.repeat(Math.round(barData.values[i] / 100));
  console.log('  ' + label + ': $' + barData.values[i] + ' ' + bar);
});

Line Charts

Line charts connect data points with lines, showing trends over time. They support multiple datasets, fill areas, and smooth curves.

Creating a Line Chart
// const lineChart = new Chart(ctx, {
//   type: 'line',
//   data: {
//     labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
//     datasets: [{
//       label: 'Visitors',
//       data: [150, 230, 180, 290, 320],
//       borderColor: 'rgb(75, 192, 192)',
//       tension: 0.1,
//       fill: false
//     }, {
//       label: 'Page Views',
//       data: [300, 450, 380, 520, 610],
//       borderColor: 'rgb(255, 99, 132)',
//       tension: 0.1,
//       fill: false
//     }]
//   }
// });

console.log('Line Chart - Key Properties:');
console.log('  borderColor: line color');
console.log('  backgroundColor: fill color');
console.log('  tension: 0 (straight) to 0.4 (curved)');
console.log('  fill: true/false for area fill');
console.log('  pointStyle: circle, cross, rect, etc.');
console.log('  stepped: true for step lines');

Pie and Doughnut Charts

Pie and doughnut charts show proportional data. Doughnut charts are pie charts with a hole in the center. Both are useful for showing parts of a whole.

Pie and Doughnut Charts
// Pie Chart
// const pieChart = new Chart(ctx, {
//   type: 'pie',  // or 'doughnut'
//   data: {
//     labels: ['Chrome', 'Firefox', 'Safari', 'Edge'],
//     datasets: [{
//       data: [65, 15, 12, 8],
//       backgroundColor: [
//         '#4285F4', '#FF7139', '#006CFF', '#0078D7'
//       ]
//     }]
//   }
// });

const browsers = [
  { name: 'Chrome', share: 65 },
  { name: 'Firefox', share: 15 },
  { name: 'Safari', share: 12 },
  { name: 'Edge', share: 8 }
];

console.log('Browser Market Share (Pie/Doughnut):');
browsers.forEach(function(b) {
  const bar = '='.repeat(b.share);
  console.log('  ' + b.name + ': ' + b.share + '% ' + bar);
});

console.log('\nPie: type = "pie"');
console.log('Doughnut: type = "doughnut"');

Configuration Options

Chart.js provides extensive configuration options for customizing the appearance and behavior of charts, including titles, legends, tooltips, axes, and animations.

Chart Configuration
// const chart = new Chart(ctx, {
//   type: 'bar',
//   data: { ... },
//   options: {
//     responsive: true,
//     plugins: {
//       title: {
//         display: true,
//         text: 'Monthly Sales'
//       },
//       legend: {
//         position: 'top'
//       },
//       tooltip: {
//         enabled: true
//       }
//     },
//     scales: {
//       y: {
//         beginAtZero: true,
//         title: { display: true, text: 'Amount ($)' }
//       }
//     },
//     animation: {
//       duration: 1000
//     }
//   }
// });

console.log('Key Options:');
console.log('  responsive: auto-resize to container');
console.log('  plugins.title: chart title');
console.log('  plugins.legend: dataset labels');
console.log('  plugins.tooltip: hover tooltips');
console.log('  scales: axis configuration');
console.log('  animation: entry animations');

Responsive Charts and Updating Data

Chart.js charts are responsive by default. You can also update chart data dynamically by modifying the data object and calling chart.update().

Updating Chart Data
// Charts are responsive by default
// They resize when the window/container changes

// Update data dynamically:
// chart.data.labels.push('Jun');
// chart.data.datasets[0].data.push(2500);
// chart.update();  // Re-render the chart

// Replace all data:
// chart.data.datasets[0].data = [100, 200, 300];
// chart.update();

// Remove data:
// chart.data.labels.pop();
// chart.data.datasets[0].data.pop();
// chart.update();

// Destroy chart:
// chart.destroy();

console.log('Updating Chart Data:');
console.log('1. Modify chart.data');
console.log('2. Call chart.update()');
console.log('');
console.log('chart.destroy() removes the chart');
console.log('Always destroy before creating a new chart');
console.log('on the same canvas element');
Chart Typetype ValueBest For
BarbarComparing categories
LinelineTrends over time
PiepieParts of a whole
DoughnutdoughnutParts of a whole (with center)
RadarradarComparing multiple variables
Polar AreapolarAreaProportional data in radial form
ScatterscatterCorrelation between variables
BubblebubbleThree-dimensional data
📝 Note: Always call chart.destroy() before creating a new chart on the same canvas element. Creating multiple charts on the same canvas without destroying the previous one causes memory leaks and rendering issues. Chart.js 4.x uses tree-shaking, so import only the components you need for smaller bundle sizes.
Exercise:
What method must you call after modifying chart data to see the changes?
Try it YourselfCtrl+Enter to run
Click Run to see the output here.