28. Visualization — Exercises
These exercises practice every idea of the Visualization lesson. They use the course datasets: data/sales.csv, data/customers.csv, data/houses.csv, data/sensors.csv, data/web_traffic.csv, data/ab_test.csv and scikit-learn’s bundled iris dataset. The data dictionary describes every column.
How to work:
- Read the task and the expected output or the acceptance criteria.
- Copy the setup block and the starter code into a script (for example
exercise.py) and replace each to-do comment with your code. - Run the script with
python exercise.py. A chart window opens at eachplt.show(); close it to continue. Compare the printed lines with the expected output and your chart with the one in the solution. - Stuck? Open one hint at a time. Open the solution only after a real attempt.
A chart cannot be compared character by character, so most solutions also print the numbers behind the chart and check them with assert. Print the same numbers in your own code: they prove that you plotted the right data.
Every exercise starts from this block. It imports the libraries, fixes how pandas prints tables and sets one color-blind-friendly theme. plt.rcdefaults() first resets any style that an earlier experiment left behind.
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport seaborn as sns
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)plt.rcdefaults()sns.set_theme(style="whitegrid", palette="colorblind")Warm-up
Section titled “Warm-up”M28-W01 · Your first object-oriented chart
Section titled “M28-W01 · Your first object-oriented chart”The shop sold these units in the first week of 2024 (Monday 1 January to Sunday 7 January), from data/sales.csv: 24, 23, 28, 34, 38, 36, 39. Draw a line chart with markers using plt.subplots. Set the title Units sold, 1–7 January 2024, the x label Day and the y label Units. Print the title, the two labels and the number of lines on the Axes.
Units sold, 1–7 January 2024Day | Unitslines: 1days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]units = [24, 23, 28, 34, 38, 36, 39]# TODO: create fig and ax with plt.subplots(figsize=(6, 3))# TODO: plot units against days with markers; set the title and both labels# TODO: print the title, "xlabel | ylabel" and "lines: N"; then plt.show()Hint 1
fig, ax = plt.subplots(figsize=(6, 3)) gives you the Axes. ax.plot(days, units, marker="o") draws the line with a dot at each point.
Hint 2
Setters start with set_: ax.set_title(...), ax.set_xlabel(...). Getters start with get_: ax.get_title(). ax.lines is the list of Line2D artists on the Axes.
Solution
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]units = [24, 23, 28, 34, 38, 36, 39]fig, ax = plt.subplots(figsize=(6, 3))ax.plot(days, units, marker="o")ax.set_title("Units sold, 1–7 January 2024")ax.set_xlabel("Day")ax.set_ylabel("Units")print(ax.get_title())print(ax.get_xlabel(), "|", ax.get_ylabel())print("lines:", len(ax.lines))assert ax.get_ylabel() == "Units"assert len(ax.lines) == 1plt.show()Units sold, 1–7 January 2024Day | Unitslines: 1
How it works:
plt.subplotsreturns a Figure and one Axes. Every later command goes to that Axes.- With a list of strings as x, Matplotlib treats the days as categories and places them in the given order.
- The getters read back what you set, so the asserts can check the chart without looking at it.
Alternative: set the three texts in one call with ax.set(title="Units sold, 1–7 January 2024", xlabel="Day", ylabel="Units"). ax.set accepts any set_* property as a keyword.
M28-W02 · Predict what plt.subplots returns
Section titled “M28-W02 · Predict what plt.subplots returns”Predict the output: read the code and write down, line by line, what it prints. Then run it.
fig, axs = plt.subplots(3, 2)print(type(axs).__name__, axs.shape)fig, axs = plt.subplots(1, 4)print(axs.shape, axs.ndim)fig, ax = plt.subplots(1, 1)print(type(ax).__name__)fig, axs = plt.subplots(2, 1, squeeze=False)print(axs.shape, len(fig.axes))print(len(plt.get_fignums()), "figures open")plt.close("all")print(len(plt.get_fignums()), "figures open")Acceptance criteria:
- You wrote a prediction for each of the six lines before you ran the code.
- Your prediction matches the Output in the solution, or you can explain each difference.
Hint 1
A grid returns a NumPy array of Axes with the shape (nrows, ncols). A single row or column is squeezed to a 1-D array. (1, 1) is squeezed to one Axes object.
Hint 2
squeeze=False turns the squeezing off: the result is always 2-D. Each plt.subplots call creates a new figure, and figures stay open until you close them.
Solution
fig, axs = plt.subplots(3, 2)print(type(axs).__name__, axs.shape)fig, axs = plt.subplots(1, 4)print(axs.shape, axs.ndim)fig, ax = plt.subplots(1, 1)print(type(ax).__name__)fig, axs = plt.subplots(2, 1, squeeze=False)print(axs.shape, len(fig.axes))print(len(plt.get_fignums()), "figures open")plt.close("all")print(len(plt.get_fignums()), "figures open")assert axs.shape == (2, 1)assert plt.get_fignums() == []ndarray (3, 2)(4,) 1Axes(2, 1) 24 figures open0 figures openHow it works:
(3, 2)gives a 2-D array of 6 Axes. Index it asaxs[row, col].(1, 4)gives a 1-D array of 4 Axes:axs[0]toaxs[3].axs[0, 1]would raise anIndexError.(1, 1)gives a plainAxes, not an array, soax.plot(...)works directly.squeeze=Falsekeeps the 2-D shape(2, 1). Code that loops over rows and columns then works for any grid size.fig.axeslists the Axes of one figure.- The four calls made four figures.
plt.close("all")closes them and frees their memory.
Alternative: iterate with for ax in np.atleast_1d(axs).flat: or for ax in fig.axes: to handle one Axes and an array of Axes with the same loop.
M28-W03 · Fix the title bug
Section titled “M28-W03 · Fix the title bug”Fix the bug: this script should draw revenue by sales channel. It stops with TypeError: 'Text' object is not callable on the ax.title line. Fix it so that it sets the title Revenue by channel and the y label Revenue (USD). Print the title and label, and the revenue per channel in millions of USD.
Revenue by channel | Revenue (USD){'online': 1.52, 'store': 2.08}sales = pd.read_csv("data/sales.csv")by_channel = sales.groupby("channel")["revenue"].sum()fig, ax = plt.subplots(figsize=(5, 3.5))ax.bar(by_channel.index, by_channel.to_numpy())ax.title("Revenue by channel")ax.ylabel("Revenue (USD)")# TODO: print the title and label, then the revenue per channel in millionsplt.show()Hint 1
plt.title() and plt.ylabel() are pyplot functions. An Axes has set_... methods instead.
Hint 2
ax.title exists, but it is a Text object that holds the title. Calling it with (...) is the bug.
Solution
sales = pd.read_csv("data/sales.csv")by_channel = sales.groupby("channel")["revenue"].sum()fig, ax = plt.subplots(figsize=(5, 3.5))ax.bar(by_channel.index, by_channel.to_numpy())ax.set_title("Revenue by channel")ax.set_ylabel("Revenue (USD)")print(ax.get_title(), "|", ax.get_ylabel())print((by_channel / 1e6).round(2).to_dict())assert ax.get_title() == "Revenue by channel"plt.show()Revenue by channel | Revenue (USD){'online': 1.52, 'store': 2.08}
How it works:
ax.set_titleandax.set_ylabelare the object-oriented setters. The pyplot namesplt.titleandplt.ylabelwork only on the current Axes.ax.titleis an attribute that holds a Text artist; calling it raises theTypeError.- Dividing by
1e6shows millions;.to_dict()prints a compact one-line result.
Alternative: ax.set(title="Revenue by channel", ylabel="Revenue (USD)") sets both in one call.
M28-W04 · A sorted horizontal bar chart with labels
Section titled “M28-W04 · A sorted horizontal bar chart with labels”Draw total revenue by category from data/sales.csv as horizontal bars, largest at the top, with each value written next to its bar (thousands separator, no decimals). Print the revenue per category in thousands of USD, smallest first.
categoryBooks 106.9Beauty 150.4Clothing 314.7Sports 544.1Home 672.3Electronics 1808.1Name: revenue, dtype: float64sales = pd.read_csv("data/sales.csv")# TODO: total revenue per category, sorted ascending# TODO: ax.barh(...), then ax.bar_label(bars, fmt="{:,.0f}", padding=3)# TODO: a title, an x label and room for the labels (ax.set_xlim)# TODO: print the totals in thousands (1 decimal); plt.show()Hint 1
barh draws the first value at the bottom. Sort ascending, so the largest bar ends at the top.
Hint 2
bars = ax.barh(by_cat.index, by_cat.to_numpy()) returns the bar artists that ax.bar_label(bars, ...) needs. Labels outside the bars need space: ax.set_xlim(0, by_cat.max() * 1.2).
Solution
sales = pd.read_csv("data/sales.csv")by_cat = sales.groupby("category")["revenue"].sum().sort_values()fig, ax = plt.subplots(figsize=(7, 3.5))bars = ax.barh(by_cat.index, by_cat.to_numpy(), color="C0")ax.bar_label(bars, fmt="{:,.0f}", padding=3)ax.set_xlim(0, by_cat.max() * 1.2)ax.set(title="Electronics earns half of all revenue", xlabel="Revenue (USD)")print((by_cat / 1000).round(1))assert by_cat.index[-1] == "Electronics"plt.show()categoryBooks 106.9Beauty 150.4Clothing 314.7Sports 544.1Home 672.3Electronics 1808.1Name: revenue, dtype: float64
How it works:
sort_values()orders the categories by revenue.barhstacks them from the bottom, so the largest is at the top, where the eye starts.bar_labelwrites each value;padding=3leaves 3 points of space after the bar.- Horizontal bars suit long category names: they read left to right with no rotation.
Alternative: by_cat.plot.barh(ax=ax) draws the same bars with pandas, which calls Matplotlib for you. Seaborn’s sns.barplot(x=by_cat.to_numpy(), y=by_cat.index, color="C0", ax=ax) works too.
M28-W05 · Read the counts behind a histogram
Section titled “M28-W05 · Read the counts behind a histogram”Draw a histogram of customer age from data/customers.csv with bins of 8 years: edges 18, 26, 34, …, 82. ax.hist returns the counts per bin. Print the edges and the counts as whole numbers, and check that the counts add up to the number of customers.
edges: [18, 26, 34, 42, 50, 58, 66, 74, 82]counts: [502, 788, 1113, 1163, 836, 416, 137, 45]customers = pd.read_csv("data/customers.csv")edges = list(range(18, 83, 8))# TODO: counts, bin_edges, patches = ax.hist(...)# TODO: label the chart; print the edges and the counts as int lists; plt.show()Hint 1
Pass the list of edges as bins=edges. Eight bins need nine edges.
Hint 2
The counts and edges come back as float arrays. counts.astype(int).tolist() prints them as whole numbers.
Solution
customers = pd.read_csv("data/customers.csv")edges = list(range(18, 83, 8))fig, ax = plt.subplots(figsize=(6, 3.5))counts, bin_edges, patches = ax.hist(customers["age"], bins=edges, edgecolor="white")ax.set(title="Customer age", xlabel="Age (years)", ylabel="Customers")print("edges:", bin_edges.astype(int).tolist())print("counts:", counts.astype(int).tolist())assert counts.sum() == len(customers)plt.show()edges: [18, 26, 34, 42, 50, 58, 66, 74, 82]counts: [502, 788, 1113, 1163, 836, 416, 137, 45]
How it works:
- Each bin includes its left edge and excludes its right edge, except the last bin, which includes both. So every age from 18 to 80 lands in exactly one bin.
ax.histreturns the counts, the edges and the bar artists. You get the numbers for a report without a secondgroupby.- The assert proves that no customer fell outside the bins.
Alternative: np.histogram(customers["age"], bins=edges) computes the same counts without drawing, and pd.cut(customers["age"], edges, right=False).value_counts(sort=False) gives labeled intervals.
M28-W06 · Save a figure with an exact pixel size
Section titled “M28-W06 · Save a figure with an exact pixel size”A web page needs a chart of exactly 900 × 600 pixels. Draw a histogram of monthly_charges on a 6 × 4 inch figure, save it as output/charges.png with the right dpi, close the figure and read the file back with plt.imread to check its size. Print the shape of the image array.
(600, 900, 4)from pathlib import Path
customers = pd.read_csv("data/customers.csv")# TODO: fig, ax = plt.subplots(figsize=(6, 4)); draw the histogram# TODO: create output/ and save with the dpi that gives 900 x 600 pixels# TODO: close the figure; read the PNG with plt.imread; print its shapeHint 1
Pixels = inches × dpi. 6 inches × dpi = 900 pixels.
Hint 2
Do not pass bbox_inches="tight" here: it crops the image and changes its size. plt.imread returns an array of shape (height, width, channels).
Solution
from pathlib import Path
customers = pd.read_csv("data/customers.csv")fig, ax = plt.subplots(figsize=(6, 4))ax.hist(customers["monthly_charges"], bins=30)ax.set(title="Monthly charges", xlabel="USD per month", ylabel="Customers")Path("output").mkdir(exist_ok=True)fig.savefig("output/charges.png", dpi=150)plt.close(fig)image = plt.imread("output/charges.png")print(image.shape)assert image.shape[:2] == (600, 900)(600, 900, 4)How it works:
- 6 × 150 = 900 pixels wide and 4 × 150 = 600 pixels high.
- The array has height first, then width, then 4 color channels: red, green, blue and alpha (transparency).
plt.close(fig)frees the figure. A script that saves many charts needs this.
Alternative: save a vector file instead, fig.savefig("output/charges.svg"). An SVG has no pixel size: it scales to any width without blur, which suits web pages.
M28-W07 · Fix the Seaborn palette warning
Section titled “M28-W07 · Fix the Seaborn palette warning”Fix the bug: this bar chart of churn rate by contract works, but Seaborn 0.13 prints FutureWarning: Passing palette without assigning hue is deprecated. Keep one color per contract and no legend, remove the warning and turn off the error bars. Print the bar heights rounded to 3 decimals, in the order month-to-month, one-year, two-year.
[0.296, 0.088, 0.032]customers = pd.read_csv("data/customers.csv")order = ["month-to-month", "one-year", "two-year"]fig, ax = plt.subplots(figsize=(6, 3.5))sns.barplot(data=customers, x="contract", y="churned", order=order, palette="colorblind", errorbar=None, ax=ax)# TODO: fix the call; print the bar heights; plt.show()Hint 1
The warning text says what to do: assign the x variable to hue and set legend=False.
Hint 2
Each bar is a Rectangle in ax.patches. bar.get_height() returns its height as a NumPy float; float(...) makes it a plain Python float, which prints without np.float64(...).
Solution
customers = pd.read_csv("data/customers.csv")order = ["month-to-month", "one-year", "two-year"]fig, ax = plt.subplots(figsize=(6, 3.5))sns.barplot(data=customers, x="contract", y="churned", hue="contract", order=order, hue_order=order, palette="colorblind", legend=False, errorbar=None, ax=ax)ax.set(title="Churn rate by contract", xlabel="Contract", ylabel="Churn rate")heights = [round(float(bar.get_height()), 3) for bar in ax.patches]print(heights)assert heights == [0.296, 0.088, 0.032]plt.show()[0.296, 0.088, 0.032]
How it works:
hue="contract"tells Seaborn which column the colors stand for. The palette is then a real mapping, which is what Seaborn 0.13 wants.legend=Falsehides the legend, which would repeat the x-axis labels.hue_ordermatchesorder, so the colors follow the bars.
Alternative: if the colors carry no meaning, use one color: sns.barplot(..., color="C0"). Fewer colors make a calmer chart.
M28-W08 · Choose the chart
Section titled “M28-W08 · Choose the chart”Choose the chart and justify it: for each question, pick one chart from this list: histogram, box plot, bar chart with error bars, line chart, scatter plot, correlation heatmap. Store your answers in a dict from question number to chart name and print them. Write one sentence per answer that says why.
- How is
avg_session_minutesspread across the 5,000 customers? - Does the churn rate differ between the three contracts, and is the gap more than noise?
- How did daily web visits change from 2022 to 2024?
- Does house price change with distance to the city center?
- Which pairs of the 11 numeric columns of
houses.csvmove together? - How do the monthly charges of the three plans compare, outliers included?
Acceptance criteria:
- The dict has six entries, each one of the six chart names.
- Each answer has a one-sentence reason in a comment.
- Your answers match the solution, or your reason convinces a colleague.
charts = { 1: "", # TODO: chart name, then a comment with the reason # TODO: questions 2 to 6}for number, chart in charts.items(): print(f"Q{number}: {chart}")Hint 1
Ask first what kind of question it is: the spread of one variable, a comparison of groups, a change over time or a relationship between two numeric variables.
Hint 2
“Is the gap more than noise?” asks for uncertainty, which means error bars. “Outliers included” points to a chart that draws outliers as dots.
Solution
allowed = {"histogram", "box plot", "bar chart with error bars", "line chart", "scatter plot", "correlation heatmap"}charts = { 1: "histogram", # the shape of one numeric column: peak, spread, skew 2: "bar chart with error bars", # rate per group, and the CI shows the noise 3: "line chart", # a value over ordered time shows trend and season 4: "scatter plot", # two numeric columns; each house is one point 5: "correlation heatmap", # 55 pairs at a glance, colored by strength and sign 6: "box plot", # medians, quartiles and outliers side by side}for number, chart in charts.items(): print(f"Q{number}: {chart}")assert set(charts.values()) <= allowedassert len(set(charts.values())) == 6Q1: histogramQ2: bar chart with error barsQ3: line chartQ4: scatter plotQ5: correlation heatmapQ6: box plotHow it works:
- Questions 1 and 6 are about distributions. One column alone suits a histogram; several groups side by side suit box plots, which also mark outliers.
- Question 2 compares rates of groups. A bar shows the rate and its error bar shows the uncertainty.
- Question 3 is a trend over time: a line chart, because time is ordered and continuous.
- Question 4 relates two numeric columns: a scatter plot. Add a regression line or a smoother to show the trend.
- Question 5 asks about many pairs at once: 11 columns have 55 pairs, so a correlation heatmap gives the overview. Check the strongest pairs with scatter plots afterward.
Alternative: for question 1, an ECDF or a KDE also works; for question 6, a violin plot shows the shape in more detail, but it hides individual outliers.
M28-W09 · Write a tick formatter for money
Section titled “M28-W09 · Write a tick formatter for money”Write a function short_money(value, pos) that formats a USD amount for an axis: millions as 1.8M (one decimal), thousands as 672k (no decimals) and smaller values as whole numbers. Wrap it in a FuncFormatter and print the label for each of 950, 12,400, 672,295 and 1,808,108.
950 -> 950 12,400 -> 12k 672,295 -> 672k1,808,108 -> 1.8Mfrom matplotlib.ticker import FuncFormatter
def short_money(value, pos): """Format a USD amount as 950, 12k or 1.8M.""" # TODO: three cases, largest first
formatter = FuncFormatter(short_money)# TODO: print "value -> label" for the four valuesHint 1
Test the largest unit first: if abs(value) >= 1_000_000:. abs keeps negative values (losses) correct.
Hint 2
Matplotlib calls the formatter with two arguments: the tick value and the tick position. Your function must accept both, even if it ignores pos.
Solution
from matplotlib.ticker import FuncFormatter
def short_money(value, pos): """Format a USD amount as 950, 12k or 1.8M.""" if abs(value) >= 1_000_000: return f"{value / 1_000_000:.1f}M" if abs(value) >= 1_000: return f"{value / 1_000:.0f}k" return f"{value:.0f}"
formatter = FuncFormatter(short_money)for value in [950, 12_400, 672_295, 1_808_108]: print(f"{value:>9,} -> {formatter(value, 0)}")assert formatter(1_808_108, 0) == "1.8M"assert formatter(-12_400, 0) == "-12k" 950 -> 950 12,400 -> 12k 672,295 -> 672k1,808,108 -> 1.8MHow it works:
- The checks run from the largest unit to the smallest, so each value takes the first unit that fits.
- A formatter is callable, so you test it like any function before you put it on an axis with
ax.yaxis.set_major_formatter(formatter). - The second assert checks a negative value, which
abshandles.
Alternative: matplotlib.ticker.EngFormatter(places=1) gives engineering prefixes with no code of your own:
from matplotlib.ticker import EngFormatter
eng = EngFormatter(places=1)print([eng(value, 0) for value in [950, 12_400, 672_295, 1_808_108]])['950.0', '12.4 k', '672.3 k', '1.8 M']It always shows one decimal and a space before the prefix, so you trade control over the format for less code.
M28-C01 · Highlight the best weekday
Section titled “M28-C01 · Highlight the best weekday”Compute the mean daily revenue for each weekday from data/sales.csv (first total revenue per date, then the mean per weekday, Monday first). Draw a bar chart where Saturday is orange ("C1") and every other day is light gray ("0.7"), so the eye goes straight to the best day. Print the seven means rounded to whole USD.
Mon 4233.0Tue 3943.0Wed 4259.0Thu 4416.0Fri 5598.0Sat 6365.0Sun 5636.0Name: revenue, dtype: float64sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]# TODO: daily = total revenue per order_date# TODO: by_day = mean of daily per day of week (0 = Monday), index renamed to days# TODO: a color list, the bar chart, a title that states the finding# TODO: print by_day rounded; plt.show()Hint 1
Two steps: sales.groupby("order_date")["revenue"].sum() gives one value per day. Then group that Series by daily.index.day_of_week.
Hint 2
A list comprehension builds the colors: ["C1" if day == "Sat" else "0.7" for day in days]. Pass it as color= to ax.bar.
Solution
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]daily = sales.groupby("order_date")["revenue"].sum()by_day = daily.groupby(daily.index.day_of_week).mean()by_day.index = dayscolors = ["C1" if day == "Sat" else "0.7" for day in days]fig, ax = plt.subplots(figsize=(7, 3.5))ax.bar(days, by_day.to_numpy(), color=colors)ax.set(title="Saturday brings the most revenue", ylabel="Mean daily revenue (USD)")print(by_day.round(0))assert by_day.idxmax() == "Sat"plt.show()Mon 4233.0Tue 3943.0Wed 4259.0Thu 4416.0Fri 5598.0Sat 6365.0Sun 5636.0Name: revenue, dtype: float64
How it works:
- Summing per date first gives one value per calendar day; the mean per weekday then averages about 104 days each. Taking the mean of the order lines directly would answer a different question (the average line, not the average day).
day_of_weekis 0 for Monday to 6 for Sunday, so the groups come out in calendar order.- One accent color on a gray background is a strong way to point at one value. It also works for color-blind readers, because the contrast is in lightness, not only in hue.
Alternative: use daily.index.day_name() as the group key and reindex with the full day names to fix the order.
M28-C02 · Small multiples by region
Section titled “M28-C02 · Small multiples by region”Draw the monthly revenue of each region from data/sales.csv as a 2 × 2 grid of line charts with shared axes, one region per panel in alphabetical order. Show revenue in thousands of USD, give the figure one y label with fig.supylabel and use short date labels. Print the shape of the monthly table and each region’s total in thousands.
(24, 4)regionEast 993.7North 888.2South 891.8West 822.8dtype: float64import matplotlib.dates as mdates
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])# TODO: monthly = revenue per month (rows) and region (columns)# TODO: plt.subplots(2, 2, sharex=True, sharey=True, layout="constrained")# TODO: one region per Axes; ConciseDateFormatter on the bottom row# TODO: print monthly.shape and the totals per region; plt.show()Hint 1
sales.groupby([pd.Grouper(key="order_date", freq="MS"), "region"])["revenue"].sum().unstack() gives a table with one row per month and one column per region.
Hint 2
zip(axs.flat, monthly.columns) pairs each Axes with a region. For the date labels: ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(ax.xaxis.get_major_locator())).
Solution
import matplotlib.dates as mdates
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])monthly = ( sales.groupby([pd.Grouper(key="order_date", freq="MS"), "region"])["revenue"] .sum() .unstack())fig, axs = plt.subplots(2, 2, figsize=(9, 5.5), sharex=True, sharey=True, layout="constrained")for ax, region in zip(axs.flat, monthly.columns): ax.plot(monthly.index, monthly[region] / 1000, marker=".") ax.set_title(region)for ax in axs[1]: locator = ax.xaxis.get_major_locator() ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(locator))fig.supylabel("Revenue (thousand USD)")fig.suptitle("Every region has the same December peak")print(monthly.shape)print((monthly.sum() / 1000).round(1))assert monthly.shape == (24, 4)plt.show()(24, 4)regionEast 993.7North 888.2South 891.8West 822.8dtype: float64
How it works:
pd.Grouper(key="order_date", freq="MS")groups dates by month inside agroupby, next to the region key, and labels each month by its first day. With"ME"(month end), the December total would sit at 31 December, right on the January tick, and the peak would look like a January peak.unstack()moves the regions into columns.sharex=True, sharey=Truegive every panel the same scales, so the reader compares levels directly. Only the bottom row shows x labels.fig.supylabelputs one y label for the whole figure instead of four copies.
Alternative: Seaborn does it in one call from long data: sns.relplot(data=long, x="order_date", y="revenue", col="region", col_wrap=2, kind="line"), where long = monthly.stack().rename("revenue").reset_index().
M28-C03 · Annotate the busiest day
Section titled “M28-C03 · Annotate the busiest day”Draw daily visits from data/web_traffic.csv as a line chart. Find the busiest day in the data and annotate it with an arrow and the text 08 Apr 2024: 18,385 visits, built from the data, not typed. Print the date and the number of visits.
2024-04-08 1838508 Apr 2024: 18,385 visitstraffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"])# TODO: peak = the row with the most visits (idxmax + loc)# TODO: plot visits over date; ax.annotate(...) with an f-string label# TODO: print the date and visits; plt.show()Hint 1
traffic.loc[traffic["visits"].idxmax()] returns the whole row of the busiest day as a Series.
Hint 2
f-strings format dates and numbers: f"{peak['date']:%d %b %Y}: {peak['visits']:,.0f} visits". Put xytext in an empty area, for example at the start of the period and near the top.
Solution
traffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"])peak = traffic.loc[traffic["visits"].idxmax()]label = f"{peak['date']:%d %b %Y}: {peak['visits']:,.0f} visits"fig, ax = plt.subplots(figsize=(8, 3.5))ax.plot(traffic["date"], traffic["visits"], linewidth=0.8)ax.annotate(label, xy=(peak["date"], peak["visits"]), xytext=(pd.Timestamp("2022-06-01"), 16_000), arrowprops={"arrowstyle": "->", "color": "0.3"})ax.set(title="Daily visits, 2022–2024", ylabel="Visits")print(peak["date"].date(), int(peak["visits"]))print(label)assert peak["date"] == pd.Timestamp("2024-04-08")plt.show()2024-04-08 1838508 Apr 2024: 18,385 visits
How it works:
idxmaxskips the five missing values and returns the index label of the largest value;locreturns that row.xyis the point the arrow touches, in data coordinates: a date and a number of visits.xytextis where the text starts.visitsis a float column because of its blanks, soint(...)prints it without.0.
Alternative: mark the top 3 days with traffic.nlargest(3, "visits") and a loop over its rows, or with one ax.scatter call on those rows.
M28-C04 · Compare two groups of different size fairly
Section titled “M28-C04 · Compare two groups of different size fairly”Fix the bug: the analyst below wants to know whether churners have shorter sessions. Their histogram makes the churned group look tiny, because it has 963 customers against 4,037. Change the histogram so that each group’s area is 1, draw it as outlines (element="step"), and print the median avg_session_minutes of each group.
churned0 13.01 12.3Name: avg_session_minutes, dtype: float64customers = pd.read_csv("data/customers.csv")fig, ax = plt.subplots(figsize=(7, 3.5))sns.histplot(data=customers, x="avg_session_minutes", hue="churned", bins=40, ax=ax)# TODO: normalize each group separately; draw outlines# TODO: print the median per group; plt.show()Hint 1
stat="density" scales the bars so that their total area is 1. common_norm decides whether that is one area for all groups together or one per group.
Hint 2
common_norm=False normalizes each hue group on its own.
Solution
customers = pd.read_csv("data/customers.csv")fig, ax = plt.subplots(figsize=(7, 3.5))sns.histplot(data=customers, x="avg_session_minutes", hue="churned", bins=40, stat="density", common_norm=False, element="step", ax=ax)ax.set(title="Session length: churned vs retained customers", xlabel="Average session (minutes)")medians = customers.groupby("churned")["avg_session_minutes"].median()print(medians.round(1))assert medians[1] < medians[0]plt.show()churned0 13.01 12.3Name: avg_session_minutes, dtype: float64
How it works:
- With counts, the bigger group dominates the picture. With
stat="density", common_norm=False, each group has an area of 1, so you compare shapes. element="step"draws outlines, which overlap better than filled bars.- The medians put a number on what the chart shows: the two groups are close, and churners sit a little lower. Session length alone is a weak churn signal.
Alternative: sns.kdeplot(..., common_norm=False) gives smooth curves, and sns.ecdfplot(...) needs no normalization at all, because each curve always runs from 0 to 1.
M28-C05 · Interpret an ECDF of tenure
Section titled “M28-C05 · Interpret an ECDF of tenure”Interpret a result: draw the ECDF of tenure_months for churned and retained customers, with a dotted vertical line at 6 months. Print the share of each group with a tenure of 6 months or less, and the median tenure of each group. Then answer in two sentences: what share of churners leave within their first half year, and what does that suggest for the retention team?
tenure <= 6 months: {0: 0.154, 1: 0.507}median tenure: {0: 20.0, 1: 6.0}customers = pd.read_csv("data/customers.csv")# TODO: sns.ecdfplot(..., hue="churned"); ax.axvline(6, ...)# TODO: share with tenure <= 6 per group; median tenure per group# TODO: print both; plt.show(); write your interpretation as a commentHint 1
The share of a boolean column is its mean: (customers["tenure_months"] <= 6).groupby(customers["churned"]).mean().
Hint 2
On an ECDF, the height of a curve at x = 6 is exactly the share at or below 6 months. Read it from the chart and compare with the printed number.
Solution
customers = pd.read_csv("data/customers.csv")fig, ax = plt.subplots(figsize=(7, 3.5))sns.ecdfplot(data=customers, x="tenure_months", hue="churned", ax=ax)ax.axvline(6, color="0.4", linestyle=":")ax.set(title="Churners are concentrated in the first months", xlabel="Tenure (months)", ylabel="Share of customers")short = (customers["tenure_months"] <= 6).groupby(customers["churned"]).mean()print("tenure <= 6 months:", short.round(3).to_dict())median_tenure = customers.groupby("churned")["tenure_months"].median()print("median tenure:", median_tenure.to_dict())assert short[1] > short[0]plt.show()tenure <= 6 months: {0: 0.154, 1: 0.507}median tenure: {0: 20.0, 1: 6.0}
How it works:
- Each curve rises from 0 to 1. Its height at 6 months is the share of the group with a tenure of 6 months or less.
- The churned curve rises much faster: a large share of churners leave in their first six months, against a much smaller share of retained customers.
- Interpretation: churn is concentrated early in the customer life. The retention team should focus on onboarding in the first months, for example with a check-in call after month 1.
Alternative: a histogram with stat="density", common_norm=False shows the same pattern, but you must read areas, not heights, to get shares.
M28-C06 · Churn rate with confidence intervals
Section titled “M28-C06 · Churn rate with confidence intervals”Draw the churn rate by payment_method as a bar chart sorted from highest to lowest, one color, with 95% bootstrap confidence intervals (seed=42) and a percent y-axis. Print a table with the rate and the number of customers of each method, in the same order.
rate customerspayment_methodelectronic_check 0.248 1563paypal 0.174 868bank_transfer 0.174 1209credit_card 0.158 1360from matplotlib.ticker import PercentFormatter
customers = pd.read_csv("data/customers.csv")# TODO: order = methods sorted by churn rate, highest first# TODO: sns.barplot(..., order=order, color="C0", errorbar=("ci", 95), seed=42)# TODO: percent axis; print rate and size per method; plt.show()Hint 1
customers.groupby("payment_method")["churned"].mean().sort_values(ascending=False).index is the order.
Hint 2
.agg(rate="mean", customers="size") gives both columns of the table in one step. PercentFormatter(xmax=1, decimals=0) formats the axis.
Solution
from matplotlib.ticker import PercentFormatter
customers = pd.read_csv("data/customers.csv")rates = ( customers.groupby("payment_method")["churned"] .agg(rate="mean", customers="size") .sort_values("rate", ascending=False))fig, ax = plt.subplots(figsize=(7, 3.5))sns.barplot(data=customers, x="payment_method", y="churned", order=rates.index, color="C0", errorbar=("ci", 95), seed=42, ax=ax)ax.yaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=0))ax.set(title="Electronic check customers churn most", xlabel="Payment method", ylabel="Churn rate")print(rates.round(3))assert rates.index[0] == "electronic_check"plt.show() rate customerspayment_methodelectronic_check 0.248 1563paypal 0.174 868bank_transfer 0.174 1209credit_card 0.158 1360
How it works:
- Sorting the bars makes the ranking visible at once;
order=rates.indexpasses that order to Seaborn. - The error bars come from 1,000 bootstrap resamples per bar.
seed=42makes them the same on every run. - The electronic-check interval does not overlap the others, so its higher churn is not noise. The other three intervals overlap, so their differences may be chance.
Alternative: sns.pointplot(..., linestyle="none") draws a dot and an interval per method, which uses less ink than bars when the rates are far from zero.
M28-C07 · A heatmap of support tickets and contract
Section titled “M28-C07 · A heatmap of support tickets and contract”Build a table of churn rate with one row per contract (month-to-month, one-year, two-year) and one column per number of support tickets, where 5 or more tickets form one column 5+. Draw it as an annotated heatmap with percent labels, a percent color bar and a sequential colormap from 0 to 1. A rate from a handful of customers is not reliable, so count the customers per cell and hide the cells with fewer than 30. Print the rate table rounded to 2 decimals and the count table.
tickets 0 1 2 3 4 5+contractmonth-to-month 0.21 0.23 0.31 0.49 0.66 0.94one-year 0.08 0.10 0.08 0.09 0.09 0.00two-year 0.02 0.04 0.05 0.02 0.00 0.00support_tickets 0 1 2 3 4 5+contractmonth-to-month 795 966 582 279 128 34one-year 425 427 229 98 34 12two-year 317 349 216 80 22 7customers = pd.read_csv("data/customers.csv")contracts = ["month-to-month", "one-year", "two-year"]# TODO: tickets = support_tickets clipped at 5, as text, with "5" replaced by "5+"# TODO: rates = pivot_table(index="contract", columns=tickets, values="churned")# TODO: counts = pd.crosstab(contract, tickets), rows in the same order# TODO: sns.heatmap(rates, mask=..., annot=True, fmt=".0%", cmap="rocket_r", ...)# TODO: print rates and counts; plt.show()Hint 1
customers["support_tickets"].clip(upper=5) caps the values at 5. .astype(str).replace("5", "5+") relabels the cap.
Hint 2
Add the new column with assign(tickets=...) before pivot_table. Reorder the rows with .loc[contracts]. mask=(counts < 30).to_numpy() hides the small cells; cbar_kws={"format": PercentFormatter(1)} formats the color bar.
Solution
from matplotlib.ticker import PercentFormatter
customers = pd.read_csv("data/customers.csv")contracts = ["month-to-month", "one-year", "two-year"]tickets = customers["support_tickets"].clip(upper=5).astype(str).replace("5", "5+")rates = ( customers.assign(tickets=tickets) .pivot_table(index="contract", columns="tickets", values="churned") .loc[contracts])counts = pd.crosstab(customers["contract"], tickets).loc[contracts]fig, ax = plt.subplots(figsize=(8, 3.2))sns.heatmap(rates, mask=(counts < 30).to_numpy(), annot=True, fmt=".0%", cmap="rocket_r", vmin=0, vmax=1, linewidths=1, ax=ax, cbar_kws={"label": "churn rate", "format": PercentFormatter(1)})ax.set(title="Month-to-month churn climbs with every support ticket", xlabel="Support tickets (blank: fewer than 30 customers)", ylabel="")ax.tick_params(axis="y", labelrotation=0)print(rates.round(2))print(counts)assert rates.loc["month-to-month"].is_monotonic_increasingplt.show()tickets 0 1 2 3 4 5+contractmonth-to-month 0.21 0.23 0.31 0.49 0.66 0.94one-year 0.08 0.10 0.08 0.09 0.09 0.00two-year 0.02 0.04 0.05 0.02 0.00 0.00support_tickets 0 1 2 3 4 5+contractmonth-to-month 795 966 582 279 128 34one-year 425 427 229 98 34 12two-year 317 349 216 80 22 7
How it works:
- Clipping at 5 merges the rare high counts into one column, but the
5+cells are still small: the count table shows how many customers each rate rests on. A 0% from a dozen customers says almost nothing, so the mask hides every cell with fewer than 30 customers. Always check the cell sizes before you trust a heatmap of rates. vmin=0, vmax=1fixes the color scale to the full range of a rate, so the same shade always means the same rate.- The month-to-month row rises with every ticket, while the one-year and two-year rows stay low. This is an interaction: the effect of tickets depends on the contract. A model needs both features together to capture it.
Alternative: pd.crosstab(customers["contract"], tickets, values=customers["churned"], aggfunc="mean") builds the same table.
M28-C08 · Correlation heatmap of the churn data
Section titled “M28-C08 · Correlation heatmap of the churn data”Draw the correlation matrix of the numeric columns of data/customers.csv as a heatmap that shows only the lower triangle, with a diverging colormap centered at 0 and values with 2 decimals. Print the three columns with the strongest correlation (by absolute value) with churned.
tenure_months -0.281total_charges -0.212support_tickets 0.210Name: churned, dtype: float64customers = pd.read_csv("data/customers.csv")# TODO: corr = numeric columns .corr()# TODO: mask = upper triangle with np.triu(np.ones_like(corr, dtype=bool))# TODO: sns.heatmap(corr, mask=mask, annot=True, fmt=".2f", cmap="vlag", ...)# TODO: print the top 3 by absolute correlation with churned; plt.show()Hint 1
customers.select_dtypes("number") keeps only numeric columns, so customer_id and the text columns drop out.
Hint 2
sort_values(key=abs, ascending=False) sorts by size and ignores the sign. Drop churned itself first: its correlation with itself is 1.
Solution
customers = pd.read_csv("data/customers.csv")corr = customers.select_dtypes("number").corr()mask = np.triu(np.ones_like(corr, dtype=bool))fig, ax = plt.subplots(figsize=(7.5, 6))sns.heatmap(corr.iloc[1:, :-1], mask=mask[1:, :-1], annot=True, fmt=".2f", cmap="vlag", vmin=-1, vmax=1, linewidths=0.5, annot_kws={"size": 8}, ax=ax)ax.set_title("Correlations in customers.csv")top = corr["churned"].drop("churned").sort_values(key=abs, ascending=False)print(top.head(3).round(3))assert top.index[0] == "tenure_months"plt.show()tenure_months -0.281total_charges -0.212support_tickets 0.210Name: churned, dtype: float64
How it works:
np.triumarks the upper triangle and the diagonal asTrue;mask=hides those cells, so each pair appears once. The first row and the last column would then be empty, socorr.iloc[1:, :-1]drops them andmask[1:, :-1]cuts the mask to match.- The symmetric limits
vmin=-1, vmax=1withvlaggive white to 0, blue to negative and red to positive values. (Seaborn’scenter=0does the same, but with Matplotlib 3.11 it triggers a hidden deprecation warning inside Seaborn 0.13.2.) - Tenure has the strongest link: longer customers churn less (negative). Support tickets push churn up. All values are modest, because churn also depends on categories (contract, payment) and on non-linear effects that a correlation does not see.
Alternative: sns.clustermap(corr, cmap="vlag", vmin=-1, vmax=1) reorders the columns so that correlated ones sit together.
M28-C09 · Regression plot of signups against visitors
Section titled “M28-C09 · Regression plot of signups against visitors”Draw signups against unique_visitors from data/web_traffic.csv with sns.regplot, small transparent points and a red-orange line ("C3"). Then compute the slope and intercept of the fitted line with np.polyfit and the correlation. Print them and read the slope as a conversion rate.
slope 0.0252, intercept -9.6, r 0.948traffic = pd.read_csv("data/web_traffic.csv")# TODO: sns.regplot(data=traffic, x=..., y=..., scatter_kws=..., line_kws=..., ax=ax)# TODO: slope, intercept = np.polyfit(...); r = correlation# TODO: print them; plt.show()Hint 1
scatter_kws={"s": 8, "alpha": 0.4} and line_kws={"color": "C3"} pass options to the points and to the line.
Hint 2
np.polyfit(x, y, deg=1) returns [slope, intercept]. traffic["unique_visitors"].corr(traffic["signups"]) gives r.
Solution
traffic = pd.read_csv("data/web_traffic.csv")fig, ax = plt.subplots(figsize=(6.5, 4))sns.regplot(data=traffic, x="unique_visitors", y="signups", ax=ax, scatter_kws={"s": 8, "alpha": 0.4}, line_kws={"color": "C3"}, seed=42) # the CI band is a bootstrap: fix its seedax.set(title="About 2.5 signups per 100 unique visitors", xlabel="Unique visitors per day", ylabel="Signups per day")slope, intercept = np.polyfit(traffic["unique_visitors"], traffic["signups"], deg=1)r = traffic["unique_visitors"].corr(traffic["signups"])print(f"slope {slope:.4f}, intercept {intercept:.1f}, r {r:.3f}")assert 0.02 < slope < 0.03plt.show()slope 0.0252, intercept -9.6, r 0.948
How it works:
regplotdraws the points, fits a least-squares line and shades its 95% confidence band. Here the band is very thin, because 1,096 days pin the line down.- The slope 0.025 means each extra unique visitor brings 0.025 signups: a marginal conversion rate of about 2.5%.
- r = 0.95 is a very strong straight-line relationship. The high points above the line are campaign days, where visitors convert better.
Alternative: sns.lmplot(data=traffic.assign(campaign=traffic["marketing_spend"] > 2000), x="unique_visitors", y="signups", hue="campaign") fits one line per group and shows the campaign effect.
M28-C10 · Refactor a loop into a figure-level function
Section titled “M28-C10 · Refactor a loop into a figure-level function”Refactor: the code below draws monthly units per category for 2024 with a manual loop over a 2 × 3 grid. Replace the loop with one sns.relplot call that draws the same six panels. Print the shape of the grid of Axes and the six panel titles.
(6,)['Beauty', 'Books', 'Clothing', 'Electronics', 'Home', 'Sports']sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])units = ( sales[sales["order_date"].dt.year == 2024] .assign(month=lambda d: d["order_date"].dt.month) .groupby(["category", "month"], as_index=False)["quantity"].sum())categories = sorted(units["category"].unique())fig, axs = plt.subplots(2, 3, figsize=(10, 5), sharex=True)for ax, category in zip(axs.flat, categories): subset = units[units["category"] == category] ax.plot(subset["month"], subset["quantity"]) ax.set_title(category)# TODO: replace the loop with one sns.relplot(...) callplt.show()Hint 1
The long table units already has one row per category and month. col="category" makes one panel per category; col_wrap=3 breaks after three.
Hint 2
g.set_titles("{col_name}") gives short panel titles. g.axes is the array of Axes; with col_wrap, it is 1-D.
Solution
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])units = ( sales[sales["order_date"].dt.year == 2024] .assign(month=lambda d: d["order_date"].dt.month) .groupby(["category", "month"], as_index=False)["quantity"].sum())g = sns.relplot(data=units, x="month", y="quantity", col="category", col_wrap=3, kind="line", marker="o", height=2.4, aspect=1.3, facet_kws={"sharey": False})g.set_titles("{col_name}")g.set_axis_labels("Month (2024)", "Units")print(g.axes.shape)titles = [ax.get_title() for ax in g.axes.flat]print(titles)assert len(titles) == 6plt.show()(6,)['Beauty', 'Books', 'Clothing', 'Electronics', 'Home', 'Sports']
How it works:
relplotsplits the long table bycoland draws a line in each panel. The loop, the subsetting and the titles are gone.- The panels come in sorted order of the category values, the same order as the loop.
sharey=Falselets each panel use its own range, because Clothing sells many more units than Books. To compare levels instead, keep the default shared axis.
Alternative: g = sns.FacetGrid(units, col="category", col_wrap=3) followed by g.map_dataframe(sns.lineplot, x="month", y="quantity") builds the same grid in two steps, and lets you map any plotting function.
M28-C11 · Interpret an A/B test violin plot
Section titled “M28-C11 · Interpret an A/B test violin plot”Interpret a result: data/ab_test.csv holds a checkout-page test. Draw a split violin plot of time_on_page_s by device, with group as hue and quartile lines. Print the median time on page for each device and group as a table. Then answer: does the treatment page keep users longer on every device?
group control treatmentdevicedesktop 83.2 91.3mobile 66.8 76.6tablet 69.1 74.4ab = pd.read_csv("data/ab_test.csv")devices = ["desktop", "mobile", "tablet"]# TODO: sns.violinplot(..., hue="group", split=True, inner="quart", order=devices)# TODO: medians = groupby(["device", "group"]) median, unstacked# TODO: print medians; plt.show(); answer in a commentHint 1
split=True needs exactly two hue levels; group has two: control and treatment.
Hint 2
.unstack() after the groupby puts the groups side by side, which makes the comparison easy to read.
Solution
ab = pd.read_csv("data/ab_test.csv")devices = ["desktop", "mobile", "tablet"]fig, ax = plt.subplots(figsize=(7.5, 4))sns.violinplot(data=ab, x="device", y="time_on_page_s", hue="group", order=devices, split=True, inner="quart", cut=0, ax=ax)ax.set(title="Time on page by device and test group", xlabel="Device", ylabel="Time on page (s)")medians = ab.groupby(["device", "group"])["time_on_page_s"].median().unstack()print(medians.round(1))assert (medians["treatment"] > medians["control"]).all()plt.show()group control treatmentdevicedesktop 83.2 91.3mobile 66.8 76.6tablet 69.1 74.4
How it works:
- Each violin shows the full distribution, which is right-skewed: most visits are short and a few are long. Medians describe such data better than means.
cut=0stops each violin at the smallest and largest real value, so no density appears below 0 seconds.- Interpretation: the treatment median is higher on every device, so the new page keeps users longer everywhere. Longer is not automatically better on a checkout page; module 29 tests whether the difference is real and whether it comes with more conversions.
Alternative: sns.boxenplot (a letter-value plot) shows more quantiles than a box plot for large samples and does not trigger the Matplotlib 3.11 warning that sns.boxplot does.
M28-C12 · An interactive bar chart with Plotly Express
Section titled “M28-C12 · An interactive bar chart with Plotly Express”Build an interactive grouped bar chart of total revenue per category and year from data/sales.csv with Plotly Express. Use the color-blind-friendly Safe palette, the plotly_white template, readable axis titles and a tooltip such as Electronics: 1,021,503 USD. Print the trace names and the number of bars in each trace.
['2023', '2024'] [6, 6]import plotly.express as px
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])# TODO: totals with columns category, year (as text) and revenue# TODO: px.bar(..., color="year", barmode="group", labels=..., template=...)# TODO: fig.update_traces(hovertemplate=...); fig.show()# TODO: print the trace names and bar countsHint 1
Make the year text with .dt.year.astype(str): Plotly then treats it as a category with distinct colors, not as a number on a color scale.
Hint 2
Each color group is one trace in fig.data. A trace has a name and an x tuple.
Solution
import plotly.express as px
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])totals = ( sales.assign(year=sales["order_date"].dt.year.astype(str)) .groupby(["category", "year"], as_index=False)["revenue"].sum())fig = px.bar( totals, x="category", y="revenue", color="year", barmode="group", labels={"category": "Category", "revenue": "Revenue (USD)", "year": "Year"}, title="Revenue by category, 2023 vs 2024", template="plotly_white", color_discrete_sequence=px.colors.qualitative.Safe,)fig.update_traces(hovertemplate="%{x}: %{y:,.0f} USD")fig.show()print([trace.name for trace in fig.data], [len(trace.x) for trace in fig.data])assert len(fig.data) == 2['2023', '2024'] [6, 6]How it works:
- Plotly Express makes one trace per
colorvalue: here one per year, each with six bars. barmode="group"places the bars side by side; the default"relative"would stack them.hovertemplatecontrols the tooltip text:%{x}is the category and%{y:,.0f}the revenue with a thousands separator.
Alternative: text_auto=".3s" in px.bar writes short labels such as 1.02M on the bars, so a static screenshot keeps the values too.
M28-C13 · Fix a misleading bar chart
Section titled “M28-C13 · Fix a misleading bar chart”Fix the bug: this chart of 2024 revenue by region has three problems: the y-axis starts at 190,000, every bar has a different rainbow color that means nothing, and the bars are in no order. Fix all three: start at zero, use one color, sort from highest to lowest. Print the y-axis limits, the number of distinct bar colors and the revenue per region in thousands.
ylim: (0, 572003)colors: 1regionEast 544.8South 482.3North 477.7West 446.2Name: revenue, dtype: float64sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])y2024 = sales[sales["order_date"].dt.year == 2024]by_region = y2024.groupby("region")["revenue"].sum()fig, ax = plt.subplots(figsize=(6, 3.5))colors = plt.cm.jet(np.linspace(0, 1, len(by_region)))ax.bar(by_region.index, by_region.to_numpy(), color=colors)ax.set_ylim(190_000, 560_000)# TODO: fix the three problems; print the checks; plt.show()Hint 1
sort_values(ascending=False) orders the regions. color="C0" gives all bars one color.
Hint 2
ax.set_ylim(0, None) starts the axis at zero. {bar.get_facecolor() for bar in bars} collects the distinct colors.
Solution
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])y2024 = sales[sales["order_date"].dt.year == 2024]by_region = y2024.groupby("region")["revenue"].sum().sort_values(ascending=False)fig, ax = plt.subplots(figsize=(6, 3.5))bars = ax.bar(by_region.index, by_region.to_numpy(), color="C0")ax.set_ylim(0, None)ax.bar_label(bars, labels=[f"{v / 1000:,.0f}k" for v in by_region])ax.set(title="2024 revenue by region: East leads", ylabel="Revenue (USD)")print("ylim:", tuple(int(v) for v in ax.get_ylim()))print("colors:", len({bar.get_facecolor() for bar in bars}))print((by_region / 1000).round(1))assert ax.get_ylim()[0] == 0plt.show()ylim: (0, 572003)colors: 1regionEast 544.8South 482.3North 477.7West 446.2Name: revenue, dtype: float64
How it works:
- A bar’s length is its value only if the bar starts at 0. From 190,000, the smallest region’s bar looked a fraction of the largest; from 0, the real gap is clear.
- Color should carry meaning. Four random colors suggest four kinds of thing, and
jetalso changes lightness unevenly. One color says “same measure, different region”. - Sorting turns the chart into a ranking that the reader gets at a glance. The labels give the exact values.
Alternative: a horizontal dot plot (ax.scatter(by_region, by_region.index)) may use a zoomed axis honestly, because a dot encodes position, not length.
M28-C14 · A pair plot of the iris dataset
Section titled “M28-C14 · A pair plot of the iris dataset”Load scikit-learn’s bundled iris dataset as a DataFrame, add a species column with the species names and draw a corner pair plot colored by species. Print the shape of the data, the shape of the grid of Axes and the mean petal length per species. Which measurement separates the three species best?
(150, 6) (4, 4)speciessetosa 1.46versicolor 4.26virginica 5.55Name: petal length (cm), dtype: float64from sklearn.datasets import load_iris
bunch = load_iris(as_frame=True)# TODO: iris = bunch.frame; species = map target 0, 1, 2 to bunch.target_names# TODO: sns.pairplot(iris.drop(columns="target"), hue="species", corner=True, height=1.8)# TODO: print shapes and the mean petal length per species; plt.show()Hint 1
bunch.frame holds the four measurements and the target column (0, 1 or 2). bunch.target_names holds the three names in that order.
Hint 2
iris["target"].map(dict(enumerate(bunch.target_names))) turns the codes into names. The returned PairGrid has g.axes.
Solution
from sklearn.datasets import load_iris
bunch = load_iris(as_frame=True)iris = bunch.frame.copy()iris["species"] = iris["target"].map(dict(enumerate(bunch.target_names)))g = sns.pairplot(iris.drop(columns="target"), hue="species", corner=True, height=1.8, plot_kws={"s": 12})print(iris.shape, g.axes.shape)print(iris.groupby("species")["petal length (cm)"].mean().round(2))assert g.axes.shape == (4, 4)plt.show()(150, 6) (4, 4)speciessetosa 1.46versicolor 4.26virginica 5.55Name: petal length (cm), dtype: float64
How it works:
load_iris(as_frame=True)returns pandas objects;framecombines the features and the target.- The pair plot has a 4 × 4 grid;
corner=Trueleaves the upper triangle empty (those Axes areNone). - The petal panels separate the species best: setosa forms its own cluster with short petals, and versicolor and virginica overlap only a little. Sepal width alone separates them poorly. A classifier in module 36 confirms this.
Alternative: sns.pairplot(..., kind="kde") draws density contours instead of points, which helps when points overlap.
Challenge
Section titled “Challenge”M28-X01 · A one-page sales dashboard
Section titled “M28-X01 · A one-page sales dashboard”Build a one-page dashboard from data/sales.csv with plt.subplot_mosaic: a wide monthly revenue trend on top with the peak annotated, and three panels below: revenue by category (sorted horizontal bars), the online and store share of revenue per year (100% stacked bars) and mean daily revenue by weekday. Give every panel a title that states its finding. Save it as output/sales_dashboard.png at dpi=150, then print the key numbers.
total revenue: 3,596,524 USD, growth 2024: 18.6%online share: {2023: 0.378, 2024: 0.46}best weekday: Sat | top category: Electronicsfrom pathlib import Path
from matplotlib.ticker import FuncFormatter, PercentFormatter
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])k = FuncFormatter(lambda v, pos: f"{v / 1000:,.0f}k")# TODO: monthly revenue, revenue by category, channel share by year, weekday means# TODO: fig, axd = plt.subplot_mosaic([["trend"] * 3, ["category", "channel", "weekday"]],# figsize=(12, 7), layout="constrained")# TODO: draw the four panels; annotate the peak; save; print; plt.show()Hint 1
The channel shares per year: pd.crosstab(year, sales["channel"], values=sales["revenue"], aggfunc="sum", normalize="index"). Each row then adds up to 1.
Hint 2
A 100% stacked bar is two ax.bar calls: the first share from 0, the second with bottom= the first share.
Hint 3
Weekday means: total revenue per date first, then groupby(daily.index.day_of_week).mean().
Solution
from pathlib import Path
from matplotlib.ticker import FuncFormatter, PercentFormatter
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])k = FuncFormatter(lambda v, pos: f"{v / 1000:,.0f}k")monthly = sales.set_index("order_date")["revenue"].resample("MS").sum()by_cat = sales.groupby("category")["revenue"].sum().sort_values()year = sales["order_date"].dt.year.rename("year")share = pd.crosstab(year, sales["channel"], values=sales["revenue"], aggfunc="sum", normalize="index")daily = sales.groupby("order_date")["revenue"].sum()days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]by_day = daily.groupby(daily.index.day_of_week).mean().set_axis(days)
fig, axd = plt.subplot_mosaic([["trend"] * 3, ["category", "channel", "weekday"]], figsize=(12, 7), layout="constrained")ax = axd["trend"]ax.plot(monthly.index, monthly.to_numpy(), marker="o")ax.annotate(f"peak {monthly.max() / 1000:,.0f}k", xy=(monthly.idxmax(), monthly.max()), xytext=(pd.Timestamp("2024-05-01"), 280_000), arrowprops={"arrowstyle": "->", "color": "0.3"})ax.yaxis.set_major_formatter(k)ax.set_ylim(0, None)ax.set_title("Monthly revenue: +19% in 2024, peaks every December")ax = axd["category"]ax.barh(by_cat.index, by_cat.to_numpy(), color="C0")ax.xaxis.set_major_formatter(k)ax.set_title("Electronics is half of revenue")ax = axd["channel"]labels = share.index.astype(str)ax.bar(labels, share["online"], label="online", color="C0")ax.bar(labels, share["store"], bottom=share["online"], label="store", color="C1")ax.yaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=0))ax.legend(loc="lower right", frameon=True)ax.set_title("Online share grows")ax = axd["weekday"]ax.bar(days, by_day.to_numpy(), color=["C1" if d == "Sat" else "0.7" for d in days])ax.yaxis.set_major_formatter(k)ax.set_title("Saturday is the best day")fig.suptitle("Sales review 2023–2024", fontsize=16, fontweight="bold")Path("output").mkdir(exist_ok=True)fig.savefig("output/sales_dashboard.png", dpi=150, bbox_inches="tight")
growth = monthly["2024"].sum() / monthly["2023"].sum() - 1print(f"total revenue: {monthly.sum():,.0f} USD, growth 2024: {growth:.1%}")print("online share:", share["online"].round(3).to_dict())print("best weekday:", by_day.idxmax(), "| top category:", by_cat.index[-1])assert Path("output/sales_dashboard.png").exists()plt.show()total revenue: 3,596,524 USD, growth 2024: 18.6%online share: {2023: 0.378, 2024: 0.46}best weekday: Sat | top category: Electronics
How it works:
- All numbers are computed first, then drawn. Keeping data work and drawing apart makes both easier to test.
subplot_mosaictakes a picture of the layout:["trend"] * 3makes the trend span all three columns of the first row.- Each panel’s title is a finding, so a reader who only skims the titles still gets the story.
- The stacked bars use
bottom=so that online and store add up to 100% for each year.normalize="index"made each row of the crosstab sum to 1. resample("MS")labels each month by its first day, so each point sits inside its own month on the date axis; month-end labels would put December on the January tick.monthly["2024"]selects all months of 2024 by partial string indexing on the date index.
Alternative: write one function per panel (plot_trend(ax, monthly), plot_categories(ax, by_cat) and so on), as in the lesson’s Example 1. Each function then works in this dashboard, in a slide or in a single chart.
M28-X02 · Mark vibration spikes on a sensor chart
Section titled “M28-X02 · Mark vibration spikes on a sensor chart”A spike here is a reading of sensor S4 in data/sensors.csv that is more than 3 times the centered rolling median of the surrounding day (144 readings, at least 72 present). Draw S4 vibration as a thin line, the rolling median as a thick line, the spikes as red-orange dots, and the warn (4.5 mm/s) and fail (11.2 mm/s) levels as dashed lines. Print the number of spikes and the three largest.
spikes: 10timestamp2024-05-12 06:40:00 18.982024-05-13 01:30:00 18.572024-05-04 10:30:00 17.73Name: vibration_mm_s, dtype: float64import matplotlib.dates as mdates
sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])# TODO: s4 = S4 vibration as a Series indexed by timestamp# TODO: baseline = s4.rolling(144, center=True, min_periods=72).median()# TODO: spikes = s4[s4 > 3 * baseline]# TODO: line, baseline, ax.scatter for spikes, two axhline levels, legend# TODO: print the count and spikes.nlargest(3); plt.show()Hint 1
sensors[sensors["sensor_id"] == "S4"].set_index("timestamp")["vibration_mm_s"] gives the Series. Blank readings stay NaN; a comparison with NaN is False, so they never count as spikes.
Hint 2
center=True puts the window around each reading, half before and half after, so a spike is compared with its neighbors on both sides.
Solution
import matplotlib.dates as mdates
sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])s4 = sensors[sensors["sensor_id"] == "S4"].set_index("timestamp")["vibration_mm_s"]baseline = s4.rolling(144, center=True, min_periods=72).median()spikes = s4[s4 > 3 * baseline]fig, ax = plt.subplots(figsize=(9, 4))ax.plot(s4.index, s4.to_numpy(), linewidth=0.5, color="C0", alpha=0.7, label="reading")ax.plot(baseline.index, baseline.to_numpy(), linewidth=2, color="C2", label="rolling median (1 day)")ax.scatter(spikes.index, spikes.to_numpy(), color="C3", s=20, zorder=3, label=f"spike > 3x median ({len(spikes)})")ax.axhline(4.5, color="0.4", linestyle="--", linewidth=1)ax.axhline(11.2, color="0.2", linestyle="--", linewidth=1)ax.text(s4.index[0], 4.8, "warn 4.5", fontsize=8)ax.text(s4.index[0], 11.5, "fail 11.2", fontsize=8)ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(ax.xaxis.get_major_locator()))ax.set(title="S4: isolated spikes, then steady wear from May 12", ylabel="Vibration (mm/s)")ax.legend(loc="upper left", fontsize=8)print("spikes:", len(spikes))print(spikes.nlargest(3).round(2))assert len(spikes) > 0plt.show()spikes: 10timestamp2024-05-12 06:40:00 18.982024-05-13 01:30:00 18.572024-05-04 10:30:00 17.73Name: vibration_mm_s, dtype: float64
How it works:
- The rolling median follows the slow wear trend but ignores single spikes, so it is a good baseline. A rolling mean would be pulled up by each spike.
- A ratio to the baseline (3×) adapts to the rising level after May 12: a reading of 12 mm/s is a spike in a quiet week and normal on May 14.
zorder=3draws the dots on top of the lines. The label in the legend states the rule and the count, so the chart documents itself.- The chart separates two different problems: short spikes (a sensor glitch or a knock) and a lasting rise (wear). Each needs a different alert.
Alternative: a z-score on a rolling window ((s4 - rolling_mean) / rolling_std > 4) is common too, but the spikes inflate the standard deviation and hide each other; the median-based rule is more robust.
M28-X03 · An A/B test chart with error bars you compute
Section titled “M28-X03 · An A/B test chart with error bars you compute”Compute the conversion rate of each group on each device in data/ab_test.csv, with a 95% confidence interval from the normal approximation: rate ± 1.96 × √(rate × (1 − rate) / n). Draw grouped bars (devices on the x-axis, control and treatment side by side) with these intervals as error bars, using ax.bar(..., yerr=...). Print the table of rates, sizes and interval half-widths. On which device does the treatment not win?
rate n half_widthdevice groupdesktop control 0.120 1707 0.015 treatment 0.145 1721 0.017mobile control 0.085 2792 0.010 treatment 0.100 2785 0.011tablet control 0.125 503 0.029 treatment 0.114 492 0.028treatment wins on: ['desktop', 'mobile']from matplotlib.ticker import PercentFormatter
ab = pd.read_csv("data/ab_test.csv")# TODO: summary = groupby(["device", "group"])["converted"].agg(rate="mean", n="size")# TODO: summary["half_width"] = 1.96 * sqrt(rate * (1 - rate) / n)# TODO: x = np.arange(3); bars at x - 0.2 and x + 0.2 with width 0.4 and yerr# TODO: print summary; plt.show(); answer the questionHint 1
summary.xs("control", level="group") selects the control rows of the MultiIndex, one row per device.
Hint 2
ax.bar(x - 0.2, ctrl["rate"], width=0.4, yerr=ctrl["half_width"], capsize=4, label="control") draws one set; repeat with x + 0.2 for treatment. Then ax.set_xticks(x, labels=devices).
Solution
from matplotlib.ticker import PercentFormatter
ab = pd.read_csv("data/ab_test.csv")summary = ab.groupby(["device", "group"])["converted"].agg(rate="mean", n="size")summary["half_width"] = 1.96 * np.sqrt(summary["rate"] * (1 - summary["rate"]) / summary["n"])devices = ["desktop", "mobile", "tablet"]x = np.arange(len(devices))fig, ax = plt.subplots(figsize=(7, 4))for offset, group, color in [(-0.2, "control", "C0"), (0.2, "treatment", "C1")]: part = summary.xs(group, level="group").loc[devices] ax.bar(x + offset, part["rate"], width=0.4, yerr=part["half_width"], capsize=4, color=color, label=group)ax.set_xticks(x, labels=devices)ax.yaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=0))ax.set(title="Treatment is ahead on desktop and mobile, behind on tablet", ylabel="Conversion rate (95% CI)")ax.legend(frameon=False)print(summary.round(4))lift = summary["rate"].unstack()print("treatment wins on:", list(lift.index[lift["treatment"] > lift["control"]]))assert lift.loc["tablet", "treatment"] < lift.loc["tablet", "control"]plt.show() rate n half_widthdevice groupdesktop control 0.120 1707 0.015 treatment 0.145 1721 0.017mobile control 0.085 2792 0.010 treatment 0.100 2785 0.011tablet control 0.125 503 0.029 treatment 0.114 492 0.028treatment wins on: ['desktop', 'mobile']
How it works:
- The rate of a 0/1 column is its mean. The standard error of a rate is √(p(1 − p)/n); 1.96 standard errors on each side give a 95% interval.
- The bars are placed by hand: 0.2 to the left and right of each device position, each 0.4 wide, so the pairs touch.
- “Wins” here means the point estimate: treatment has the higher rate on desktop and mobile. The desktop and mobile intervals both overlap a little. Overlapping intervals do not prove that there is no difference; a formal test of the difference (module 29) decides. On tablet, treatment is lower, but the groups are small (about 500 users each), so the intervals are wide and overlap heavily: the data cannot tell the two pages apart there.
- The normal approximation works when n × p and n × (1 − p) are both above about 10, which holds in every cell here. Module 29 adds the proper test.
Alternative: sns.barplot(data=ab, x="device", y="converted", hue="group", errorbar=("ci", 95), seed=42) computes bootstrap intervals for you; they are almost equal to these normal-approximation intervals for samples this large.
M28-X04 · Refactor chart saving into a class
Section titled “M28-X04 · Refactor chart saving into a class”Refactor: a reporting script repeats the same three lines for every chart: build the path, savefig, plt.close. It also forgets to create the folder and sometimes overwrites a chart with the same name. Write a class ChartReport with type hints:
ChartReport(folder, dpi=150)stores the settings;add(name, fig)registers a figure and raisesValueErrorfor a duplicate name;len(report)returns the number of registered figures;save_all()creates the folder, saves each figure as<name>.pngwithbbox_inches="tight", closes it and returns the list of paths.
Use it for two charts of data/customers.csv. Print the number of charts, the saved file names, the number of open figures afterward and the error message of a duplicate name.
charts: 2error: duplicate chart name: 'tenure'saved: ['churn_by_contract.png', 'tenure.png']open figures: 0 | left in report: 0from pathlib import Path
customers = pd.read_csv("data/customers.csv")fig1, ax1 = plt.subplots()customers.groupby("contract")["churned"].mean().plot.bar(ax=ax1)fig1.savefig("output/report/churn_by_contract.png", dpi=150, bbox_inches="tight")plt.close(fig1)fig2, ax2 = plt.subplots()ax2.hist(customers["tenure_months"], bins=24)fig2.savefig("output/report/tenure.png", dpi=150, bbox_inches="tight")plt.close(fig2)# TODO: replace the repeated save code with a ChartReport classHint 1
Store the figures in a dict from name to Figure: self._figures: dict[str, Figure] = {}. from matplotlib.figure import Figure gives the type for the hint.
Hint 2
__len__ makes len(report) work (module 20). In save_all, call self.folder.mkdir(parents=True, exist_ok=True) first.
Hint 3
Clear the dict at the end of save_all: the figures are closed, so the report should not hold them any longer.
Solution
from pathlib import Path
from matplotlib.figure import Figure
class ChartReport: """Collect named figures and save them together as PNG files."""
def __init__(self, folder: str | Path, dpi: int = 150) -> None: self.folder = Path(folder) self.dpi = dpi self._figures: dict[str, Figure] = {}
def add(self, name: str, fig: Figure) -> None: if name in self._figures: raise ValueError(f"duplicate chart name: {name!r}") self._figures[name] = fig
def __len__(self) -> int: return len(self._figures)
def save_all(self) -> list[Path]: self.folder.mkdir(parents=True, exist_ok=True) paths = [] for name, fig in self._figures.items(): path = self.folder / f"{name}.png" fig.savefig(path, dpi=self.dpi, bbox_inches="tight") plt.close(fig) paths.append(path) self._figures.clear() return paths
customers = pd.read_csv("data/customers.csv")report = ChartReport("output/report")fig, ax = plt.subplots()customers.groupby("contract")["churned"].mean().plot.bar(ax=ax, rot=0)ax.set(title="Churn rate by contract", ylabel="Churn rate")report.add("churn_by_contract", fig)fig, ax = plt.subplots()ax.hist(customers["tenure_months"], bins=24)ax.set(title="Tenure", xlabel="Months", ylabel="Customers")report.add("tenure", fig)print("charts:", len(report))try: report.add("tenure", fig)except ValueError as error: print("error:", error)paths = report.save_all()print("saved:", [path.name for path in paths])print("open figures:", len(plt.get_fignums()), "| left in report:", len(report))assert all(path.exists() for path in paths)charts: 2error: duplicate chart name: 'tenure'saved: ['churn_by_contract.png', 'tenure.png']open figures: 0 | left in report: 0How it works:
- The class keeps the settings (folder, dpi) in one place, so every chart is saved the same way.
addchecks for duplicates before it stores the figure. A silent overwrite would lose a chart; an exception makes the mistake visible at once.save_allcreates the folder, saves, closes and returns the paths, which a caller can attach to an email or list in a log. After it, no figure stays open.__len__lets the report behave like a built-in container:len(report).
Alternative: a context manager (module 11) that saves and closes on exit, with ChartReport("output/report") as report: ..., guarantees the save even if a chart in the middle fails. Add __enter__ returning self and __exit__ calling save_all().
M28-X05 · An interactive outlier explorer
Section titled “M28-X05 · An interactive outlier explorer”Price per square foot varies a lot between neighborhoods, so an outlier must be judged within its neighborhood. For each house in data/houses.csv, compute the log of price per sqft and its z-score within its neighborhood (subtract the neighborhood mean, divide by the neighborhood standard deviation). Flag houses with |z| > 3. Build a Plotly scatter of sqft against price with a log y-axis, colored by the flag, with the house id, neighborhood and z-score in the tooltip. Print the number of flagged houses and their ids, neighborhoods, prices and z-scores.
flagged: 12house_id neighborhood price z H1144 Cedar Park 223000 -3.53 H0887 Lakeview 252500 -3.46 H2174 Maple Grove 303500 -3.21 H1990 Oak Hill 273500 -3.18 H1739 Downtown 301500 -3.14 H0160 Riverside 294500 -3.09 H0914 Cedar Park 719500 3.53 H2277 Old Town 905500 4.47 H2594 Old Town 519000 4.58 H0537 Westfield 500500 4.81 H0542 Maple Grove 2660000 5.28 H0751 Oak Hill 1431000 5.35import plotly.express as px
houses = pd.read_csv("data/houses.csv")# TODO: log_ppsf = np.log(price / sqft)# TODO: z = (log_ppsf - group mean) / group std, with groupby("neighborhood").transform# TODO: flag = np.where(z.abs() > 3, "check", "normal")# TODO: px.scatter(..., log_y=True, color="flag", hover_name="house_id", hover_data=...)# TODO: fig.show(); print the flagged rows sorted by zHint 1
transform("mean") returns the group mean for every row, aligned with the original table, so you can subtract it directly.
Hint 2
hover_data={"neighborhood": True, "z": ":.2f"} adds the columns to the tooltip and formats the z-score. category_orders={"flag": ["normal", "check"]} fixes the legend order.
Solution
import plotly.express as px
houses = pd.read_csv("data/houses.csv")houses["log_ppsf"] = np.log(houses["price"] / houses["sqft"])group = houses.groupby("neighborhood")["log_ppsf"]houses["z"] = (houses["log_ppsf"] - group.transform("mean")) / group.transform("std")houses["flag"] = np.where(houses["z"].abs() > 3, "check", "normal")fig = px.scatter( houses, x="sqft", y="price", color="flag", log_y=True, opacity=0.6, hover_name="house_id", hover_data={"neighborhood": True, "z": ":.2f"}, category_orders={"flag": ["normal", "check"]}, color_discrete_sequence=["#88CCEE", "#CC3311"], labels={"sqft": "Size (sqft)", "price": "Price (USD, log scale)"}, title="Houses whose price per sqft is unusual for their neighborhood", template="plotly_white",)fig.show()flagged = houses.loc[houses["flag"] == "check", ["house_id", "neighborhood", "price", "z"]].sort_values("z")print("flagged:", len(flagged))print(flagged.round(2).to_string(index=False))assert "H0542" in set(flagged["house_id"])flagged: 12house_id neighborhood price z H1144 Cedar Park 223000 -3.53 H0887 Lakeview 252500 -3.46 H2174 Maple Grove 303500 -3.21 H1990 Oak Hill 273500 -3.18 H1739 Downtown 301500 -3.14 H0160 Riverside 294500 -3.09 H0914 Cedar Park 719500 3.53 H2277 Old Town 905500 4.47 H2594 Old Town 519000 4.58 H0537 Westfield 500500 4.81 H0542 Maple Grove 2660000 5.28 H0751 Oak Hill 1431000 5.35How it works:
- Price per sqft removes most of the size effect. Its log makes the distribution close to normal, so a z-score of 3 means the same thing in every neighborhood.
transformkeeps one row per house, so the z-score lines up with the house it belongs to.- The scatter shows each flagged house among its peers. Hover over a red point to read its id and z-score, then decide: a data error, a special house or a real bargain.
- A z-score rule flags candidates; it does not prove an error. Some flags here are injected price errors from the dataset generator, some are genuine but unusual houses.
Alternative: a robust z-score uses the median and the median absolute deviation (MAD) instead of the mean and standard deviation, so the outliers themselves do not widen the yardstick. Module 26 shows it.