Skip to main content

Chapter 1: First steps

Chapter 1: First steps

TipAt a glance
  • You will build: a table and a figure of monthly rainfall from a small sample file
  • You need: the environment in environment.yml; nothing to download
  • Time to run: under 10 seconds when tested (Windows 11)
  • Level: beginner

This chapter is an example. It reads a small file of daily rainfall, adds up each month, draws a figure and checks the result, and on the way it uses each part of the template: the boxes, a figure with alternative text, a checkpoint and a link to the source ledger. Replace it with your own first chapter.

NoteLearning objectives

By the end of this chapter you will be able to:

  • read a table of daily values with pandas;
  • add the daily values up by month;
  • draw a figure that has alternative text;
  • end a chapter with a checkpoint.

Before running this chapter, create the environment in environment.yml and open this notebook with its kernel. The data, sample-data/rainfall.csv, is part of the repository.

1. The data

The file holds made-up daily rainfall for three imaginary stations in 2023. It was generated with a fixed random seed by sample-data/make_sample.py (ledger L1), so it describes no real place, and every run of this chapter gives the same numbers.

from pathlib import Path

import matplotlib.pyplot as plt
import pandas as pd

# The repository root, whether the notebook runs from en/, id/ or the root itself
ROOT = Path.cwd() if (Path.cwd() / "tutorial.yml").exists() else Path.cwd().parent
DATA = ROOT / "sample-data" / "rainfall.csv"
print("data file:", DATA.relative_to(ROOT).as_posix())
data file: sample-data/rainfall.csv
rain = pd.read_csv(DATA, parse_dates=["date"])
print(f"{len(rain):,} rows, {rain['station'].nunique()} stations, "
      f"{rain['date'].min():%d %b %Y} to {rain['date'].max():%d %b %Y}")
rain.head()
1,095 rows, 3 stations, 01 Jan 2023 to 31 Dec 2023
date station rain_mm
0 2023-01-01 Station A 15.2
1 2023-01-02 Station A 21.4
2 2023-01-03 Station A 0.6
3 2023-01-04 Station A 14.6
4 2023-01-05 Station A 0.0

Look before moving on. The line above the table should report 1,095 rows: 365 days for each of the three stations. Any other count means the file was changed or only partly read.

2. Monthly totals

pivot_table adds up the daily values of each month for each station, which gives a table of 12 months by 3 stations.

monthly = (rain.assign(month=rain["date"].dt.month)
               .pivot_table(index="month", columns="station", values="rain_mm", aggfunc="sum")
               .round(1))
monthly
station Station A Station B Station C
month
1 168.3 101.1 85.3
2 103.2 103.3 215.1
3 84.9 132.0 205.0
4 171.4 157.6 200.3
5 12.5 4.9 57.3
6 5.3 37.3 131.0
7 29.6 21.4 59.2
8 4.4 24.8 112.6
9 76.8 73.6 19.4
10 5.0 14.0 63.7
11 179.1 61.6 105.2
12 170.0 112.6 84.3

Look before moving on. Compare November to April with May to October. The sample was generated with rain on more days from November to April (ledger L1). Stations A and B show it clearly. Station C shows it less: with one year of data, a few heavy days can lift a dry-season month above a wet-season one, as in June (131.0 mm) against January (85.3 mm).

3. A figure

A figure in a notebook is stored in the file as an image. The #| fig-alt: line at the top of the cell gives it alternative text, which screen readers announce to readers who cannot see the image. tools/check_site.py stops the build when an image has none.

ax = monthly.plot.bar(figsize=(8, 3.5), width=0.8)
ax.set_xlabel("Month of 2023")
ax.set_ylabel("Rainfall (mm)")
ax.set_title("Monthly rainfall, made-up sample data")
plt.tight_layout()
plt.show()

Grouped bar chart of the monthly rainfall totals in the table above: for each month of 2023, one bar per station.

Checkpoint

The cell below stops with an error if the data or the table is not what this chapter expects. Every chapter ends with one, so readers know their run matches the author’s.

assert len(rain) == 3 * 365, "expected 365 days for each of 3 stations"
assert rain["rain_mm"].notna().all() and (rain["rain_mm"] >= 0).all(), "missing or negative rainfall"
assert monthly.shape == (12, 3), "expected 12 months by 3 stations"
print("checkpoint passed")
checkpoint passed

Troubleshooting

Symptom Cause Fix
FileNotFoundError for rainfall.csv The notebook was started from a folder other than en/, id/ or the repository root Open it from the repository, or set ROOT to the repository folder
ModuleNotFoundError: No module named 'pandas' The notebook runs in a kernel without the tutorial’s environment Choose the kernel of the environment from environment.yml

What comes next

Chapter 2 describes how a chapter is written: the shape it follows, the boxes, the source ledger and translation.