Matplotlib-Bubble-Scatter-Plots

Scatter & Bubble Plots in Matplotlib — Baby Steps

Keyword: matplotlib scatter • Difficulty: Beginner • Author: Champak Roy

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): scatter and bubble sample

🧪 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 alpha to reduce overplotting (transparency).
  • The s parameter controls marker area (not diameter) — larger values create much bigger bubbles.
  • c + cmap gives a meaningful color dimension; add plt.colorbar() to show the scale.
  • Always call matplotlib.use('Agg') in Pyodide and return the image as base64 (as in the practice runner).
© Learning Sutras — Champak Roy | Made with 💙 in Varanasi

0 Comments

Post a Comment

0 Comments