Rana Maninder Singh
Lesson 9 of 12Data Analysis with Python

Matplotlib

Lesson opener

In one line: Line, bar, pie, histogram, scatter, subplots.

Why it matters: Histograms show how values cluster - essential before choosing averages or spotting skew.

Before this lesson: EDA

Before you start

ResourceLink
PreviousEDA
NextSeaborn


What you will learn

Line, bar, pie, histogram, scatter, subplots.

Chart picker cheat sheet
Chart picker cheat sheet

Basics

[Line chart from groupby]

WHY Minimal matplotlib workflow: group, plot, title, save.

WHEN Use for first revenue-by-month chart from real sales.csv.

import matplotlib.pyplot as plt
import pandas as pd
sales = pd.read_csv("data/sales.csv")
by_month = sales.groupby("month")["revenue"].sum()
by_month.plot(kind="line")
plt.title("Revenue by month")
plt.tight_layout()
plt.savefig("outputs/ds10_line.png")
plt.show()

Breaking it down:

Use this when: you need a quick monthly trend PNG for a slide.


Chart types

typeuse
barcategories
pieshare (few slices)
histdistribution
scatterrelationship
subplotsmultiple panels

[Four chart types subplots]

WHY One figure, four panels — bar, line, scatter, pie for the same dataset story.

WHEN Use when building a chart-type reference sheet.

import matplotlib.pyplot as plt

# Hard-coded business numbers — no file import needed
product_categories = ["Lamps", "Chairs", "Monitors", "Keyboards"]
category_sales = [12500, 28400, 45200, 9800]

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
monthly_revenue = [42, 45, 48, 44, 52, 55, 58, 54, 60, 63, 59, 68]

advertising_spend = [8, 12, 15, 10, 18, 20, 22, 19, 24, 26, 23, 28]
sales_from_ads = [35, 42, 48, 38, 52, 55, 58, 50, 62, 65, 60, 70]

regions = ["North", "South", "West", "East"]
market_share = [32, 28, 24, 16]

fig, axes = plt.subplots(2, 2, figsize=(10, 8))

# Top-left — bar chart: sales by product category
axes[0, 0].bar(product_categories, category_sales, color="steelblue")
axes[0, 0].set_title("Sales by product category")
axes[0, 0].set_ylabel("Sales (USD thousands)")
axes[0, 0].tick_params(axis="x", rotation=20)

# Top-right — line chart: monthly revenue trend
axes[0, 1].plot(months, monthly_revenue, marker="o", color="darkgreen")
axes[0, 1].set_title("Monthly revenue (12 months)")
axes[0, 1].set_ylabel("Revenue (USD thousands)")
axes[0, 1].tick_params(axis="x", rotation=45)

# Bottom-left — scatter: advertising spend vs sales
axes[1, 0].scatter(advertising_spend, sales_from_ads, color="coral")
axes[1, 0].set_title("Advertising spend vs sales")
axes[1, 0].set_xlabel("Ad spend (USD thousands)")
axes[1, 0].set_ylabel("Sales (USD thousands)")

# Bottom-right — pie chart: market share by region
axes[1, 1].pie(market_share, labels=regions, autopct="%1.0f%%", startangle=90)
axes[1, 1].set_title("Market share by region")

plt.tight_layout()
plt.savefig("outputs/ds10_four_chart_types.png")
plt.show()

Breaking it down:

Use this when: training new analysts on which chart fits which question.

When to use which chart


Histogram — distribution of one numeric column

[Standalone histogram]

WHY: Histograms show how values cluster — essential before choosing averages or spotting skew.

WHEN: First look at salary, order totals, or response times.

import matplotlib.pyplot as plt

order_totals = [45, 320, 52, 410, 298, 89, 120, 55, 380, 95]

plt.figure(figsize=(6, 4))
plt.hist(order_totals, bins=5, edgecolor="black", color="#2563eb", alpha=0.85)
plt.title("Distribution of order totals")
plt.xlabel("Order total (USD)")
plt.ylabel("Frequency")
plt.tight_layout()
plt.savefig("outputs/ds10_histogram.png")
plt.show()

Breaking it down:

Use this when: someone asks "are most orders small with a few big ones?" — the histogram answers visually.


Essential commands

Command / actionWhat it does
import matplotlib.pyplot as pltImport pyplot interface.
plt.plot / .bar / .hist / .scatterCore chart types.
plt.subplots(nrows, ncols)Multiple charts in one figure.
plt.savefig('outputs/file.png')Export static image.

Practice

Do this now: Save 4 chart types to outputs/; one figure with subplots.

Checklist

  • [ ] line/bar/hist/scatter created
  • [ ] subplots used
  • [ ] PNG saved