Zero Grad›كورس Data Analysis›Matplotlib›النوت بوك
← الدرسOpen in Kaggle

Matplotlib¶

Matplotlib is the library under most Python charts: pandas' .plot() and Seaborn both draw with it. This chapter turns the NileCart sales table into charts (lines for trends, bars for comparisons, histograms for distributions, scatter plots for relationships), then combines several charts into one figure, annotates them, and saves them.

Contents

  1. Figure, Axes, and the two ways to draw
  2. Lines
  3. Styling a line
  4. Several lines
  5. Titles, labels, legends, ticks, styles
  6. Scatter plots
  7. Histograms
  8. Bar charts and pie charts
  9. Several plots in one figure
  10. Uneven layouts
  11. Box plots
  12. Text and annotations
  13. Date axes
  14. Saving figures
  15. Case study: do discounts pay?
In [1]:
from pathlib import Path

import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from IPython.display import display

%matplotlib inline
print("matplotlib", mpl.__version__)

# the clean sales table: one row per order line, money in EGP
sales = pd.read_csv("../data/nilecart/sales.csv", parse_dates=["order_date"])
sales["year"] = sales["order_date"].dt.year
sales["month"] = sales["order_date"].dt.month
print(sales.shape)
sales.head(3)
matplotlib 3.10.0
(1466, 20)
Out[1]:
order_id order_date customer_id name governorate region segment product_id product_name category quantity unit_price discount gross revenue unit_cost profit status year month
0 10002 2024-01-01 176 Fatma Hassan Cairo Greater Cairo Consumer 111 Notebook Stationery 5.0 63.0 0.00 315.0 315.0 20 215.0 cancelled 2024 1
1 10001 2024-01-01 132 Yasmin Mostafa Cairo Greater Cairo Corporate 101 Laptop Electronics 9.0 30400.0 0.05 273600.0 259920.0 27200 15120.0 completed 2024 1
2 10004 2024-01-02 131 Yasmin Fawzy Sharqia Delta Corporate 111 Notebook Stationery 10.0 57.0 0.00 570.0 570.0 20 370.0 completed 2024 1

1. Figure, Axes, and the two ways to draw¶

Two words appear in every Matplotlib error message. The Figure is the whole picture. An Axes is one plot inside it, with its own x-axis, y-axis, data, title and legend. One Figure can hold several Axes (Section 9).

Matplotlib offers two styles of drawing. The same chart both ways, the shop's revenue for each calendar month:

In [2]:
monthly = sales.groupby("month")["revenue"].sum()

# 1) pyplot style: plt.* draws on "the current Axes", whichever that is
plt.plot(monthly.index, monthly.values)
plt.title("Revenue by month (pyplot)")
plt.show()
No description has been provided for this image
In [3]:
# 2) object-oriented style: hold the Figure and the Axes, and call their methods
fig, ax = plt.subplots()
ax.plot(monthly.index, monthly.values)
ax.set_title("Revenue by month (OO)")
plt.show()

# 3) pandas draws with Matplotlib too: .plot() returns an Axes
ax = monthly.plot(marker="o", title="Revenue by month (pandas .plot)")
print("pandas returned:", type(ax).__name__)
plt.show()
No description has been provided for this image
pandas returned: Axes
No description has been provided for this image

The same picture three times. The pyplot style is fine for a quick look, but as soon as a figure has more than one plot, "the current Axes" becomes confusing. The rest of this chapter uses the object-oriented (OO) style: fig, ax = plt.subplots(), then ax.something(...). In OO style the setters start with set_: plt.title ↔ ax.set_title, plt.xlabel ↔ ax.set_xlabel, plt.xlim ↔ ax.set_xlim. Since pandas returns an Axes, everything here also works on pandas charts.


2. Lines¶

ax.plot(x, y) joins the points (x[0], y[0]), (x[1], y[1]), … with straight lines, in order. Two points make one straight line; more points make a path. The four quarters of 2025:

In [4]:
quarterly = sales[sales["year"] == 2025].groupby(sales["order_date"].dt.quarter)["revenue"].sum()
print(quarterly.round(0))

fig, ax = plt.subplots()
ax.plot([1, 4], [quarterly[1], quarterly[4]])     # only Q1 and Q4: one straight line
ax.plot(quarterly.index, quarterly.values)        # all four quarters
plt.show()
order_date
1    2875195.0
2    2720173.0
3    2574415.0
4    5507352.0
Name: revenue, dtype: float64
No description has been provided for this image

The straight line says "steady growth". The real path says "flat for nine months, then a jump in Q4". Two points hide a lot.

With only one list, plot treats it as the y values:

In [5]:
fig, ax = plt.subplots()
ax.plot(monthly.values)
ax.set_xlabel("position in the array")
plt.show()
No description has been provided for this image

Matplotlib invented x = 0, 1, 2, …, so January is now at 0. Passing x explicitly avoids this.

Dates on the x-axis work directly. resample("MS") sums the revenue of each month (MS = month start), giving 24 points for 2024–2025:

In [6]:
by_month = sales.set_index("order_date")["revenue"].resample("MS").sum()
print(len(by_month), "months, from", by_month.index.min().date(), "to", by_month.index.max().date())

fig, ax = plt.subplots(figsize=(10, 4))
ax.plot(by_month.index, by_month.values)
ax.set_title("Monthly revenue, 2024-2025")
plt.show()
24 months, from 2024-01-01 to 2025-12-01
No description has been provided for this image

Two peaks, both at the end of the year: White Friday and the New Year, in both years. One line shows more than the whole pivot table.


3. Styling a line¶

Every line has a marker (marker="o", "s", "^", "*", "D"), a line style (linestyle/ls: "-", "--", ":", "-.", "None"), a colour (color/c: "k", "tab:blue", "#0F766E", any CSS name), a width (linewidth/lw), a marker size (ms), marker edge and face colours (mec, mfc) and a transparency (alpha). All at once:

In [7]:
rev_2025 = sales[sales["year"] == 2025].groupby("month")["revenue"].sum()

fig, ax = plt.subplots()
ax.plot(rev_2025.index, rev_2025.values, marker="o", linestyle="--", color="#0F766E",
        linewidth=2, markersize=8, markerfacecolor="white", markeredgecolor="#0F766E")
ax.set_title("2025 revenue by month")
plt.show()
No description has been provided for this image

A shorter form is the format string: marker, line and colour in one string, in any order. "ro" = red circles and no line, "k--s" = black dashed line with squares. Order lines per month, one segment per style:

In [8]:
seg_m = sales.pivot_table(index="month", columns="segment", values="order_id", aggfunc="count")

fig, ax = plt.subplots()
ax.plot(seg_m.index, seg_m["Consumer"], "ro")            # red circles, no line
ax.plot(seg_m.index, seg_m["Corporate"], "k--s")         # black, dashed, squares
ax.plot(seg_m.index, seg_m["Small Business"], "-.y^")    # yellow, dash-dot, triangles
ax.plot(seg_m.index, seg_m.sum(axis=1), "b:", lw=4)      # blue dotted, thick: all segments
plt.show()
No description has been provided for this image

⚠️ ax.plot(x, y, "o") draws markers only, which is a quick scatter plot. Without a format string, plot always joins the points, even when their order means nothing.


4. Several lines¶

Most questions are comparisons, such as did 2025 beat 2024? The simplest way to get two lines is two plot calls:

In [9]:
rev_2024 = sales[sales["year"] == 2024].groupby("month")["revenue"].sum()

fig, ax = plt.subplots()
ax.plot(rev_2024.index, rev_2024.values)
ax.plot(rev_2025.index, rev_2025.values)
plt.show()
No description has been provided for this image

A 2-D array also works: every column becomes a line. A pivot table with months as rows and years as columns is exactly that:

In [10]:
pv = sales.pivot_table(index="month", columns="year", values="revenue", aggfunc="sum")
print("shape of pv:", pv.shape, "-> 12 x-positions, 2 lines")

fig, ax = plt.subplots()
ax.plot(pv.index, pv.values)
plt.show()
shape of pv: (12, 2) -> 12 x-positions, 2 lines
No description has been provided for this image

Matplotlib matches x with the rows of y. With the array flipped:

In [11]:
try:
    plt.plot(pv.index, pv.values.T)
except ValueError as e:
    print("ValueError:", e)
plt.close()
ValueError: x and y must have same first dimension, but have shapes (12,) and (2, 12)

Twelve x values, but each column now has only 2 values, so the shapes don't fit. If y has shape (m, n) and x has m values, the result is n lines. Two more ways to the same chart: one call with several groups, ax.plot(x, y1, "o-", x, y2, "s--"), or the pandas shortcut pv.plot(marker="o"), which also adds the legend.


5. Titles, labels, legends, ticks, styles¶

The charts so far work for exploring, but not for anyone else: no title, no units, months shown as 2, 4, 6, and no way to tell which line is which year. The same chart, finished:

In [12]:
month_names = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

fig, ax = plt.subplots(figsize=(10, 4))
ax.plot(pv.index, pv[2024], "o-", color="#9AA5B1", label="2024")
ax.plot(pv.index, pv[2025], "o-", color="#0F766E", lw=2.5, label="2025")

ax.set_title("Monthly revenue: the end-of-year peak repeats")
ax.set_xlabel("Month")
ax.set_ylabel("Revenue (EGP)")
ax.set_xticks(range(1, 13), month_names)
ax.set_ylim(0, None)                                   # start the y-axis at 0
ax.yaxis.set_major_formatter("{x:,.0f}")               # 2500000 -> 2,500,000
ax.grid(True, axis="y", alpha=0.3)
ax.legend(title="Year", loc="upper left")
plt.show()
No description has been provided for this image

Notes on the legend:

  • ax.legend() collects every line that has a label=. A line without a label is left out.
  • ax.legend(["a", "b"]) labels lines in the order they were drawn, which breaks silently when the code is reordered.
  • loc="best" (the default) picks the emptiest corner; "upper left" and the like fix the position.
In [13]:
fig, ax = plt.subplots()
ax.plot(pv.index, pv[2024])                         # no label -> not in the legend
ax.plot(pv.index, pv[2025], label="2025")
ax.axhline(pv.values.mean(), color="grey", ls=":", label="average month")   # a horizontal reference line
ax.legend()
plt.show()
No description has been provided for this image

A style changes the look of every chart created after it. plt.style.available lists them; with plt.style.context(...) applies one to a single block only:

In [14]:
print(plt.style.available[:8], "...")

with plt.style.context("ggplot"):
    fig, ax = plt.subplots(figsize=(6, 3))
    ax.plot(pv.index, pv[2025], "o-")
    ax.set_title("ggplot style")
    plt.show()
['Solarize_Light2', '_classic_test_patch', '_mpl-gallery', '_mpl-gallery-nogrid', 'bmh', 'classic', 'dark_background', 'fast'] ...
No description has been provided for this image

Under every style is plt.rcParams, a large dictionary of defaults. Setting it once at the top of a notebook gives all its charts one look. The rest of this chapter uses this theme:

In [15]:
plt.rcParams.update({
    "figure.figsize": (8, 4.5),
    "axes.spines.top": False,          # no box around the plot
    "axes.spines.right": False,
    "axes.titlesize": 13,
    "axes.titleweight": "bold",
    "axes.grid": True,
    "grid.alpha": 0.3,
    "axes.formatter.limits": (-7, 9),  # plain numbers on the axes, no "1e6"
    "axes.prop_cycle": mpl.cycler(color=["#0F766E", "#E89B2D", "#D95D4A", "#152B3C", "#7C8B96"]),
})

fig, ax = plt.subplots()
ax.plot(pv.index, pv[2024], "o-", label="2024")
ax.plot(pv.index, pv[2025], "o-", label="2025")
ax.set(title="Same chart, custom theme", xlabel="Month", ylabel="Revenue (EGP)")   # several setters in one call
ax.legend()
plt.show()
No description has been provided for this image

6. Scatter plots¶

Bars and lines show one number per group. A scatter plot shows every row as a dot, with two numbers as x and y: the chart for does this go with that? Does a bigger order mean more profit?

In [16]:
fig, ax = plt.subplots()
ax.scatter(sales["revenue"], sales["profit"])
ax.set(title="Profit vs revenue per order line", xlabel="Revenue (EGP)", ylabel="Profit (EGP)")
plt.show()
No description has been provided for this image

Mostly yes, but there are several "arms", and some dots sit below zero. A colour per category shows whose arms they are. The simplest way to get a legend is one scatter call per group:

In [17]:
fig, ax = plt.subplots()
for cat, part in sales.groupby("category"):
    ax.scatter(part["revenue"], part["profit"], label=cat, alpha=0.6, s=20)
ax.axhline(0, color="black", lw=1)
ax.set(title="Electronics: big revenue, thin (or negative) profit", xlabel="Revenue (EGP)", ylabel="Profit (EGP)")
ax.legend(title="Category")
plt.show()

print("order lines with a loss:", (sales["profit"] < 0).sum(),
      "| all of them Electronics:", sales.loc[sales["profit"] < 0, "category"].eq("Electronics").all())
No description has been provided for this image
order lines with a loss: 32 | all of them Electronics: True

Every dot below zero is an Electronics order. To see why, c= can also take numbers: a colormap (cmap=) turns them into colours, and fig.colorbar shows the scale. s= sets each dot's size the same way. Colour by discount, size by quantity:

In [18]:
elec = sales[sales["category"] == "Electronics"]

fig, ax = plt.subplots()
points = ax.scatter(elec["revenue"], elec["profit"], c=elec["discount"], cmap="viridis",
                    s=elec["quantity"] * 15, alpha=0.7)
fig.colorbar(points, ax=ax, label="discount")
ax.axhline(0, color="black", lw=1)
ax.set(title="Electronics order lines: colour = discount, size = quantity", xlabel="Revenue (EGP)", ylabel="Profit (EGP)")
plt.show()
No description has been provided for this image

The yellow dots, the 20% discounts, sit below zero: the pivot table of the pandas chapter in one glance. (With data=df, column names can be passed directly: ax.scatter("unit_price", "quantity", data=sales).)


7. Histograms¶

What does a typical order look like? is a question about the distribution of one number. A histogram cuts the range into bins and counts the values in each. It is not a bar chart: a bar chart compares categories, while a histogram's bars touch because the bins are continuous.

In [19]:
mean, median = sales["revenue"].mean(), sales["revenue"].median()

fig, ax = plt.subplots()
ax.hist(sales["revenue"], bins=30, edgecolor="white")
ax.axvline(mean, color="#D95D4A", ls="--", lw=2, label=f"mean = {mean:,.0f}")
ax.axvline(median, color="#152B3C", ls=":", lw=2, label=f"median = {median:,.0f}")
ax.set(title="Revenue per order line", xlabel="Revenue (EGP)", ylabel="Number of order lines")
ax.legend()
plt.show()
print(f"skew = {sales['revenue'].skew():.2f}")
No description has been provided for this image
skew = 3.63

Almost everything is crushed into the first bar: a strongly right-skewed column. Most order lines are small (a mouse, a notebook) and a few laptop orders are huge; they pull the mean (about 19,000 EGP) far above the median (3,820).

The number of bins changes the picture. Too few hide the shape; too many turn it into noise. Trying a couple of values is good practice:

In [20]:
for bins in [5, 100]:
    fig, ax = plt.subplots(figsize=(6, 3))
    ax.hist(sales["revenue"], bins=bins, edgecolor="white")
    ax.set(title=f"bins = {bins}", xlabel="Revenue (EGP)", ylabel="Count")
    plt.show()
No description has been provided for this image
No description has been provided for this image

For money, a log axis is often the honest choice: every step is ×10 instead of +10,000, so the 45-pound notebooks and the 300,000-pound laptop orders are both visible. The bins must then be spaced evenly on the log scale, which is what np.logspace does:

In [21]:
log_bins = np.logspace(np.log10(sales["revenue"].min()), np.log10(sales["revenue"].max()), 30)

fig, ax = plt.subplots()
ax.hist(sales["revenue"], bins=log_bins, edgecolor="white")
ax.set_xscale("log")
ax.set(title="Revenue per order line (log scale)", xlabel="Revenue (EGP, log scale)", ylabel="Number of order lines")
plt.show()
No description has been provided for this image

To compare groups, overlap their histograms. alpha makes them see-through, and density=True scales each one so its area is 1, which compares shapes even when the groups have very different sizes:

In [22]:
kwargs = dict(bins=log_bins, alpha=0.5, density=True)

fig, ax = plt.subplots()
for cat in ["Accessories", "Furniture", "Electronics"]:
    ax.hist(sales.loc[sales["category"] == cat, "revenue"], label=cat, **kwargs)
ax.set_xscale("log")
ax.set(title="Each category lives in its own price range", xlabel="Revenue (EGP, log scale)", ylabel="Density")
ax.legend()
plt.show()
No description has been provided for this image

8. Bar charts and pie charts¶

ax.bar(categories, heights) compares one number per category. Three habits make a bar chart good: sort the bars (unless the categories have a natural order, like months), use horizontal bars when the labels are long, and start at 0.

In [23]:
cat_rev = sales.groupby("category")["revenue"].sum().sort_values(ascending=False)

fig, ax = plt.subplots()
bars = ax.bar(cat_rev.index, cat_rev.values, color="#0F766E")
ax.bar_label(bars, fmt="{:,.0f}")                      # the value on top of each bar
ax.set(title="Electronics bring most of the revenue", xlabel="Category", ylabel="Revenue (EGP)")
ax.yaxis.set_major_formatter("{x:,.0f}")
plt.show()
print(f"Electronics share: {cat_rev['Electronics'] / cat_rev.sum():.0%}")
No description has been provided for this image
Electronics share: 81%

Product names are long, so horizontal bars; one bar in a different colour tells the reader where to look:

In [24]:
prod_rev = sales.groupby("product_name")["revenue"].sum().sort_values()      # ascending, so the biggest ends on top
colors = np.where(prod_rev.index == "Phone", "#E89B2D", "#9AA5B1")

fig, ax = plt.subplots(figsize=(8, 5))
ax.barh(prod_rev.index, prod_rev.values, color=colors)
ax.set(title="The phone is the top seller", xlabel="Revenue (EGP)", ylabel="")
ax.xaxis.set_major_formatter("{x:,.0f}")
ax.grid(axis="y", visible=False)
plt.show()
No description has been provided for this image

Grouped bars put 2024 next to 2025 for each category. A first attempt gives both years the category names as x:

In [25]:
cy = sales.pivot_table(index="category", columns="year", values="revenue", aggfunc="sum")

fig, ax = plt.subplots()
ax.bar(cy.index, cy[2024], label="2024", color="#9AA5B1")
ax.bar(cy.index, cy[2025], label="2025", color="#0F766E")     # drawn on top of 2024!
ax.legend()
plt.show()
No description has been provided for this image

No error, but it looks like a stacked chart, and it isn't one. Both calls drew at the same four spots, so 2025 sits in front of 2024: grey is visible only where 2024 was bigger (Electronics, Furniture), and in Accessories 2024 is completely hidden.

⚠️ Matplotlib has no "group" argument: each series is shifted sideways by hand. For two series, each bar is 0.4 wide, one moved 0.2 left and the other 0.2 right. Text can't be shifted (cy.index - 0.2 is a TypeError), so the positions are the numbers 0, 1, 2, 3 and set_xticks puts the names back. (pandas does it in one line: cy.plot(kind="bar").)

In [26]:
x = np.arange(len(cy))                     # 0, 1, 2, 3

fig, ax = plt.subplots()
ax.bar(x - 0.2, cy[2024], width=0.4, label="2024", color="#9AA5B1")
ax.bar(x + 0.2, cy[2025], width=0.4, label="2025", color="#0F766E")
ax.set_xticks(x, cy.index)
ax.set(title="Revenue by category and year", ylabel="Revenue (EGP)")
ax.yaxis.set_major_formatter("{x:,.0f}")
ax.legend()
plt.show()
No description has been provided for this image

A shortcut that keeps the category names: align="edge" starts each bar at the tick instead of centring it there, and a negative width grows the bar to the left:

In [27]:
fig, ax = plt.subplots()
ax.bar(cy.index, cy[2024], width=-0.4, align="edge", label="2024", color="#9AA5B1")
ax.bar(cy.index, cy[2025], width=0.4, align="edge", label="2025", color="#0F766E")
ax.set(title="Revenue by category and year", ylabel="Revenue (EGP)")
ax.yaxis.set_major_formatter("{x:,.0f}")
ax.legend()
plt.show()
No description has been provided for this image

Stacked bars show what each bar is made of: bottom= starts every new layer on top of the previous ones. (pandas: df.plot(kind="bar", stacked=True).)

In [28]:
status_ct = pd.crosstab(sales["category"], sales["status"])[["completed", "shipped", "returned", "cancelled"]]

fig, ax = plt.subplots()
bottom = 0                                 # the first layer starts at the floor
for status in status_ct.columns:
    ax.bar(status_ct.index, status_ct[status], bottom=bottom, label=status)
    bottom = bottom + status_ct[status]    # next layer starts on top of this one
ax.set(title="Order lines by category and status", ylabel="Order lines")
ax.legend(title="Status")
plt.show()
No description has been provided for this image

A pie shows parts of one whole and only works with a few slices; a sorted bar chart is usually clearer (see the principles chapter). For five regions it is acceptable:

In [29]:
region_rev = sales[sales["region"] != "Unknown"].groupby("region")["revenue"].sum().sort_values(ascending=False)

fig, ax = plt.subplots(figsize=(5, 5))
ax.pie(region_rev.values, labels=region_rev.index, autopct="%1.1f%%", startangle=90, counterclock=False,
       explode=[0.08, 0, 0, 0, 0], wedgeprops={"edgecolor": "white"})
ax.set_title("Share of revenue by region")
plt.show()
No description has been provided for this image

9. Several plots in one figure¶

  • What: several charts inside one figure.
  • When to use: to compare charts side by side, or when one page has to tell the whole story.

9.1 The pyplot way¶

plt.subplot(rows, cols, index) picks one cell of a grid. The index starts from 1. This form is common in code found online.

In [30]:
segment_lines = sales.loc[sales["segment"] != "Unknown", "segment"].value_counts()

plt.figure(figsize=(10, 3.5))

plt.subplot(1, 2, 1)                 # 1 row, 2 columns, plot 1
plt.barh(segment_lines.index, segment_lines.values)
plt.title("Order lines by segment")

plt.subplot(1, 2, 2)                 # plot 2
plt.hist(sales["quantity"], bins=10)
plt.title("Quantity per order line")

plt.show()
No description has been provided for this image

9.2 The object-oriented way¶

plt.subplots(rows, cols) returns the Figure and an array of Axes. With a 2 × 2 grid, axs.flat loops over the plots. layout="constrained" keeps titles from overlapping, and fig.suptitle adds one title for the whole figure.

In [31]:
by_cat_month = sales.pivot_table(index="month", columns="category", values="revenue", aggfunc="sum")

fig, axs = plt.subplots(2, 2, figsize=(10, 6), sharex=True, layout="constrained")

for ax, cat in zip(axs.flat, cat_rev.index):
    ax.plot(by_cat_month.index, by_cat_month[cat], marker="o")
    ax.set_title(cat)

fig.suptitle("Monthly revenue by category")
plt.show()
No description has been provided for this image

Every category peaks in November and December.

⚠️ Each plot has its own y-scale. That is right for comparing shapes. To compare sizes, share the scale with sharey=True:

In [32]:
fig, axs = plt.subplots(1, 4, figsize=(12, 3), sharey=True, layout="constrained")

for ax, cat in zip(axs, cat_rev.index):
    ax.plot(by_cat_month.index, by_cat_month[cat])
    ax.set_title(cat)

plt.show()
No description has been provided for this image

On a shared scale, Electronics counts in millions and Stationery becomes a flat line.


10. Uneven layouts¶

  • What: a figure whose plots have different sizes.
  • When to use: when the main chart needs more room, as on a report page or a small dashboard.

10.1 With plt.subplot¶

Each plt.subplot(rows, cols, position) call imagines its own grid, and positions count left to right, then top to bottom. So two grids can be mixed:

  • subplot(2, 1, 1): 2 rows, 1 column, so position 1 is the whole top half.
  • subplot(2, 3, 4), (2, 3, 5), (2, 3, 6): 2 rows, 3 columns, so positions 4, 5, 6 are the bottom row.
┌───────────────────────┐
│    subplot(2, 1, 1)   │
├───────┬───────┬───────┤
│(2,3,4)│(2,3,5)│(2,3,6)│
└───────┴───────┴───────┘

⚠️ Positions 1, 2, 3 of the second grid are skipped: the wide plot already sits there.

In [33]:
plt.figure(figsize=(10, 6))

plt.subplot(2, 1, 1)
plt.plot(monthly.index, monthly.values, marker="o")
plt.title("Revenue by month")

for i, cat in enumerate(["Electronics", "Furniture", "Accessories"]):
    plt.subplot(2, 3, 4 + i)
    plt.hist(sales.loc[sales["category"] == cat, "revenue"], bins=20)
    plt.title(cat)

plt.tight_layout()
plt.show()
No description has been provided for this image

10.2 With subplot_mosaic¶

The layout is drawn as text: every letter is one plot, and a repeated letter makes that plot bigger.

In [34]:
prod = sales.groupby("product_name")["revenue"].sum().sort_values()

fig = plt.figure(figsize=(11, 6), layout="constrained")
axd = fig.subplot_mosaic('''
AAB
CCB
''')

axd["A"].plot(by_month.index, by_month.values)
axd["A"].set_title("Monthly revenue")

axd["B"].barh(prod.index, prod.values)
axd["B"].set_title("Revenue by product")

axd["C"].hist(sales["discount"] * 100, bins=[0, 2.5, 7.5, 12.5, 22.5], rwidth=0.8)
axd["C"].set_title("Discount used (%)")

plt.show()
No description has been provided for this image

11. Box plots¶

  • What: a summary of a distribution in five numbers (minimum, Q1, median, Q3, maximum), with outliers as dots.
  • When to use: to compare a numeric column across many categories without crowding.
In [35]:
sales.groupby("category")["revenue"].describe()[["25%", "50%", "75%", "max"]].round(0)
Out[35]:
25% 50% 75% max
category
Accessories 1284.0 2400.0 4320.0 12600.0
Electronics 22050.0 41800.0 75600.0 336000.0
Furniture 3152.0 7220.0 19950.0 58500.0
Stationery 120.0 228.0 315.0 630.0

ax.boxplot takes one list of values per group:

In [36]:
order = ["Stationery", "Accessories", "Furniture", "Electronics"]
groups = [sales.loc[sales["category"] == c, "revenue"] for c in order]

fig, ax = plt.subplots()
ax.boxplot(groups, tick_labels=order)
ax.set_yscale("log")
ax.set(title="Revenue per order line by category", ylabel="Revenue (log scale)")
plt.show()
No description has been provided for this image

The median Electronics line is 41,800 EGP, against 228 EGP for Stationery, which is why the log scale is needed.

11.1 A styled box plot¶

Horizontal, filled with colour, and without the outlier dots:

In [37]:
fig, ax = plt.subplots()
bp = ax.boxplot(groups, tick_labels=order, vert=False, patch_artist=True, showfliers=False)

for box, color in zip(bp["boxes"], ["lightblue", "khaki", "salmon", "lightgreen"]):
    box.set_facecolor(color)

ax.set_xscale("log")
ax.set(title="Revenue per order line, no outlier dots", xlabel="Revenue (log scale)")
plt.show()
No description has been provided for this image

12. Text and annotations¶

  • What: words, arrows and lines on top of a chart.
  • When to use: when there is one thing the reader must see.

First, where is the peak?

In [38]:
peak_date = by_month.idxmax()
peak_val = by_month.max()
print(peak_date, peak_val)
2024-12-01 00:00:00 2670815.05

ax.annotate adds the label and the arrow: xy is the point, xytext is where the text goes, and arrowprops styles the arrow.

In [39]:
fig, ax = plt.subplots(figsize=(10, 4.5))
ax.plot(by_month.index, by_month.values, marker="o")

ax.annotate(f"Peak: {peak_val:,.0f}", xy=(peak_date, peak_val), xytext=(pd.Timestamp("2024-05-01"), peak_val),
            arrowprops={"arrowstyle": "->", "color": "black"})

ax.set(title="Revenue peaks at the end of every year", ylabel="Revenue (EGP)")
plt.show()
No description has been provided for this image

ax.axhline draws a reference line, and ax.text writes plain text:

In [40]:
average = by_month.mean()

fig, ax = plt.subplots(figsize=(10, 4.5))
ax.plot(by_month.index, by_month.values, marker="o")

ax.axhline(average, color="grey", linestyle=":")
ax.text(by_month.index[0], average * 1.05, f"monthly average {average:,.0f}", color="grey")

ax.set(title="Monthly revenue against the average", ylabel="Revenue (EGP)")
plt.show()
No description has been provided for this image

13. Date axes¶

  • What: a time axis with ticks under control.
  • When to use: for any chart over time, because default date ticks are often crowded.

Two years of daily revenue is 731 points. A locator decides where the ticks go, and a formatter decides how they look. A 30-day average shows the trend, and ax.axvspan shades the White Friday season.

In [41]:
daily = sales.set_index("order_date")["revenue"].resample("D").sum()
smooth = daily.rolling(30, center=True).mean()

fig, ax = plt.subplots(figsize=(11, 4.5))
ax.plot(daily.index, daily.values, color="lightgrey", linewidth=0.6, label="daily")
ax.plot(smooth.index, smooth.values, linewidth=2.5, label="30-day average")

ax.axvspan(pd.Timestamp("2024-11-01"), pd.Timestamp("2024-12-31"), color="orange", alpha=0.15)
ax.axvspan(pd.Timestamp("2025-11-01"), pd.Timestamp("2025-12-31"), color="orange", alpha=0.15)

ax.xaxis.set_major_locator(mdates.MonthLocator(interval=3))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %Y"))
fig.autofmt_xdate()

ax.set(title="Daily revenue: Nov-Dec shaded", ylabel="Revenue (EGP)")
ax.legend(loc="upper left")
plt.show()
No description has been provided for this image

The 30-day average rises in both shaded seasons.


14. Saving figures¶

fig.savefig(path, dpi=..., bbox_inches="tight"). The extension picks the format: .png for slides and messages, .svg or .pdf for print.

⚠️ Call savefig before plt.show(); afterwards the figure is already closed and the saved picture is empty.

In [42]:
Path("output").mkdir(exist_ok=True)

fig, ax = plt.subplots()
ax.barh(region_rev.sort_values().index, region_rev.sort_values().values)
ax.set(title="Revenue by region", xlabel="Revenue (EGP)")
fig.savefig("output/revenue_by_region.png", dpi=150, bbox_inches="tight")
plt.show()
print("saved:", Path("output/revenue_by_region.png").exists())
No description has been provided for this image
saved: True

15. Case study: do discounts pay?¶

The planning question for the next White Friday: should the shop keep giving 20% off?

The discount is an ordered number (0 → 5 → 10 → 20%), so one line per category shows the trend, and a line at zero marks where the shop starts losing money on a sale.

In [43]:
profit_by_disc = sales.pivot_table(index="discount", columns="category", values="profit", aggfunc="mean")
display(profit_by_disc.round(0))

fig, ax = plt.subplots(figsize=(9, 5))
for cat in profit_by_disc.columns:
    ax.plot(profit_by_disc.index * 100, profit_by_disc[cat], marker="o", lw=2, label=cat)
ax.axhline(0, color="black", lw=1)
ax.set_xticks([0, 5, 10, 20])
ax.set(title="20% off Electronics loses money on an average order line",
       xlabel="Discount (%)", ylabel="Average profit per order line (EGP)")
ax.yaxis.set_major_formatter("{x:,.0f}")
ax.legend(title="Category")
plt.show()
category Accessories Electronics Furniture Stationery
discount
0.00 1714.0 10401.0 5940.0 181.0
0.05 1512.0 8250.0 6026.0 159.0
0.10 1332.0 4332.0 5543.0 136.0
0.20 1036.0 -1753.0 3901.0 108.0
No description has been provided for this image

Finding: profit falls with the discount in every category except Furniture, which barely moves until 20%. Electronics fall fastest: from about +10,400 EGP per order line with no discount to about −1,750 at 20%. Their margins are thin, so 20% off pushes the price below cost.

Recommendation: keep the White Friday discounts, but cap Electronics at 10%.


Summary¶

Task Code
New figure + one Axes fig, ax = plt.subplots(figsize=(w, h))
Line ax.plot(x, y, "o--", color=..., lw=..., ms=..., label=...)
Several lines several ax.plot calls · ax.plot(x, Y_2d) · df.plot()
Scatter ax.scatter(x, y, c=..., s=..., alpha=..., cmap=...) + fig.colorbar(points)
Histogram ax.hist(values, bins=..., density=..., alpha=...) · ax.set_xscale("log")
Bars ax.bar(cats, h), ax.barh(...), width= + offsets (grouped), bottom= (stacked), ax.bar_label(bars)
Pie ax.pie(values, labels=..., autopct="%1.1f%%", startangle=90)
Box plot ax.boxplot(groups, tick_labels=..., vert=False, patch_artist=True, showfliers=False)
Grid of plots fig, axs = plt.subplots(r, c, sharey=..., layout="constrained"), fig.suptitle
Uneven layout fig.subplot_mosaic("AAB;CCB"), plt.subplot(2, 3, 4)
Reference lines ax.axhline(y), ax.axvline(x), ax.axvspan(start, end)
Text ax.text(x, y, s), ax.annotate(s, xy=, xytext=, arrowprops=)
Labels ax.set_title, ax.set_xlabel, ax.set_ylabel, ax.set(...), ax.legend()
Axes ax.set_xlim / set_ylim, ax.set_xticks(pos, labels), ax.yaxis.set_major_formatter("{x:,.0f}")
Dates mdates.MonthLocator, mdates.DateFormatter("%b %Y"), fig.autofmt_xdate()
Look plt.style.use(...), with plt.style.context(...), plt.rcParams.update({...})
Save fig.savefig("x.png", dpi=150, bbox_inches="tight") before plt.show()

Next: Seaborn: statistical charts straight from a DataFrame.