Skip to content
Learn Python with BNHR

Stretch: charts

On this page
  1. Overview
  2. S3.1 · Small multiples by province
  3. S3.2 · Honest error bars, or none
  4. S3.3 · Seasons: price by month of the year
  5. S3.4 · A trend line: fertilizer and yield
  6. S3.5 · A tooltip that answers the next question

Every exercise in 83_stretch_charts.py, with the solution and why it works. Each answer stays closed until you swear you tried it first. Opening one changes nothing in your notebook; your check still has to go green from your own code. Read the whole notebook, with its lessons.

Stretch S3.1. Small multiples by province

The task

Seven provinces' tomato prices in one chart are seven tangled lines. Small multiples give each province a small chart of its own, side by side, so the eye compares shapes. They compare honestly only if every panel shares one y scale: with a scale of its own, a province whose price barely moved fills its panel as fully as one whose price doubled.

Write province_panels(prices, commodity): one panel per province, each with the commodity's farmgate price by month as a line, every panel on the same y scale, and September 2023 a gap in every line. Return the whole figure:

  • matplotlib: fig, axes = plt.subplots(2, 4, sharey=True), one province per ax (titled with its name), an unused panel removed (ax.remove()), and return fig;
  • seaborn: sns.relplot(..., col="province", col_wrap=4, kind="line") returns a grid whose panels share their scale; titles like province = Iloilo are fine. It drops missing values, so draw each unbroken stretch as its own line (units=, with estimator=None), as module 7 section 2 shows;
  • Altair: .encode(..., facet=alt.Facet("province:N", columns=4)); a missing price breaks the line.

The check reads each panel's points, counts lines drawn across a missing month, and asks whether the panels share one y scale.

If the check is red: common causes

what you see the usual cause look at
'one y scale': False Each panel scaled itself. sharey=True; in Altair, no resolve_scale(y="independent")
'lines drawn across a gap': 7 September 2023 has no row; or seaborn dropped its missing price. reindex(pd.period_range(...)); in seaborn, units= and estimator=None
TypeError: chart_data reads a figure with one chart An ax or the array of axes was returned. return fig (or the seaborn grid, or the Altair chart)
Panels named '' The panels have no titles. ax.set_title(province)

Still stuck after ten minutes? Ask your table, then raise your hand.

The solution, and why it works

Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.

Stretch S3.2. Honest error bars, or none

The task

An error bar says "the true value is probably in here". seaborn's default bars answer that for a simple random sample of plots; this survey sampled households, with weights. So either draw intervals computed for the weighted mean, or draw none. Here is an approximate 95% interval for a weighted mean $\bar y$, from yields $y$ and weights $w$:

$$\bar y = \frac{\sum w y}{\sum w} \qquad se = \frac{\sqrt{\sum w^2 (y - \bar y)^2}}{\sum w} \qquad \text{interval: } \bar y \pm 1.96 , se$$

It treats each plot as drawn on its own. The survey drew households, and a household's plots are alike, so the survey's true interval is somewhat wider: say "approximate" on the chart.

Write interval_bars(table): for a table of plots, a bar per province (its weighted mean yield) with an error bar from the interval's low end to its high end, a value axis from zero titled with t/ha.

  • matplotlib: ax.barh(...), then ax.errorbar(means, provinces, xerr=[means - low, high - means], fmt="none") (xerr takes the distances below and above);
  • seaborn: sns.barplot(summary, ..., errorbar=None, ax=ax), then the same ax.errorbar: seaborn's own errorbar= cannot draw intervals you computed;
  • Altair: a layer of mark_bar() and mark_errorbar() with x="low:Q", x2="high:Q".

The check reads the bars, each error bar's two ends (to 3 decimals), and the value axis.

If the check is red: common causes

what you see the usual cause look at
The error bars are close but not right seaborn's own error bars (a bootstrap), or a plain standard error. compute se from the formula, with the weights
The error bars are twice too long, or end at the wrong place xerr given the ends, not the distances to them. xerr=[mean - low, high - mean]
'error bars': [] The error bars are drawn another way (ax.hlines, ax.plot). ax.errorbar, or Altair's mark_errorbar / mark_rule with x2
'value axis names the unit': False No axis title, or one without t/ha. ax.set_xlabel(...)

Still stuck after ten minutes? Ask your table, then raise your hand.

The solution, and why it works

Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.

Stretch S3.3. Seasons: price by month of the year

The task

Four years of tomato prices in one long line show a trend; laid over each other, one line per year with January to December along the x axis, they show the season: when in the year the price climbs and falls, and whether every year does it.

Write seasonal_lines(prices, commodity): the commodity's price, averaged over the provinces for each month; then one line per year (named by the year, as text: "2022"), x the month of the year as a number (1 to 12), every month from the first to the last a point, and September 2023 a gap in 2023's line. The value axis's title contains PHP/kg.

Tools: groupby("month")["price"].mean() and the reindex from module 7; on a period index, .year and .month give each month's year and month number. ax.set_xticks(range(1, 13), calendar.month_abbr[1:]) labels the months by name (the check reads the numbers, not the labels).

If the check is red: common causes

what you see the usual cause look at
'lines drawn across a gap': 1 September 2023 has no row, so 2023's line joins August to October. reindex before turning the months around
Every row's series is None The years' lines have no names. label=str(year); in seaborn hue="year"; in Altair color="year:N"
Many more lines, or x values like '2023-07-01' The months were not turned into month numbers. .month on the period index
Prices off by a little The provinces were not averaged, or one province was picked. groupby("month")["price"].mean()

Still stuck after ten minutes? Ask your table, then raise your hand.

The solution, and why it works

Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.

Stretch S3.4. A trend line: fertilizer and yield

The task

Do rice plots that get more fertilizer per hectare yield more? A scatter shows every plot as a point; a trend line summarizes how yield changes, on average, as fertilizer grows. Fit it, don't draw it by eye: the least-squares line is the straight line that keeps the points' squared vertical distances to it as small as possible, and np.polyfit(x, y, 1) gives its slope and intercept.

Write fertilizer_trend(table): for a table of plots, keep those with fertilizer recorded; x is fertilizer per hectare (fertilizer_kg / area_ha), y the yield (t/ha). Draw every plot as a point, and the least-squares line as a line from the smallest x to the largest.

  • matplotlib: ax.scatter(x, y), then ax.plot([x_min, x_max], [...]) from the slope and intercept;
  • seaborn: sns.regplot(data, x=..., y=..., ax=ax) fits and draws it in one call (its shaded band is not checked);
  • Altair: Altair's own transform_regression draws in your browser, where the check cannot read it, so fit with np.polyfit and layer the points with a line drawn from a two-row table.

The check reads the points, and the line's slope and intercept. Then read your chart: what does the line say?

If the check is red: common causes

what you see the usual cause look at
LinAlgError or nan from np.polyfit Plots without fertilizer recorded are still in. table[table["fertilizer_kg"].notna()]
The slope is far off x is total fertilizer, not per hectare. fertilizer_kg / area_ha
'trend line (slope, intercept)': None No line is drawn, or Altair's transform_regression (the check can't run it). a line from np.polyfit's slope and intercept
More points than plots The line was drawn with markers. ax.plot(...) without marker=; points with ax.scatter

Still stuck after ten minutes? Ask your table, then raise your hand.

The solution, and why it works

Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.

Stretch S3.5. A tooltip that answers the next question

The task

A reader looking at a bar of yields asks two things next: what exactly is it? and how many plots is it based on? On a screen, a tooltip answers both when the pointer rests on the bar, without crowding the chart. Only Altair (of the three) makes charts with tooltips: matplotlib and seaborn draw pictures.

Write tooltip_bars(table), in Altair: for a table of plots, one bar per province with its weighted mean yield, a value axis from zero titled with t/ha, and a tooltip that shows the province, the yield (yield_t_ha, formatted to two decimals) and the number of plots in the survey behind it (a column plots).

Tools: groupby("province").agg(...) with named aggregations for the sums and the count (module 4, section 1); tooltip=[alt.Tooltip("province:N", title="Province"), alt.Tooltip("yield_t_ha:Q", format=".2f", title="..."), ...]. The check reads the bars, the value axis, and which columns the tooltip shows.

If the check is red: common causes

what you see the usual cause look at
'tooltip shows': [] A matplotlib or seaborn chart (a picture: no tooltip), or no tooltip= in the encoding. alt.Chart(...).encode(..., tooltip=[...])
'plots' is missing from the tooltip The summary has no count of plots, or it is named otherwise. plots=("yield_t_ha", "size") in agg
The bars are close but not right Altair's mean(yield_t_ha), a plain mean. the weighted mean, computed in pandas
'value axis names the unit': False The axis is titled with the column's name. alt.X(..., title="Weighted mean yield (t/ha)")

Still stuck after ten minutes? Ask your table, then raise your hand.

The solution, and why it works

Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.

Something new

Identify results
LayerExplore a stretch exercises
Stretch exercises S3Stretch: charts
AboutStretch exercises of Arrays & DataFrames, after module 7: chart exercises on the survey and the prices, in the library of your choice, each with its check and its solution on the companion.
CourseArrays & DataFrames, free