Skip to main content

Matplotlib (Part 1): Line, Bar, and Scatter Plots

Following Introduction to data visualization, this lesson focuses on Matplotlib’s object-oriented API (fig, ax = plt.subplots()) rather than implicit global state—you will thank yourself when plots stack in notebooks or web exports.

Install if needed:

pip install matplotlib

📚 Prerequisites

  • Comfortable running short Python scripts locally or in a notebook.

🎯 What you'll master

  • Instantiate figures and axes explicitly.
  • Plot line charts for ordered measurements, bars for categorical comparisons, scatter plots for correlations.

import matplotlib.pyplot as plt

days = range(7)
sessions = [120, 135, 128, 150, 160, 170, 190]

fig, ax = plt.subplots()
ax.plot(days, sessions, marker="o")
ax.set_title("Daily active sessions")
ax.set_xlabel("Day index")
ax.set_ylabel("Sessions")
plt.show()

Vertical bar chart — categorical totals

regions = ["North", "South", "East"]
revenue = [42, 53, 38]

fig, ax = plt.subplots()
ax.bar(regions, revenue, color=["#4472c4", "#ed7d31", "#a5a5a5"])
ax.set_ylabel("Revenue ($k)")
plt.show()

Scatter — relationships between paired measurements

cpu = [20, 45, 60, 82, 50]
latency = [120, 190, 250, 400, 200]

fig, ax = plt.subplots()
ax.scatter(cpu, latency, alpha=0.85)
ax.set_xlabel("CPU utilization (%)")
ax.set_ylabel("Latency (ms)")
plt.show()

💡 Key takeaways

  • Prefer explicit Axes variables so notebooks do not bleed styles across cells.
  • Line plots assume comparable scales on the independent axis—sort your data chronologically!

➡️ Next steps

Polish typography and palettes in Matplotlib (Part 2): Labels, titles, colors.