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
svalues too small or too large, making bubbles invisible or overlapping excessively. - Not matching the length of
x,y, andsarrays, causing errors. - Forgetting to set
alphafor 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()withsfor bubble sizes. - Set
alphabetween 0 and 1 for bubble transparency. - Use
cto 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.