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.

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