0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Create Bubble Chart in Matplotlib: Simple Guide

To create a bubble chart in matplotlib, use the scatter() function with three main arguments: x-coordinates, y-coordinates, and bubble sizes. You can also customize colors and transparency by adding c and alpha parameters.
๐Ÿ“

Syntax

The basic syntax for creating a bubble chart with matplotlib.pyplot.scatter() is:

  • x: list or array of x-axis values.
  • y: list or array of y-axis values.
  • s: list or array of bubble sizes (area of each point).
  • c (optional): colors of bubbles.
  • alpha (optional): transparency level of bubbles.
python
import matplotlib.pyplot as plt

plt.scatter(x, y, s=sizes, c=colors, alpha=0.5)
plt.show()
๐Ÿ’ป

Example

This example shows how to create a bubble chart with different bubble sizes and colors representing data points.

python
import matplotlib.pyplot as plt

# Data points
x = [5, 15, 25, 35, 45]
y = [10, 20, 25, 30, 40]

# Bubble sizes
sizes = [100, 300, 500, 700, 900]

# Bubble colors
colors = ['red', 'blue', 'green', 'orange', 'purple']

plt.scatter(x, y, s=sizes, c=colors, alpha=0.6)
plt.title('Simple Bubble Chart')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.show()
Output
A scatter plot window showing 5 bubbles at specified x and y positions with varying sizes and colors.
โš ๏ธ

Common Pitfalls

Common mistakes when creating bubble charts include:

  • Using s values too small or too large, making bubbles invisible or overlapping excessively.
  • Not matching the length of x, y, and s arrays, causing errors.
  • Forgetting to set alpha for transparency, which can make bubbles hard to distinguish.

Always ensure your data arrays have the same length and choose bubble sizes that visually make sense.

python
import matplotlib.pyplot as plt

# Wrong: sizes array length mismatch
x = [1, 2, 3]
y = [4, 5, 6]
sizes = [100, 200]  # Wrong length

# This will raise an error
# plt.scatter(x, y, s=sizes)

# Correct:
sizes = [100, 200, 300]
plt.scatter(x, y, s=sizes, alpha=0.5)
plt.show()
Output
A scatter plot window showing 3 bubbles with sizes 100, 200, and 300 respectively.
๐Ÿ“Š

Quick Reference

Tips for creating bubble charts in Matplotlib:

  • Use plt.scatter() with s for bubble sizes.
  • Set alpha between 0 and 1 for bubble transparency.
  • Use c to assign colors to bubbles.
  • Ensure all input arrays (x, y, s, c) have the same length.
  • Adjust bubble sizes to improve readability.
โœ…

Key Takeaways

Use plt.scatter() with x, y, and s parameters to create bubble charts.
Ensure sizes array matches x and y lengths to avoid errors.
Customize bubble colors with c and transparency with alpha.
Adjust bubble sizes for clear visualization without overlap.
Always label axes and add a title for better chart understanding.