Scatter & Bubble Plots in Matplotlib — Baby Steps
Scatter plots show relationships between two numeric variables. Bubble plots are an extension where the marker size encodes a third variable (like population, sales, or magnitude). Below you'll find short theory, code examples, a static preview, and an interactive Pyodide practice area.
💡 Step-by-Step Tutorial
1) Import Matplotlib & NumPy
import matplotlib.pyplot as plt
import numpy as np
2) Prepare sample data
x = np.random.rand(50) * 10
y = np.random.rand(50) * 8
sizes = np.random.rand(50) * 300 + 30 # marker sizes for bubble plot
colors = np.random.rand(50) # color mapping
3) Basic scatter plot
plt.scatter(x, y)
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.title('Simple Scatter Plot')
plt.show()
4) Scatter with color & size
plt.scatter(x, y, s=sizes, c=colors, cmap='viridis', alpha=0.7, edgecolor='k')
plt.colorbar(label='color scale')
plt.title('Bubble plot — size & color')
plt.show()
5) Annotate & highlight
# highlight the largest bubble
idx = np.argmax(sizes)
plt.scatter(x, y, s=sizes, c=colors, cmap='plasma', alpha=0.7, edgecolors='w')
plt.scatter(x[idx], y[idx], s=sizes[idx]*1.2, facecolors='none', edgecolor='red', linewidth=1.8)
plt.text(x[idx]+0.2, y[idx], 'Largest', color='red')
💬 Tip: use alpha to avoid overplotting, and cmap to pick appealing color maps (eg. viridis, plasma, magma).
📊 Sample static output (Scatter + Bubble):
🧪 Practice: Scatter & Bubble with Pyodide
Click Preload Pyodide once to install matplotlib and numpy. Then press Run & Render to display your chart as an image!
Idle
Console output:
No chart yet — run code to render a PNG here.
🧠Tips & Notes
- Use
alphato reduce overplotting (transparency). - The
sparameter controls marker area (not diameter) — larger values create much bigger bubbles. c+cmapgives a meaningful color dimension; addplt.colorbar()to show the scale.- Always call
matplotlib.use('Agg')in Pyodide and return the image as base64 (as in the practice runner).
0 Comments