TExcelTAD
Home › Matplotlib › Matplotlib Mini Project

Matplotlib Mini Project

In this project you'll build a one-page sales dashboard for a small online shop, step by step. It combines most of the course: generating data, line charts with rolling averages, annotations, sorted bar charts, a heatmap, a layout built with subplot_mosaic, shared styling with rc_context, and saving the finished figure.

The final result is a single figure with four panels and a row of headline numbers (KPIs):

text
┌──────────────┬──────────────┬──────────────┐
│ Orders: 4,1… │ Revenue: …   │ Avg basket…  │   ← KPI tiles
├──────────────┴──────────────┼──────────────┤
│ Daily orders + 7-day avg    │ Revenue by   │
│                             │ category     │
├─────────────────────────────┼──────────────┤
│ Orders by weekday and hour  │ Basket sizes │
└─────────────────────────────┴──────────────┘

Every step is a complete program you can run and modify. The data is simulated with a seeded random generator, so you get the same numbers every time.

Step 1: Generate the data

Real dashboards read from a database or a CSV file. We simulate one quarter (91 days) of orders with NumPy instead: a weekly pattern (busier weekends), a slow upward trend, and some noise. Each order gets a category, an hour of the day and a basket value.

python · try it yourself
import numpy as np

rng = np.random.default_rng(2024)
days = np.arange("2024-01-01", "2024-04-01", dtype="datetime64[D]")
weekday = (days.view("int64") - 4) % 7          # 0 = Monday

base = 38 + 0.12 * np.arange(days.size)                 # slow growth
weekend_boost = np.where(weekday >= 5, 12, 0)
daily_orders = rng.poisson(base + weekend_boost)

categories = np.array(["Books", "Games", "Music", "Gadgets", "Toys"])
n = daily_orders.sum()
order_cat = rng.choice(categories, size=n, p=[0.30, 0.20, 0.15, 0.25, 0.10])
profile = np.exp(-((np.arange(24) - 20) ** 2) / 18) + 0.3 * np.exp(-((np.arange(24) - 12) ** 2) / 6) + 0.02
order_hour = rng.choice(24, size=n, p=profile / profile.sum())   # evening peak, small lunch peak
order_value = np.round(rng.gamma(shape=3, scale=12, size=n), 2)
order_day = np.repeat(np.arange(days.size), daily_orders.tolist())

print("Days:", days.size, "from", days[0], "to", days[-1])
print("Orders:", n)
print(f"Revenue: {order_value.sum():,.2f}")
print("First week of orders:", daily_orders[:7].tolist())
print("Weekdays of the first week:", weekday[:7].tolist())
Days: 91 from 2024-01-01 to 2024-03-31
Orders: 4130
Revenue: 146,553.39
First week of orders: [41, 34, 27, 36, 40, 40, 53]
Weekdays of the first week: [0, 1, 2, 3, 4, 5, 6]

The weekday trick works because 1970-01-01 was a Thursday: subtracting 4 and taking the remainder by 7 maps Monday to 0. np.repeat gives every order the index of its day, which we'll need for the heatmap.

Step 2: Daily orders with a trend line

Daily data is noisy. A 7-day rolling average smooths out the weekly rhythm and shows the trend. We compute it with np.convolve, then annotate the busiest day:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

rng = np.random.default_rng(2024)
days = np.arange("2024-01-01", "2024-04-01", dtype="datetime64[D]")
weekday = (days.view("int64") - 4) % 7
daily_orders = rng.poisson(38 + 0.12 * np.arange(days.size) + np.where(weekday >= 5, 12, 0))

rolling = np.convolve(daily_orders, np.ones(7) / 7, mode="valid")   # 85 values
peak = daily_orders.argmax()

fig, ax = plt.subplots(figsize=(8, 3.5), layout="constrained")
ax.plot(days, daily_orders, color="0.7", lw=1, label="daily")
ax.plot(days[6:], rolling, color="C0", lw=2.5, label="7-day average")
ax.annotate(f"Peak: {daily_orders[peak]}", xy=(days[peak], daily_orders[peak]),
            xytext=(-60, 5), textcoords="offset points",
            arrowprops=dict(arrowstyle="->", color="0.3"))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%d %b"))
ax.set(ylabel="Orders", title="Daily orders")
ax.legend(loc="upper left")
plt.show()

print("Peak day:", days[peak], "with", daily_orders[peak], "orders")
print(f"7-day average: {rolling[0]:.1f} at the start, {rolling[-1]:.1f} at the end")
Peak day: 2024-03-10 with 72 orders
7-day average: 38.7 at the start, 51.4 at the end

The rolling average starts on day 7 (days[6:]) because it needs a full week of data.

Step 3: Revenue by category

A sorted horizontal bar chart is the clearest way to rank categories. Labels on the bars replace the need for a grid:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(7)
categories = np.array(["Books", "Games", "Music", "Gadgets", "Toys"])
order_cat = rng.choice(categories, size=4000, p=[0.30, 0.20, 0.15, 0.25, 0.10])
order_value = np.round(rng.gamma(shape=3, scale=12, size=4000), 2)

revenue = {c: order_value[order_cat == c].sum() for c in categories}
ranked = sorted(revenue.items(), key=lambda kv: kv[1])
names = [c for c, _ in ranked]
values = [v / 1000 for _, v in ranked]            # in thousands

fig, ax = plt.subplots(figsize=(5, 3.5), layout="constrained")
bars = ax.barh(names, values, color="C2")
ax.bar_label(bars, fmt="%.1fk", padding=3)
ax.set_xlim(0, max(values) * 1.2)
ax.spines[["top", "right"]].set_visible(False)
ax.set(xlabel="Revenue (thousand €)", title="Revenue by category")
plt.show()

for c, v in reversed(ranked):
    print(f"{c:<8} {v:>10,.2f}")
Books     43,136.62
Gadgets   36,465.86
Games     29,749.01
Music     21,121.86
Toys      14,085.06

Step 4: When do people order?

A heatmap of orders by weekday and hour reveals the shop's rhythm. We count orders into a 7 × 24 grid with np.add.at, which adds 1 at each (weekday, hour) pair, even when pairs repeat:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(11)
n = 4000
weekday = rng.choice(7, size=n, p=[0.12, 0.12, 0.13, 0.13, 0.15, 0.18, 0.17])
hour_profile = np.exp(-((np.arange(24) - 20) ** 2) / 18) + 0.3 * np.exp(-((np.arange(24) - 12) ** 2) / 6) + 0.02
hour = rng.choice(24, size=n, p=hour_profile / hour_profile.sum())

grid = np.zeros((7, 24), dtype=int)
np.add.at(grid, (weekday, hour), 1)

fig, ax = plt.subplots(figsize=(9, 3.5), layout="constrained")
im = ax.imshow(grid, cmap="Blues", aspect="auto")
ax.set_yticks(range(7), ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])
ax.set_xticks(range(0, 24, 3), [f"{h:02d}:00" for h in range(0, 24, 3)])
fig.colorbar(im, ax=ax, label="Orders")
ax.set_title("Orders by weekday and hour")
plt.show()

d, h = np.unravel_index(grid.argmax(), grid.shape)
print("Total counted:", grid.sum())
print("Busiest slot:", ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][d], f"{h:02d}:00", "with", grid[d, h], "orders")
Total counted: 4000
Busiest slot: Sat 20:00 with 96 orders

Step 5: Assemble the dashboard

Now we put everything into one figure. subplot_mosaic describes the layout, a rc_context gives all panels the same clean style, and three text-only Axes act as KPI tiles. Finally we save the figure into memory, as a web app would before sending it to a browser:

python · try it yourself
import io
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# ---------- data ----------
rng = np.random.default_rng(2024)
days = np.arange("2024-01-01", "2024-04-01", dtype="datetime64[D]")
weekday_of_day = (days.view("int64") - 4) % 7
daily = rng.poisson(38 + 0.12 * np.arange(days.size) + np.where(weekday_of_day >= 5, 12, 0))
n = daily.sum()

categories = np.array(["Books", "Games", "Music", "Gadgets", "Toys"])
cat = rng.choice(categories, size=n, p=[0.30, 0.20, 0.15, 0.25, 0.10])
value = np.round(rng.gamma(shape=3, scale=12, size=n), 2)
order_weekday = np.repeat(weekday_of_day, daily.tolist())
profile = np.exp(-((np.arange(24) - 20) ** 2) / 18) + 0.3 * np.exp(-((np.arange(24) - 12) ** 2) / 6) + 0.02
hour = rng.choice(24, size=n, p=profile / profile.sum())

# ---------- figure ----------
style = {"axes.spines.top": False, "axes.spines.right": False,
         "axes.titleweight": "bold", "axes.titlesize": 11, "font.size": 9}
layout = [["k1", "k2", "k3"],
          ["trend", "trend", "cats"],
          ["heat", "heat", "hist"]]

with plt.rc_context(style):
    fig, ax = plt.subplot_mosaic(layout, figsize=(11, 7.5), layout="constrained",
                                 height_ratios=[0.45, 1, 1])
    fig.suptitle("Shop dashboard · Q1 2024", fontsize=15, fontweight="bold")

    # KPI tiles
    kpis = [("Orders", f"{n:,}"), ("Revenue", f"€{value.sum() / 1000:,.1f}k"),
            ("Avg basket", f"€{value.mean():.2f}")]
    for key, (label, text) in zip(["k1", "k2", "k3"], kpis):
        a = ax[key]
        a.set_axis_off()
        a.text(0.5, 0.62, text, ha="center", va="center", fontsize=22, fontweight="bold", color="C0")
        a.text(0.5, 0.18, label, ha="center", va="center", fontsize=11, color="0.4")

    # trend
    rolling = np.convolve(daily, np.ones(7) / 7, mode="valid")
    ax["trend"].plot(days, daily, color="0.75", lw=1, label="daily")
    ax["trend"].plot(days[6:], rolling, color="C0", lw=2.5, label="7-day avg")
    ax["trend"].xaxis.set_major_locator(mdates.MonthLocator())
    ax["trend"].xaxis.set_major_formatter(mdates.DateFormatter("%b"))
    ax["trend"].set(title="Daily orders", ylabel="Orders")
    ax["trend"].legend(loc="upper left", frameon=False)

    # categories
    revenue = {c: value[cat == c].sum() / 1000 for c in categories}
    ranked = sorted(revenue.items(), key=lambda kv: kv[1])
    bars = ax["cats"].barh([c for c, _ in ranked], [v for _, v in ranked], color="C2")
    ax["cats"].bar_label(bars, fmt="%.1fk", padding=2)
    ax["cats"].set_xlim(0, ranked[-1][1] * 1.25)
    ax["cats"].set(title="Revenue by category (k€)")

    # heatmap
    grid = np.zeros((7, 24), dtype=int)
    np.add.at(grid, (order_weekday, hour), 1)
    im = ax["heat"].imshow(grid, cmap="Blues", aspect="auto")
    ax["heat"].set_yticks(range(7), ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])
    ax["heat"].set_xticks(range(0, 24, 3), [f"{h:02d}h" for h in range(0, 24, 3)])
    ax["heat"].set_title("Orders by weekday and hour")
    fig.colorbar(im, ax=ax["heat"], shrink=0.9)

    # basket histogram
    ax["hist"].hist(value, bins=30, color="C1", edgecolor="white")
    ax["hist"].axvline(value.mean(), color="k", linestyle="--", lw=1)
    ax["hist"].set(title="Basket sizes", xlabel="€")

buffer = io.BytesIO()
fig.savefig(buffer, format="png", dpi=100)
plt.show()

print("Panels:", len(fig.axes), "(incl. colorbar)")
print("KPIs:", " | ".join(f"{label} {text}" for label, text in kpis))
print("Top category:", ranked[-1][0])
print("PNG size:", len(buffer.getvalue()), "bytes")
Panels: 8 (incl. colorbar)
KPIs: Orders 4,130 | Revenue €149.0k | Avg basket €36.07
Top category: Books
PNG size: 97032 bytes

On your own computer, replace the BytesIO buffer with a file name, for example fig.savefig("dashboard.png", dpi=150, bbox_inches="tight"), and the dashboard is ready to drop into a report.

Ideas to extend the project

  1. Compare with last quarter: add a dashed line for the previous period to the trend panel and a "+x %" change under each KPI.
  2. Highlight weekends: shade Saturdays and Sundays in the trend panel with axvspan.
  3. Category trend: replace the histogram with a stackplot of weekly revenue per category.
  4. Real data: load orders with pandas from a CSV file, group them with groupby, and feed the results into the same plotting code.
  5. Make it reusable: move each panel into a function draw_trend(ax, data) etc., so the same dashboard can be produced for any month.

Test yourself

Why does the 7-day rolling average start at days[6:]?

  1. The first week is a holiday
  2. The average needs 7 values, so the first full window ends on day 7
  3. np.convolve drops 6 values at random
  4. To leave room for the legend

Why were the KPI tiles made with set_axis_off() and text()?

  1. Matplotlib has no other way to draw text
  2. They are Axes used purely as text boxes, so ticks and spines would only add clutter
  3. To make them clickable
  4. Because constrained layout requires it

What is the benefit of wrapping the figure in plt.rc_context(style)?

  1. It makes the figure render faster
  2. All panels share one style without changing Matplotlib's global defaults
  3. It saves the figure automatically
  4. It is required for subplot_mosaic