Charts with matplotlib · lesson 9 of 11
Parts in this lesson
Amdates.ConciseDateFormatter(locator)short, readable date labels
Bs.rolling(7).mean()4.7: the 7-day average
Cax.axvspan(start, end, color=...)shade a stretch of time
Dgdf.plot(column="rate", legend=True)a choropleth map, with geopandas

Time series and maps

Last updated

Dates and places are the two things readers most want to see data against, and both have their own tools. In this lesson you'll make date axes readable, draw a rolling average over the raw days, shade and label an event, and learn how a simple map of provinces is drawn on your own computer, and why a map of totals mostly shows where people live.

By the end of this lesson you can

  • Format a date axis with matplotlib.dates locators and formatters
  • Draw a rolling average over raw data, and shade an event
  • Explain why maps and comparisons of places need rates, not totals

Date axes

When the x-axis holds dates, matplotlib picks where the ticks go and how to write them. It often picks well, sometimes not. Run the cells: daily kilos at all four stores.

time.ipynb
  • The default writes full dates like 2024-01-15, which crowd together on a narrow chart.
  • matplotlib.dates (imported as mdates) has two kinds of helper. A locator decides where the ticks go; a formatter decides what they say. AutoDateLocator picks sensible places, and ConciseDateFormatter writes as little as possible: Jan, 08, 15, …, with the year written once at the edge. Use this pair as your starting point.
  • The third cell chooses both by hand: a tick every Monday (WeekdayLocator(byweekday=mdates.MO)) written as 08 Jan (DateFormatter("%d %b"), the same codes as Python's strftime, lesson 4.6).
  • It also adds the 7-day rolling average from lesson 4.7 on top of the raw days. The raw line goes thin and grey; the average is thicker and coloured. You see the trend without losing the days, and the weekly Saturday bumps no longer hide it.

Shading an event

Something happened in late October at one store. Step through the chart being built, then run the code that draws it.

A sales line with a typhoon shaded. Two months of daily rice sales at one store. The line jumps about every day, with a high every Saturday, and something happens in late October.1 Oct15 Oct1 Nov15 Nov30 Nov0255075100rice sold (kg)
1 of 4 Two months of daily rice sales at one store. The line jumps about every day, with a high every Saturday, and something happens in late October.
typhoon.ipynb
  • The first cell makes the course's two months of daily sales for this store (made-up numbers, with a weekly pattern), then writes in the typhoon week: 92 kg the day before as people stocked up, then two days at 20 and 18 kg, and two days with no data, NaN, because the store was shut.
  • ax.axvspan(start, end, color=...) shades the stretch of time from one date to another, behind the lines. Starting and ending at noon ("2024-10-21 12:00") puts the edges between days, so the shading covers whole days.
  • ax.text writes "Typhoon" on the shading, and ax.annotate (6.6) points at the stocking-up spike.
  • A line simply stops at NaN and starts again after it: the gap tells the truth, that there's no data. Don't fill it with zeros; the store didn't sell zero, it wasn't open.
  • rolling(7, min_periods=4) averages whatever days the window has, as long as there are at least 4. Without min_periods, the average would vanish for a whole week after each missing day. The third cell shows it still has a value on 26 October, 44.4 kg, from the five days it could use.

The shading answers "what happened here?" before the reader asks. Use it for anything outside the data that explains the data: holidays, promotions, price changes, storms.

Maps, on your computer

A choropleth colours each area of a map by a number, such as provinces by sales. matplotlib draws the shapes, but you need the shapes themselves and a library that reads them: geopandas, which is pandas with a column of shapes. It doesn't run in this page, so this step is on your computer (lesson 1.4).

import geopandas as gpd
import pandas as pd
import matplotlib.pyplot as plt

provinces = gpd.read_file("data/raw/provinces.geojson")   # shapes, one row per province
rates = pd.read_csv("data/clean/cards_by_province.csv")   # one number per province
gdf = provinces.merge(rates, on="psgc_code")               # join on the PSGC code (5.8)

fig, ax = plt.subplots(figsize=(6, 8))
gdf.plot(column="per_1000", cmap="Blues", legend=True, ax=ax,
         edgecolor="white", linewidth=0.5)
ax.set_axis_off()
ax.set_title("Loyalty cards per 1,000 people", loc="left")
fig.savefig("reports/figures/cards_map.svg")
  • gpd.read_file reads a file of shapes (GeoJSON or a shapefile). Province boundaries for the Philippines are published with their PSGC codes, so joining with merge on the code avoids the spelling problems of lesson 5.8.
  • gdf.plot(column=..., cmap=..., legend=True, ax=ax) colours each shape by the column, with a sequential map (6.7) and a colour bar. Passing ax=ax draws on your own axes, so everything from this stage still works.
  • ax.set_axis_off() hides the latitude and longitude ticks, which a reader doesn't need.

Wrong way: a map of where people live

A store chain counts loyalty-card sign-ups in five barangays (the numbers are made up). The obvious map colours each barangay by its number of cards. Run the cells, which compare the same two choices as bars.

rates.ipynb

By total cards, Poblacion is far ahead with 910, and Santa Rita is last with 230. But Poblacion has 18,200 people and Santa Rita 2,600. Divide by the population and the order reverses: Santa Rita has 88.5 cards per 1,000 people, the most, and Poblacion 50.0, the fewest.

A map of totals shows mostly where people live: big places get dark colours because they're big. That's almost never the question. The question is usually "where does the scheme do well?", and that needs a rate: per person, per household, per store. Lesson 9.4 goes further into rates and why small places jump around.

The check: before colouring places by a number, ask whether that number grows just because the place is bigger. If it does, divide by the size.

Check what you learned

Which pair gives short, readable date ticks?
A store was shut for two days. What should those days be in a daily sales chart?
A map of total sales by province shows the biggest provinces darkest. What would make it answer “where do we sell well”?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Data Analysis