Menu

How to Create Bubble Charts Using Chart.js

How to Create Bubble Charts Using Chart.js

Bubble charts are perfect for visualizing three dimensions of data in a single plot. X, Y, and bubble size (Z). With Chart.js, you can create an interactive bubble chart with minimal setup. Here's how to do it.

And a quick example of what gets rendered:

Step 1: Include Chart.js

Use the CDN to quickly include Chart.js in your project:

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

Or install via npm:

npm install chart.js

Step 2: Add a Canvas Element

Add the canvas element to your HTML to render the chart:

<canvas id="myBubbleChart" width="400" height="400"></canvas>

Step 3: Configure and Render the Chart

Here’s a simple example with multiple data points:

const ctx = document.getElementById('myBubbleChart').getContext('2d');

const data = {
  datasets: [
    {
      label: 'Sample Dataset',
      data: [
        { x: 10, y: 20, r: 15 },
        { x: 15, y: 10, r: 10 },
        { x: 25, y: 30, r: 20 }
      ],
      backgroundColor: 'rgba(255, 99, 132, 0.5)',
      borderColor: 'rgba(255, 99, 132, 1)'
    }
  ]
};

const config = {
  type: 'bubble',
  data: data,
  options: {
    responsive: true,
    scales: {
      x: {
        title: {
          display: true,
          text: 'X Axis'
        }
      },
      y: {
        title: {
          display: true,
          text: 'Y Axis'
        }
      }
    }
  }
};

new Chart(ctx, config);

Breakdown of Key Fields

  • type: Set to 'bubble' to specify chart type.

  • datasets: Contains the data and visual properties for each bubble set.

    • label: Describes the dataset.
    • data: An array of objects where each object includes x, y, and r (radius/size).
    • backgroundColor: Fills the inside of each bubble.
    • borderColor: Defines the outline of the bubble.
  • scales.x and scales.y: Customize axis titles and scaling.

Conclusion

Bubble charts are ideal when you need to pack three dimensions of data into one view. Chart.js makes it easy to build and style them for anything from scientific plots to business dashboards.

Walt is a software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20+ years.
No comments posted yet
// Add a comment
// Color Theme

Custom accent
Pick any color
for the accent