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:
- Did revenue grow in 2024, and when in the year do we earn it?
- Which categories bring revenue, and which bring profit?
- Where did growth come from: which regions and categories grew, and which shrank?
- Is the online channel taking over?
- 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.
Dataset
Section titled “Dataset”data/sales.csv: 20,228 order lines from 2023-01-01 to 2024-12-31 withorder_date,region,channel,product_id,category,quantityandrevenue.data/products.csv: 30 products withunit_cost, the cost to the shop of one unit. Join it onproduct_idto 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.
Requirements
Section titled “Requirements”Your script must:
- Load both files, join them with a check that each sales line finds exactly one product (
validate="many_to_one"), and addprofitandyearcolumns. - Set one theme for all charts with a color-blind-friendly palette.
- 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.
- 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. - 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).
- Save each chart with
fig.savefig(..., dpi=150, bbox_inches="tight")intooutput/chart_pack/before showing it. - Write one Plotly Express chart with useful tooltips to
output/chart_pack/as HTML. - Print the number behind each finding, and end with
assertchecks: the total revenue, the files on disk, the sign of the growth.
Step plan
Section titled “Step plan”-
Load and join. Read
sales.csvwithparse_dates=["order_date"]and mergeproducts.csvonproduct_id. Computeprofitandyear. Print the shape and the total revenue. -
Set the theme and helpers. Call
sns.set_themeonce. Create the output folder. Write aFuncFormatterfor thousands and asave(fig, name)function that saves a figure and returns its path. -
Question 1, the trend. Monthly revenue per year as two lines on a January–December axis, from zero, with the peak month annotated.
-
Question 2, revenue and profit. One horizontal bar per category with 2024 revenue, sorted, and the gross margin rate written next to each bar.
-
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.
-
Question 4, channels. The online share of revenue per month as a line with a 50% reference line.
-
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.
-
The interactive chart. Monthly revenue by category as stacked bars with Plotly Express, saved with
write_html. -
Check. Print the findings, list the saved files and assert what must be true.
A skeleton to start from:
from pathlib import Path
import matplotlib.pyplot as pltimport pandas as pdimport plotly.express as pximport seaborn as snsfrom 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, assertRubric
Section titled “Rubric”| 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 |
Stretch goals
Section titled “Stretch goals”- Combine the five static charts into one dashboard page with
plt.subplot_mosaic, reusing one function per chart. - Add a sixth chart: the distribution of discounts per month as a 100% stacked bar. Do deeper discounts explain the November peak?
- Save every chart also as SVG, and compare the file sizes with the PNG files.
- Turn the script into a command-line tool (module 08) with
--yearand--outoptions, so that next January’s review is one command. - Rebuild question 3 with Plotly’s
px.imshow(..., text_auto=".0%"), so that the analysts can hover over each cell.
Reference solution
Section titled “Reference solution”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.
import calendarfrom pathlib import Path
import matplotlib.pyplot as pltimport pandas as pdimport plotly.express as pximport seaborn as snsfrom 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.yearprint(sales.shape)revenue, profit = sales["revenue"].sum(), sales["profit"].sum()print(f"revenue {revenue:,.2f} USD, profit {profit:,.2f} USD")(20228, 16)revenue 3,596,523.83 USD, profit 1,760,135.83 USD# 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() - 1ax.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%}")growth 18.6%; Nov+Dec share of 2024: 29.3%
# 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)) revenue margincategoryElectronics 939924.77 0.389Home 397844.84 0.552Sports 299576.31 0.577Clothing 170699.61 0.649Beauty 85444.53 0.686Books 57444.18 0.668
# 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))category Beauty Books Clothing Electronics Home SportsregionEast 0.322 0.203 0.167 0.109 0.558 0.233North 0.322 0.212 0.093 0.055 0.502 0.152South 0.462 0.097 0.196 0.081 0.347 0.254West 0.162 0.138 0.309 0.081 0.381 0.262
# 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}")online share: first 3 months 30.0%, last 3 months 52.2%, max 57.2% in 2024-11
# 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))order_date2024-11-29 33.62024-12-17 20.02024-11-30 17.6Name: revenue, dtype: float64
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.83assert all(path.exists() for path in paths) and html_path.exists()assert growth > 0assert top3.index[0] == pd.Timestamp("2024-11-29")monthly_by_category.htmlq1_monthly_trend.pngq2_category_revenue_margin.pngq3_growth_heatmap.pngq4_online_share.pngq5_top_days.pngRun it from the project folder:
python chart_pack.pyHow it works:
- Data first. The merge with
validate="many_to_one"raises an error if a product id appears twice inproducts.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. - One theme, one helper.
sns.set_themestyles every chart with the color-blind palette.savekeeps the folder, format and resolution in one place, and each chart is saved beforeplt.show(). - 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.
- 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.
- Q3.
pivot_tablewith two index levels, thenunstack, gives a region × category growth table.vlagwith the symmetric limitsvmin=-0.6, vmax=0.6puts the neutral color at 0, makes growth red and decline blue, and keeps equal changes equally dark. - Q4. A share over time is a line. The 50% reference line turns “it rises” into “it approaches half”.
- 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. - Interactive. Plotly stacks the categories per month. Clicking a legend entry hides that category, so analysts can isolate Sports or Electronics themselves.
- 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.