Skip to content

28. Visualization — Mini-project

The leadership team of the shop meets in January to review 2024. The finance analyst has the numbers, but a table of 20,228 order lines convinces nobody. You are asked for a chart pack: a small set of charts, each answering one business question, saved as image files that drop straight into the slides, plus one interactive chart for the analysts who want to dig deeper.

The questions the team asked:

  1. Did revenue grow in 2024, and when in the year do we earn it?
  2. Which categories bring revenue, and which bring profit?
  3. Where did growth come from: which regions and categories grew, and which shrank?
  4. Is the online channel taking over?
  5. Which single days matter most?

Write a script, chart_pack.py, that loads the data, computes what each chart needs, draws five static charts into output/chart_pack/ and writes one interactive HTML chart next to them. Anyone must be able to rerun it next year with one command.

  • data/sales.csv: 20,228 order lines from 2023-01-01 to 2024-12-31 with order_date, region, channel, product_id, category, quantity and revenue.
  • data/products.csv: 30 products with unit_cost, the cost to the shop of one unit. Join it on product_id to compute gross profit = revenue − unit cost × quantity.

The data dictionary describes both files. Two facts help you check your work: total revenue is 3,596,523.83 USD, and the two largest days are the Black Fridays 2023-11-24 and 2024-11-29.

Your script must:

  1. Load both files, join them with a check that each sales line finds exactly one product (validate="many_to_one"), and add profit and year columns.
  2. Set one theme for all charts with a color-blind-friendly palette.
  3. Draw five static charts with the object-oriented Matplotlib API or Seaborn, one per question 1–5. Pick the chart type with the chart-choice guide of the lesson and justify it in a comment.
  4. Give every chart a title that states the finding, axis labels with units, readable tick labels (thousands as k, percentages as %) and a legend where colors carry meaning.
  5. Keep bar charts at zero. Use a diverging colormap centered at zero for growth. Annotate at least two charts (a peak, a threshold or the top days).
  6. Save each chart with fig.savefig(..., dpi=150, bbox_inches="tight") into output/chart_pack/ before showing it.
  7. Write one Plotly Express chart with useful tooltips to output/chart_pack/ as HTML.
  8. Print the number behind each finding, and end with assert checks: the total revenue, the files on disk, the sign of the growth.
  1. Load and join. Read sales.csv with parse_dates=["order_date"] and merge products.csv on product_id. Compute profit and year. Print the shape and the total revenue.

  2. Set the theme and helpers. Call sns.set_theme once. Create the output folder. Write a FuncFormatter for thousands and a save(fig, name) function that saves a figure and returns its path.

  3. Question 1, the trend. Monthly revenue per year as two lines on a January–December axis, from zero, with the peak month annotated.

  4. Question 2, revenue and profit. One horizontal bar per category with 2024 revenue, sorted, and the gross margin rate written next to each bar.

  5. Question 3, growth. A table of 2024 vs 2023 revenue growth with regions as rows and categories as columns. Draw it as an annotated heatmap with a diverging colormap, centered at 0.

  6. Question 4, channels. The online share of revenue per month as a line with a 50% reference line.

  7. Question 5, the top days. Daily revenue in 2024 as a thin line, a 7-day rolling mean on top, and the three largest days annotated.

  8. The interactive chart. Monthly revenue by category as stacked bars with Plotly Express, saved with write_html.

  9. Check. Print the findings, list the saved files and assert what must be true.

A skeleton to start from:

chart_pack.py (starter)
from pathlib import Path
import matplotlib.pyplot as plt
import pandas as pd
import plotly.express as px
import seaborn as sns
from matplotlib.ticker import FuncFormatter, PercentFormatter
OUT = Path("output/chart_pack")
# TODO: theme, output folder, thousands formatter, save(fig, name) helper
# --- Data ---------------------------------------------------------------
# TODO: load sales and products, merge, add profit and year
# --- Q1 trend ------------------------------------------------------------
# TODO: monthly revenue per year, line chart, annotate the peak, save, show
# --- Q2 to Q5 and the interactive chart ----------------------------------
# TODO: one block per question
# --- Checks --------------------------------------------------------------
# TODO: print the findings, list the files, assert
Criterion Points Full points when
Runs end to end 2 python chart_pack.py runs with no error and no warning
Correct data 3 The join is validated; the printed numbers match the reference output
Chart choice 3 Each question gets a fitting chart type, justified in a comment
Labels and formats 3 Finding titles, axis labels with units, k and % tick labels, legends where needed
Honesty and color 3 Bars from zero; a diverging map centered at 0 for growth; color-blind-friendly palette
Annotations 2 At least two charts point the reader to the key fact
Output files 2 Five PNG files and one HTML file in output/chart_pack/, saved before plt.show()
Checks 2 Findings printed; asserts on totals, files and growth
Total 20 16 or more: you are ready for module 29
  1. Combine the five static charts into one dashboard page with plt.subplot_mosaic, reusing one function per chart.
  2. Add a sixth chart: the distribution of discounts per month as a 100% stacked bar. Do deeper discounts explain the November peak?
  3. Save every chart also as SVG, and compare the file sizes with the PNG files.
  4. Turn the script into a command-line tool (module 08) with --year and --out options, so that next January’s review is one command.
  5. Rebuild question 3 with Plotly’s px.imshow(..., text_auto=".0%"), so that the analysts can hover over each cell.

Try the project yourself first. Then compare. Your chart styling can differ; your numbers must not.

Reference solution

The solution runs as one script. It is split into blocks here so that each chart appears after its code.

chart_pack.py (part 1: data and helpers)
import calendar
from pathlib import Path
import matplotlib.pyplot as plt
import pandas as pd
import plotly.express as px
import seaborn as sns
from matplotlib.ticker import FuncFormatter, PercentFormatter
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
sns.set_theme(style="whitegrid", palette="colorblind")
OUT = Path("output/chart_pack")
OUT.mkdir(parents=True, exist_ok=True)
K = FuncFormatter(lambda value, pos: f"{value / 1000:,.0f}k")
ARROW = {"arrowstyle": "->", "color": "0.3"}
def save(fig, name):
"""Save a figure as a PNG in the chart pack folder and return the path."""
path = OUT / f"{name}.png"
fig.savefig(path, dpi=150, bbox_inches="tight")
return path
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
products = pd.read_csv("data/products.csv")
sales = sales.merge(products[["product_id", "unit_cost"]], on="product_id",
validate="many_to_one")
sales["profit"] = sales["revenue"] - sales["unit_cost"] * sales["quantity"]
sales["year"] = sales["order_date"].dt.year
print(sales.shape)
revenue, profit = sales["revenue"].sum(), sales["profit"].sum()
print(f"revenue {revenue:,.2f} USD, profit {profit:,.2f} USD")
Output
(20228, 16)
revenue 3,596,523.83 USD, profit 1,760,135.83 USD
chart_pack.py (part 2: Q1, the monthly trend)
# Q1: a line chart, because the question is a change over ordered time.
monthly = (
sales.groupby(["year", sales["order_date"].dt.month.rename("month")])["revenue"]
.sum()
.unstack(0)
)
fig, ax = plt.subplots(figsize=(8, 4))
for year in monthly.columns:
ax.plot(monthly.index, monthly[year], marker="o", label=str(year))
peak_month = monthly[2024].idxmax()
peak_value = monthly[2024].max()
ax.annotate(f"{calendar.month_abbr[peak_month]} 2024: {peak_value / 1000:,.0f}k",
xy=(peak_month, peak_value), xytext=(6, 285_000), arrowprops=ARROW)
growth = monthly[2024].sum() / monthly[2023].sum() - 1
ax.set_xticks(range(1, 13), labels=calendar.month_abbr[1:])
ax.yaxis.set_major_formatter(K)
ax.set_ylim(0, None)
ax.set(title=f"Revenue grew {growth:.0%} in 2024; November–December bring the most",
xlabel="Month", ylabel="Revenue (USD)")
ax.legend(title="Year", frameon=False)
paths = [save(fig, "q1_monthly_trend")]
plt.show()
print(f"growth {growth:.1%}; Nov+Dec share of 2024: "
f"{monthly.loc[[11, 12], 2024].sum() / monthly[2024].sum():.1%}")
Output
growth 18.6%; Nov+Dec share of 2024: 29.3%
Monthly revenue for 2023 and 2024 from zero: 2024 is above 2023 in most months, both years climb steeply in November and December, and an arrow marks the December 2024 peak of 303k.
Q1: monthly revenue, 2023 vs 2024.
chart_pack.py (part 3: Q2, revenue and margin by category)
# Q2: sorted horizontal bars, because we compare one number across categories;
# the margin rate goes into the bar labels, so one chart answers both halves.
cat = (
sales[sales["year"] == 2024]
.groupby("category")[["revenue", "profit"]]
.sum()
.assign(margin=lambda d: d["profit"] / d["revenue"])
.sort_values("revenue")
)
fig, ax = plt.subplots(figsize=(8, 4))
bars = ax.barh(cat.index, cat["revenue"], color="C0")
ax.bar_label(bars, labels=[f"{r / 1000:,.0f}k · margin {m:.0%}"
for r, m in zip(cat["revenue"], cat["margin"])], padding=4)
ax.xaxis.set_major_formatter(K)
ax.set_xlim(0, cat["revenue"].max() * 1.35)
ax.set(title="Electronics brings half the revenue at the thinnest margin",
xlabel="Revenue 2024 (USD)")
paths.append(save(fig, "q2_category_revenue_margin"))
plt.show()
print(cat[["revenue", "margin"]].round(3).sort_values("revenue", ascending=False))
Output
revenue margin
category
Electronics 939924.77 0.389
Home 397844.84 0.552
Sports 299576.31 0.577
Clothing 170699.61 0.649
Beauty 85444.53 0.686
Books 57444.18 0.668
Sorted horizontal bars of 2024 revenue: Electronics 940k with a 39% margin, then Home 398k (55%), Sports 300k (58%), Clothing 171k (65%), Beauty 85k (69%) and Books 57k (67%).
Q2: 2024 revenue by category with the gross margin rate.
chart_pack.py (part 4: Q3, growth by region and category)
# Q3: an annotated heatmap, because the question crosses two categorical
# dimensions; a diverging map centered at 0 separates growth from decline.
by_year = sales.pivot_table(index=["region", "category"], columns="year",
values="revenue", aggfunc="sum")
growth_table = (by_year[2024] / by_year[2023] - 1).unstack("category")
fig, ax = plt.subplots(figsize=(8.5, 3.6))
sns.heatmap(growth_table, annot=True, fmt=".0%", cmap="vlag", vmin=-0.6, vmax=0.6,
linewidths=1, ax=ax,
cbar_kws={"label": "growth 2024 vs 2023", "format": PercentFormatter(1)})
ax.set(title="Every region and category grew; Electronics grew least",
xlabel="", ylabel="")
ax.tick_params(axis="y", labelrotation=0)
paths.append(save(fig, "q3_growth_heatmap"))
plt.show()
print(growth_table.round(3))
Output
category Beauty Books Clothing Electronics Home Sports
region
East 0.322 0.203 0.167 0.109 0.558 0.233
North 0.322 0.212 0.093 0.055 0.502 0.152
South 0.462 0.097 0.196 0.081 0.347 0.254
West 0.162 0.138 0.309 0.081 0.381 0.262
Growth heatmap with all cells red: Home grew 35–56% in every region and Beauty 46% in the South, while Electronics grew only 5–11%.
Q3: revenue growth from 2023 to 2024 by region and category.
chart_pack.py (part 5: Q4, the online share)
# Q4: a line chart of a share over time, with the 50% line as the reference.
# freq="MS" labels each month by its first day, so each point sits inside its
# month; month-end labels would put December on the January tick.
by_month = sales.groupby([pd.Grouper(key="order_date", freq="MS"), "channel"])[
"revenue"].sum().unstack()
online_share = by_month["online"] / by_month.sum(axis=1)
fig, ax = plt.subplots(figsize=(8, 3.6))
ax.plot(online_share.index, online_share, marker="o", color="C2")
ax.axhline(0.5, color="0.4", linestyle="--", linewidth=1)
ax.text(online_share.index[0], 0.51, "half of revenue", fontsize=9, color="0.3")
ax.yaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=0))
ax.set_ylim(0, 0.7)
ax.set(title="Online share rose from under a third to about half of revenue",
ylabel="Online share of revenue")
paths.append(save(fig, "q4_online_share"))
plt.show()
first, last = online_share.iloc[:3].mean(), online_share.iloc[-3:].mean()
print(f"online share: first 3 months {first:.1%}, last 3 months {last:.1%}, "
f"max {online_share.max():.1%} in {online_share.idxmax():%Y-%m}")
Output
online share: first 3 months 30.0%, last 3 months 52.2%, max 57.2% in 2024-11
Online share of monthly revenue climbs from about 30% in early 2023 to a peak of 57% in November 2024, crossing the 50% line in late 2024.
Q4: monthly online share of revenue with a 50% reference line.
chart_pack.py (part 6: Q5, the top days)
# Q5: a line of daily revenue with a rolling mean; annotations name the top days.
daily = sales[sales["year"] == 2024].groupby("order_date")["revenue"].sum()
top3 = daily.nlargest(3)
fig, ax = plt.subplots(figsize=(9, 3.8))
ax.plot(daily.index, daily, linewidth=0.6, color="C0", alpha=0.6, label="daily")
ax.plot(daily.index, daily.rolling(7, center=True).mean(), color="C1", linewidth=2,
label="7-day mean")
for rank, (day, value) in enumerate(top3.items()): # largest first, top label
ax.annotate(f"{day:%a %d %b}: {value / 1000:,.1f}k", xy=(day, value),
xytext=(pd.Timestamp("2024-05-01"), 31_000 - rank * 4_500),
arrowprops=ARROW, fontsize=9)
ax.yaxis.set_major_formatter(K)
ax.set_ylim(0, None)
ax.set(title="Black Friday is by far the biggest day of 2024",
ylabel="Revenue per day (USD)")
ax.legend(loc="upper left", frameon=False)
paths.append(save(fig, "q5_top_days"))
plt.show()
print((top3 / 1000).round(1))
Output
order_date
2024-11-29 33.6
2024-12-17 20.0
2024-11-30 17.6
Name: revenue, dtype: float64
Daily revenue in 2024 with a 7-day mean that rises in November and December; arrows mark the top days: Friday 29 November at 33.6k, Tuesday 17 December at 20.0k and Saturday 30 November at 17.6k.
Q5: daily revenue in 2024 with a 7-day mean and the three largest days.
chart_pack.py (part 7: the interactive chart and the checks)
monthly_cat = (
sales.groupby([pd.Grouper(key="order_date", freq="MS"), "category"])["revenue"]
.sum()
.reset_index()
)
fig = px.bar(
monthly_cat, x="order_date", y="revenue", color="category",
labels={"order_date": "Month", "revenue": "Revenue (USD)", "category": "Category"},
title="Monthly revenue by category (hover for values, click the legend to filter)",
template="plotly_white", color_discrete_sequence=px.colors.qualitative.Safe,
)
fig.update_traces(hovertemplate="%{x|%b %Y}: %{y:,.0f} USD")
html_path = OUT / "monthly_by_category.html"
fig.write_html(html_path, include_plotlyjs="cdn")
fig.show()
for name in sorted(p.name for p in OUT.iterdir()):
print(name)
assert round(sales["revenue"].sum(), 2) == 3596523.83
assert all(path.exists() for path in paths) and html_path.exists()
assert growth > 0
assert top3.index[0] == pd.Timestamp("2024-11-29")
Output
monthly_by_category.html
q1_monthly_trend.png
q2_category_revenue_margin.png
q3_growth_heatmap.png
q4_online_share.png
q5_top_days.png
Monthly revenue by category, interactive · Open the interactive chart in a new tab

Run it from the project folder:

Terminal
python chart_pack.py

How it works:

  1. Data first. The merge with validate="many_to_one" raises an error if a product id appears twice in products.csv, so a broken join cannot silently double revenue. All numbers are computed before each chart and printed after it, so the findings in the titles can be checked.
  2. One theme, one helper. sns.set_theme styles every chart with the color-blind palette. save keeps the folder, format and resolution in one place, and each chart is saved before plt.show().
  3. Q1. Two lines on a shared January–December axis compare the years month by month. The axis starts at zero, and the annotation reads the peak from the data.
  4. Q2. Sorted bars rank the categories by revenue; the labels add the margin rate, which shows that the largest category earns the thinnest margin. One chart, two facts, no second axis.
  5. Q3. pivot_table with two index levels, then unstack, gives a region × category growth table. vlag with the symmetric limits vmin=-0.6, vmax=0.6 puts the neutral color at 0, makes growth red and decline blue, and keeps equal changes equally dark.
  6. Q4. A share over time is a line. The 50% reference line turns “it rises” into “it approaches half”.
  7. Q5. The thin daily line shows the spikes; the 7-day mean shows the season underneath. The three annotations are built in a loop from nlargest(3). The labels stack from the top in the order of the values, so the highest label points to the highest day and the arrows do not cross.
  8. Interactive. Plotly stacks the categories per month. Clicking a legend entry hides that category, so analysts can isolate Sports or Electronics themselves.
  9. Checks. The asserts protect the pack against silent data changes: a wrong total, a missing file or a sign flip in growth stops the script.

Alternative: build all five charts into one plt.subplot_mosaic figure for a single-page handout, and keep the separate PNG files for the slides. With one function per chart, both outputs come from the same code.