Recreating Septa Transit Timetables in Python
Recently, Rich and I were poking around transit data, and we were struck by the amount of structuring that goes into transit timetables.
For example, consider this weekend rail schedule table from SEPTA, Philadelphia's transit agency (the picture is in the original post).
Notice these big pieces:
- The vertical text on the left indicating trains are traveling "TO CENTER CITY".
- The blue header, and spanner columns ("Services" and "Train Number") grouping related columns.
- The striped background for easier reading. Also the black background indicating stations in Center City (the urban core).
Tables like this often have to be created in tools like Illustrator, and updated by hand. At the same time, when agencies automate table creation, they often sacrifice a lot of the assistive features and helpful affordances of the table.
We set out to recreate this table in Great Tables (and by we I mean 99% Rich). In this post, I'll walk quickly through how we recreated it, and share some other examples of transit timetables in the wild. For the theory behind why tables like this are useful, see The Design Philosophy of Great Tables.
Reading in stops and times
For this example, I simplified SEPTA's transit data down to two pieces:
chw-stops.csv- detailed information about each stop location.times.csv- when a train arrives at a stop on the Chesnut Hill West line. Each row is a stop location, and each column is a trip (e.g. the 6:51am train).
To make the final table we joined these two together, to get the trips and stop information together.
import std/[sequtils, streams, strutils, strformat]
import nanuq
import tabelline, tabelline/nanuq, gtdata
let stops = readCsv(newStringStream(septaStopsCsv))
let times = readCsv(newStringStream(septaTimesCsv))import polars as pl
stops = pl.read_csv("../data/great-tables/septa/chw-stops.csv")
times = pl.read_csv("../data/great-tables/septa/times.csv")library(gt)
library(dplyr)
stops <- read.csv("../data/great-tables/septa/chw-stops.csv")
times <- read.csv("../data/great-tables/septa/times.csv", check.names = FALSE)Here's a quick preview of stops.
echo stops.select("stop_name", "service_access", "service_cash").head()
shape: (5, 3) ┌────────────────────┬────────────────┬──────────────┐ │ stop_name ┆ service_access ┆ service_cash │ │ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 │ ╞════════════════════╪════════════════╪══════════════╡ │ Gray 30th Street ┆ 1 ┆ 0 │ │ Suburban Station ┆ 0 ┆ 0 │ │ Jefferson Station ┆ 0 ┆ 0 │ │ Temple University ┆ 1 ┆ 0 │ │ Chestnut Hill West ┆ 0 ┆ 0 │ └────────────────────┴────────────────┴──────────────┘
stops.select("stop_name", "service_access", "service_cash").head()| stop_name | service_access | service_cash |
|---|---|---|
| str | i64 | i64 |
| "Gray 30th Street" | 1 | 0 |
| "Suburban Station" | 0 | 0 |
| "Jefferson Station" | 0 | 0 |
| "Temple University" | 1 | 0 |
| "Chestnut Hill West" | 0 | 0 |
stops |> select(stop_name, service_access, service_cash) |> head()stop_name service_access service_cash 1 Gray 30th Street 1 0 2 Suburban Station 0 0 3 Jefferson Station 0 0 4 Temple University 1 0 5 Chestnut Hill West 0 0 6 Highland 0 0
Notice that the table above has the name of each stop, and a 1 or 0 in the service_access column to indicate whether the stop is wheelchair accessible. Note that a big challenge for this specific route is that sometimes boarding the train requires using steps, and sometimes the station requires using steps. For example, Chelton Ave (not shown) does not require steps to board the train, but the station itself is not wheelchair accessible because of steps to get to the platform.
Here's a quick preview of the times.
echo times.head(3)
shape: (3, 9) ┌─────────────────┬──────────┬──────────┬──────────┬───┬──────────┬──────────┬──────────┬──────────┐ │ stop_name ┆ 8210 ┆ 8716 ┆ 8318 ┆ … ┆ 8338 ┆ 8242 ┆ 8750 ┆ 8756 │ │ --- ┆ --- ┆ --- ┆ --- ┆ ┆ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ str ┆ str ┆ str ┆ ┆ str ┆ str ┆ str ┆ str │ ╞═════════════════╪══════════╪══════════╪══════════╪═══╪══════════╪══════════╪══════════╪══════════╡ │ Chestnut Hill ┆ 06:51:00 ┆ 08:08:00 ┆ 08:49:00 ┆ … ┆ 13:52:00 ┆ 14:49:00 ┆ 16:48:00 ┆ 18:20:00 │ │ West ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ │ │ Highland ┆ 06:52:00 ┆ 08:09:00 ┆ 08:50:00 ┆ … ┆ 13:53:00 ┆ 14:50:00 ┆ 16:49:00 ┆ 18:21:00 │ │ St. Martins ┆ 06:54:00 ┆ 08:11:00 ┆ 08:52:00 ┆ … ┆ 13:55:00 ┆ 14:52:00 ┆ 16:51:00 ┆ 18:23:00 │ └─────────────────┴──────────┴──────────┴──────────┴───┴──────────┴──────────┴──────────┴──────────┘
times.head(3)| stop_name | 8210 | 8716 | 8318 | 8322 | 8338 | 8242 | 8750 | 8756 |
|---|---|---|---|---|---|---|---|---|
| str | str | str | str | str | str | str | str | str |
| "Chestnut Hill West" | "06:51:00" | "08:08:00" | "08:49:00" | "09:49:00" | "13:52:00" | "14:49:00" | "16:48:00" | "18:20:00" |
| "Highland" | "06:52:00" | "08:09:00" | "08:50:00" | "09:50:00" | "13:53:00" | "14:50:00" | "16:49:00" | "18:21:00" |
| "St. Martins" | "06:54:00" | "08:11:00" | "08:52:00" | "09:52:00" | "13:55:00" | "14:52:00" | "16:51:00" | "18:23:00" |
times |> head(3) stop_name 8210 8716 8318 8322 8338 8242
1 Chestnut Hill West 06:51:00 08:08:00 08:49:00 09:49:00 13:52:00 14:49:00
2 Highland 06:52:00 08:09:00 08:50:00 09:50:00 13:53:00 14:50:00
3 St. Martins 06:54:00 08:11:00 08:52:00 09:52:00 13:55:00 14:52:00
8750 8756
1 16:48:00 18:20:00
2 16:49:00 18:21:00
3 16:51:00 18:23:00Notice that each trip is a column (i.e. a train leaving from Chesnut Hill West at a specific time), and each row is a stop. For example, the 8210 train is the 6:51am train. (Note that schedules and train numbers can change, so this data may be out of date).
Joining these together gives us stop_times, with trips and stop information on the columns.
let stopTimes = times.join(stops, ["stop_name"], how = JoinType.Left)
.select(lit("To Center City").alias("direction"), col("*"))
echo stopTimes.head(3)
shape: (3, 20) ┌─────────────┬────────────┬──────────┬──────────┬───┬───────────┬────────────┬─────────┬──────────┐ │ direction ┆ stop_name ┆ 8210 ┆ 8716 ┆ … ┆ stop_lat ┆ stop_lon ┆ zone_id ┆ stop_url │ │ --- ┆ --- ┆ --- ┆ --- ┆ ┆ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ str ┆ str ┆ str ┆ ┆ f64 ┆ f64 ┆ str ┆ str │ ╞═════════════╪════════════╪══════════╪══════════╪═══╪═══════════╪════════════╪═════════╪══════════╡ │ To Center ┆ Chestnut ┆ 06:51:00 ┆ 08:08:00 ┆ … ┆ 40.076389 ┆ -75.208333 ┆ 2S ┆ null │ │ City ┆ Hill West ┆ ┆ ┆ ┆ ┆ ┆ ┆ │ │ To Center ┆ Highland ┆ 06:52:00 ┆ 08:09:00 ┆ … ┆ 40.070556 ┆ -75.211111 ┆ 2S ┆ null │ │ City ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ │ │ To Center ┆ St. ┆ 06:54:00 ┆ 08:11:00 ┆ … ┆ 40.065833 ┆ -75.204444 ┆ 2S ┆ null │ │ City ┆ Martins ┆ ┆ ┆ ┆ ┆ ┆ ┆ │ └─────────────┴────────────┴──────────┴──────────┴───┴───────────┴────────────┴─────────┴──────────┘
stop_times = times.join(other=stops, on="stop_name", maintain_order="left").select(
pl.lit("To Center City").alias("direction"), pl.col("*")
)
stop_times.head(3)| direction | stop_name | 8210 | 8716 | 8318 | 8322 | 8338 | 8242 | 8750 | 8756 | service_access | service_cash | service_park | fare_zone | stop_id | stop_desc | stop_lat | stop_lon | zone_id | stop_url |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| str | str | str | str | str | str | str | str | str | str | i64 | i64 | i64 | str | i64 | str | f64 | f64 | str | str |
| "To Center City" | "Chestnut Hill West" | "06:51:00" | "08:08:00" | "08:49:00" | "09:49:00" | "13:52:00" | "14:49:00" | "16:48:00" | "18:20:00" | 0 | 0 | 1 | "2" | 90801 | null | 40.076389 | -75.208333 | "2S" | null |
| "To Center City" | "Highland" | "06:52:00" | "08:09:00" | "08:50:00" | "09:50:00" | "13:53:00" | "14:50:00" | "16:49:00" | "18:21:00" | 0 | 0 | 1 | "2" | 90802 | null | 40.070556 | -75.211111 | "2S" | null |
| "To Center City" | "St. Martins" | "06:54:00" | "08:11:00" | "08:52:00" | "09:52:00" | "13:55:00" | "14:52:00" | "16:51:00" | "18:23:00" | 0 | 0 | 1 | "1" | 90803 | null | 40.065833 | -75.204444 | "2S" | null |
stop_times <-
times |>
left_join(stops, by = "stop_name") |>
mutate(direction = "To Center City", .before = 1)
stop_times |> head(3) direction stop_name 8210 8716 8318 8322
1 To Center City Chestnut Hill West 06:51:00 08:08:00 08:49:00 09:49:00
2 To Center City Highland 06:52:00 08:09:00 08:50:00 09:50:00
3 To Center City St. Martins 06:54:00 08:11:00 08:52:00 09:52:00
8338 8242 8750 8756 service_access service_cash service_park
1 13:52:00 14:49:00 16:48:00 18:20:00 0 0 1
2 13:53:00 14:50:00 16:49:00 18:21:00 0 0 1
3 13:55:00 14:52:00 16:51:00 18:23:00 0 0 1
fare_zone stop_id stop_desc stop_lat stop_lon zone_id stop_url
1 2 90801 NA 40.07639 -75.20833 2S NA
2 2 90802 NA 40.07056 -75.21111 2S NA
3 1 90803 NA 40.06583 -75.20444 2S NANotice that in the table above, the first row tells us when each train leaves Chesnut Hill West, and information about the Chesnut Hill West stop.
Creating the table
Below is the code for the table, with 5 key activities marked with comments. For example, the first is creating high level structure, like the header and the left-hand "To Center City" stub. Others include formatting in checkmarks, customizing columns (e.g. their width), and styling (e.g. setting background colors and fonts).
It's a lot to take in, but worth it!:
proc hMP(v: Value): string =
let parts = ($v).split(":").mapIt(parseInt(it))
var h = parts[0]
var ap = "a"
if h > 12:
h -= 12
ap = "p"
&"{h}:{parts[1]:02}{ap}"
proc tick(v: Value): string =
if v == 1: "✓" else: ""
# the columns of the trains: four digits, as `cs.matches(r"^[0-9]{4}$")`
let trains = named(it.len == 4 and it.allCharsInSet(Digits))
let center = [-4, -3, -2] # the stations of Center City
let transitTable = tabella(stopTimes):
# Create left-hand stub, top header, and hide extra cols --------
tabStub groupnameCol = "direction"
tabHeader "Saturdays, Sundays, and Major Holidays"
colsHide ["stop_url", "zone_id", "stop_desc", "stop_lat", "stop_lon", "stop_id"]
# custom functions for checkmarks and time formatting -----------
fmt trains, hMP
fmt startsWith("service_"), tick
# relabel columns and add spanners (labels over columns) --------
colsLabel:
stop_name: "Stations"
service_access: "A"
service_cash: "C"
service_park: "P"
fare_zone: html"Fare<br>Zone"
tabSpanner "Services", startsWith("service_")
tabSpanner "Train Number", trains
# move columns around and setting their width and alignment -----
colsMoveToStart "fare_zone"
colsMoveToStart startsWith("service_")
colsWidth stopTimes.columns.filterIt(it.startsWith("service_")).mapIt((it, "18px"))
colsWidth stopTimes.columns.filterIt(it.startsWith("8")).mapIt((it, "60px"))
colsAlign alCenter, "fare_zone"
colsAlign alRight, trains
# styles: striping, vertical text, background colors, fonts -----
# style header
tabStyle style.css("background-color: rgb(66, 99, 128) !important; color: white !important; font-size: 24px !important; font-weight: bold !important; border-width: 0px !important;"),
loc.header()
# style vertical text on left
tabStyle style.css("writing-mode: sideways-lr; padding-bottom: 25% !important; font-size: 24px !important; font-weight: bold !important; text-transform: uppercase !important;"),
loc.rowGroups()
tabStyle style.css("background-color: black !important; color: white !important; border-top: none !important; border-bottom: none !important;"),
loc.body(rows = center)
tabStyle style.css("""
border-top: none !important;
border-bottom: none !important;
border-right: solid white 2px !important;
color: white !important;
"""),
loc.body(cols = everything() - trains, rows = center)
tabStyle style.css("border-right: solid black 2px !important;"),
loc.body(cols = everything() - trains, rows = toSeq(0 ..< 10) & @[-1])
tabOptions(rowStripingBackgroundColor = "#A9A9A9", rowGroupAsColumn = true)
optRowStriping()
optTableOutline()
optTableFont "\"IBM Plex Sans\", " & systemFonts("neo-grotesque")
nbTable transitTable
# on a phone: the stations as the stub, which stays in view while the trains scroll
let onAPhone = transitTable.tabStub("stop_name")
.tabOptions(stubSticky = true)
nbTable onAPhone
| Saturdays, Sundays, and Major Holidays | |||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Services | Fare Zone | Stations | Train Number | ||||||||||
| A | C | P | 8210 | 8716 | 8318 | 8322 | 8338 | 8242 | 8750 | 8756 | |||
| To Center City | ✓ | 2 | Chestnut Hill West | 6:51a | 8:08a | 8:49a | 9:49a | 1:52p | 2:49p | 4:48p | 6:20p | ||
| ✓ | 2 | Highland | 6:52a | 8:09a | 8:50a | 9:50a | 1:53p | 2:50p | 4:49p | 6:21p | |||
| ✓ | 1 | St. Martins | 6:54a | 8:11a | 8:52a | 9:52a | 1:55p | 2:52p | 4:51p | 6:23p | |||
| ✓ | 1 | Richard Allen Lane | 6:56a | 8:13a | 8:54a | 9:54a | 1:57p | 2:54p | 4:53p | 6:25p | |||
| ✓ | ✓ | 1 | Carpenter | 6:58a | 8:15a | 8:56a | 9:56a | 1:59p | 2:56p | 4:55p | 6:27p | ||
| 1 | Upsal | 7:00a | 8:17a | 8:58a | 9:58a | 2:01p | 2:58p | 4:57p | 6:29p | ||||
| ✓ | ✓ | C | Tulpehocken | 7:02a | 8:19a | 9:00a | 10:00a | 2:03p | 3:00p | 4:59p | 6:31p | ||
| ✓ | ✓ | C | Chelten Avenue | 7:04a | 8:21a | 9:02a | 10:02a | 2:05p | 3:02p | 5:01p | 6:33p | ||
| ✓ | ✓ | C | Queen Lane | 7:06a | 8:23a | 9:04a | 10:04a | 2:07p | 3:04p | 5:03p | 6:35p | ||
| ✓ | C | North Philadelphia | 7:12a | 8:29a | 9:12a | 10:12a | 2:15p | 3:12p | 5:09p | 6:41p | |||
| ✓ | ✓ | 2 | Gray 30th Street | 7:23a | 8:42a | 9:23a | 10:23a | 2:26p | 3:23p | 5:20p | 6:54p | ||
| ✓ | 2 | Suburban Station | 7:28a | 8:47a | 9:28a | 10:28a | 2:31p | 3:28p | 5:25p | 6:59p | |||
| ✓ | 2 | Jefferson Station | 7:33a | 8:52a | 9:33a | 10:33a | 2:36p | 3:33p | 5:30p | 7:04p | |||
| ✓ | ✓ | 2 | Temple University | 7:37a | 8:57a | 9:37a | 10:37a | 2:40p | 3:37p | 5:35p | 7:08p | ||
| Saturdays, Sundays, and Major Holidays | |||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Services | Fare Zone | Train Number | |||||||||||
| A | C | P | 8210 | 8716 | 8318 | 8322 | 8338 | 8242 | 8750 | 8756 | |||
| To Center City | Chestnut Hill West | ✓ | 2 | 6:51a | 8:08a | 8:49a | 9:49a | 1:52p | 2:49p | 4:48p | 6:20p | ||
| Highland | ✓ | 2 | 6:52a | 8:09a | 8:50a | 9:50a | 1:53p | 2:50p | 4:49p | 6:21p | |||
| St. Martins | ✓ | 1 | 6:54a | 8:11a | 8:52a | 9:52a | 1:55p | 2:52p | 4:51p | 6:23p | |||
| Richard Allen Lane | ✓ | 1 | 6:56a | 8:13a | 8:54a | 9:54a | 1:57p | 2:54p | 4:53p | 6:25p | |||
| Carpenter | ✓ | ✓ | 1 | 6:58a | 8:15a | 8:56a | 9:56a | 1:59p | 2:56p | 4:55p | 6:27p | ||
| Upsal | 1 | 7:00a | 8:17a | 8:58a | 9:58a | 2:01p | 2:58p | 4:57p | 6:29p | ||||
| Tulpehocken | ✓ | ✓ | C | 7:02a | 8:19a | 9:00a | 10:00a | 2:03p | 3:00p | 4:59p | 6:31p | ||
| Chelten Avenue | ✓ | ✓ | C | 7:04a | 8:21a | 9:02a | 10:02a | 2:05p | 3:02p | 5:01p | 6:33p | ||
| Queen Lane | ✓ | ✓ | C | 7:06a | 8:23a | 9:04a | 10:04a | 2:07p | 3:04p | 5:03p | 6:35p | ||
| North Philadelphia | ✓ | C | 7:12a | 8:29a | 9:12a | 10:12a | 2:15p | 3:12p | 5:09p | 6:41p | |||
| Gray 30th Street | ✓ | ✓ | 2 | 7:23a | 8:42a | 9:23a | 10:23a | 2:26p | 3:23p | 5:20p | 6:54p | ||
| Suburban Station | ✓ | 2 | 7:28a | 8:47a | 9:28a | 10:28a | 2:31p | 3:28p | 5:25p | 6:59p | |||
| Jefferson Station | ✓ | 2 | 7:33a | 8:52a | 9:33a | 10:33a | 2:36p | 3:33p | 5:30p | 7:04p | |||
| Temple University | ✓ | ✓ | 2 | 7:37a | 8:57a | 9:37a | 10:37a | 2:40p | 3:37p | 5:35p | 7:08p | ||
from great_tables import GT, html, style, loc, google_font
import polars as pl
import polars.selectors as cs
def h_m_p(s):
h, m, _ = [int(part) for part in s.split(":")]
ap = "a"
if h > 12:
h -= 12
ap = "p"
return f"{h}:{m:02d}{ap}"
def tick(b):
return "✓" if b else ""
transit_table = (
GT(stop_times)
# Create left-hand stub, top header, and hide extra cols --------
.tab_stub(groupname_col="direction")
.tab_header("Saturdays, Sundays, and Major Holidays")
.cols_hide(
columns=["stop_url", "zone_id", "stop_desc", "stop_lat", "stop_lon", "stop_id"]
)
# custom functions for checkmarks and time formatting -----------
.fmt(h_m_p, columns=cs.matches(r"^[0-9]{4}$"))
.fmt(tick, columns=cs.starts_with("service_"))
# relabel columns and add spanners (labels over columns) --------
.cols_label(
stop_name="Stations",
service_access="A",
service_cash="C",
service_park="P",
fare_zone=html("Fare<br>Zone"),
)
.tab_spanner(label="Services", columns=cs.starts_with("service_"))
.tab_spanner(label="Train Number", columns=cs.matches(r"^[0-9]{4}$"))
# move columns around and setting their width and alignment -----
.cols_move_to_start("fare_zone")
.cols_move_to_start(cs.starts_with("service_"))
.cols_width(
cases={c: "18px" for c in stop_times.columns if c.startswith("service_")}
)
.cols_width(cases={c: "60px" for c in stop_times.columns if c.startswith("8")})
.cols_align(align="center", columns="fare_zone")
.cols_align(align="right", columns=cs.matches(r"^[0-9]{4}$"))
# styles: striping, vertical text, background colors, fonts -----
# style header
.tab_style(
locations=loc.header(),
style=style.css(
"background-color: rgb(66, 99, 128) !important; color: white !important; font-size: 24px !important; font-weight: bold !important; border-width: 0px !important;",
),
)
# style vertical text on left
.tab_style(
locations=loc.row_groups(),
style=style.css(
"writing-mode: sideways-lr; padding-bottom: 25% !important; font-size: 24px !important; font-weight: bold !important; text-transform: uppercase !important;"
),
)
.tab_style(
style=style.css(
"background-color: black !important; color: white !important; border-top: none !important; border-bottom: none !important;"
),
locations=loc.body(columns=None, rows=list(range(-4, -1))),
)
.tab_style(
style=style.css(
'''
border-top: none !important;
border-bottom: none !important;
border-right: solid white 2px !important;
color: white !important;
'''
),
locations=loc.body(
columns=~cs.matches(r"^[0-9]{4}$"), rows=list(range(-4, -1))
),
)
.tab_style(
style=style.css("border-right: solid black 2px !important;"),
locations=loc.body(
columns=~cs.matches(r"^[0-9]{4}$"), rows=list(range(0, 10)) + [13]
),
)
.tab_options(
row_striping_background_color="#A9A9A9",
row_group_as_column=True,
)
.opt_row_striping(row_striping=True)
.opt_table_outline()
.opt_table_font(font=google_font("IBM Plex Sans"))
)
transit_table| Saturdays, Sundays, and Major Holidays | |||||||||||||
| Services | Fare Zone |
Stations | Train Number | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| A | C | P | 8210 | 8716 | 8318 | 8322 | 8338 | 8242 | 8750 | 8756 | |||
| To Center City | ✓ | 2 | Chestnut Hill West | 6:51a | 8:08a | 8:49a | 9:49a | 1:52p | 2:49p | 4:48p | 6:20p | ||
| ✓ | 2 | Highland | 6:52a | 8:09a | 8:50a | 9:50a | 1:53p | 2:50p | 4:49p | 6:21p | |||
| ✓ | 1 | St. Martins | 6:54a | 8:11a | 8:52a | 9:52a | 1:55p | 2:52p | 4:51p | 6:23p | |||
| ✓ | 1 | Richard Allen Lane | 6:56a | 8:13a | 8:54a | 9:54a | 1:57p | 2:54p | 4:53p | 6:25p | |||
| ✓ | ✓ | 1 | Carpenter | 6:58a | 8:15a | 8:56a | 9:56a | 1:59p | 2:56p | 4:55p | 6:27p | ||
| 1 | Upsal | 7:00a | 8:17a | 8:58a | 9:58a | 2:01p | 2:58p | 4:57p | 6:29p | ||||
| ✓ | ✓ | C | Tulpehocken | 7:02a | 8:19a | 9:00a | 10:00a | 2:03p | 3:00p | 4:59p | 6:31p | ||
| ✓ | ✓ | C | Chelten Avenue | 7:04a | 8:21a | 9:02a | 10:02a | 2:05p | 3:02p | 5:01p | 6:33p | ||
| ✓ | ✓ | C | Queen Lane | 7:06a | 8:23a | 9:04a | 10:04a | 2:07p | 3:04p | 5:03p | 6:35p | ||
| ✓ | C | North Philadelphia | 7:12a | 8:29a | 9:12a | 10:12a | 2:15p | 3:12p | 5:09p | 6:41p | |||
| ✓ | ✓ | 2 | Gray 30th Street | 7:23a | 8:42a | 9:23a | 10:23a | 2:26p | 3:23p | 5:20p | 6:54p | ||
| ✓ | 2 | Suburban Station | 7:28a | 8:47a | 9:28a | 10:28a | 2:31p | 3:28p | 5:25p | 6:59p | |||
| ✓ | 2 | Jefferson Station | 7:33a | 8:52a | 9:33a | 10:33a | 2:36p | 3:33p | 5:30p | 7:04p | |||
| ✓ | ✓ | 2 | Temple University | 7:37a | 8:57a | 9:37a | 10:37a | 2:40p | 3:37p | 5:35p | 7:08p | ||
h_m_p <- function(s) {
parts <- as.integer(strsplit(s, ":")[[1]])
h <- parts[1]
ap <- "a"
if (h > 12) {
h <- h - 12
ap <- "p"
}
sprintf("%d:%02d%s", h, parts[2], ap)
}
tick <- function(b) ifelse(b == 1, "✓", "")
trains <- grep("^[0-9]{4}$", names(stop_times), value = TRUE)
transit_table <-
stop_times |>
# Create left-hand stub, top header, and hide extra cols --------
gt(groupname_col = "direction", row_group_as_column = TRUE) |>
tab_header("Saturdays, Sundays, and Major Holidays") |>
cols_hide(columns = c(stop_url, zone_id, stop_desc, stop_lat, stop_lon, stop_id)) |>
# custom functions for checkmarks and time formatting -----------
fmt(columns = matches("^[0-9]{4}$"), fns = function(x) vapply(x, h_m_p, "")) |>
fmt(columns = starts_with("service_"), fns = tick) |>
# relabel columns and add spanners (labels over columns) --------
cols_label(
stop_name = "Stations",
service_access = "A",
service_cash = "C",
service_park = "P",
fare_zone = html("Fare<br>Zone")
) |>
tab_spanner(label = "Services", columns = starts_with("service_")) |>
tab_spanner(label = "Train Number", columns = matches("^[0-9]{4}$")) |>
# move columns around and setting their width and alignment -----
cols_move_to_start(fare_zone) |>
cols_move_to_start(starts_with("service_")) |>
cols_width(starts_with("service_") ~ px(18), starts_with("8") ~ px(60)) |>
cols_align(align = "center", columns = fare_zone) |>
cols_align(align = "right", columns = matches("^[0-9]{4}$")) |>
# styles: striping, vertical text, background colors, fonts -----
tab_style(
locations = cells_title(),
style = "background-color: rgb(66, 99, 128) !important; color: white !important; font-size: 24px !important; font-weight: bold !important; border-width: 0px !important;"
) |>
tab_style(
locations = cells_row_groups(),
style = "writing-mode: sideways-lr; padding-bottom: 25% !important; font-size: 24px !important; font-weight: bold !important; text-transform: uppercase !important;"
) |>
tab_style(
style = "background-color: black !important; color: white !important; border-top: none !important; border-bottom: none !important;",
locations = cells_body(rows = 11:13)
) |>
tab_style(
style = "border-top: none !important; border-bottom: none !important; border-right: solid white 2px !important; color: white !important;",
locations = cells_body(columns = !matches("^[0-9]{4}$"), rows = 11:13)
) |>
tab_style(
style = "border-right: solid black 2px !important;",
locations = cells_body(columns = !matches("^[0-9]{4}$"), rows = c(1:10, 14))
) |>
tab_options(row.striping.background_color = "#A9A9A9") |>
opt_row_striping(row_striping = TRUE) |>
opt_table_outline() |>
opt_table_font(font = google_font("IBM Plex Sans"))
transit_table| Saturdays, Sundays, and Major Holidays | |||||||||||||
|
Services
|
Fare Zone |
Stations |
Train Number
|
||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| A | C | P | 8210 | 8716 | 8318 | 8322 | 8338 | 8242 | 8750 | 8756 | |||
| To Center City | ✓ | 2 | Chestnut Hill West | 6:51a | 8:08a | 8:49a | 9:49a | 1:52p | 2:49p | 4:48p | 6:20p | ||
| ✓ | 2 | Highland | 6:52a | 8:09a | 8:50a | 9:50a | 1:53p | 2:50p | 4:49p | 6:21p | |||
| ✓ | 1 | St. Martins | 6:54a | 8:11a | 8:52a | 9:52a | 1:55p | 2:52p | 4:51p | 6:23p | |||
| ✓ | 1 | Richard Allen Lane | 6:56a | 8:13a | 8:54a | 9:54a | 1:57p | 2:54p | 4:53p | 6:25p | |||
| ✓ | ✓ | 1 | Carpenter | 6:58a | 8:15a | 8:56a | 9:56a | 1:59p | 2:56p | 4:55p | 6:27p | ||
| 1 | Upsal | 7:00a | 8:17a | 8:58a | 9:58a | 2:01p | 2:58p | 4:57p | 6:29p | ||||
| ✓ | ✓ | C | Tulpehocken | 7:02a | 8:19a | 9:00a | 10:00a | 2:03p | 3:00p | 4:59p | 6:31p | ||
| ✓ | ✓ | C | Chelten Avenue | 7:04a | 8:21a | 9:02a | 10:02a | 2:05p | 3:02p | 5:01p | 6:33p | ||
| ✓ | ✓ | C | Queen Lane | 7:06a | 8:23a | 9:04a | 10:04a | 2:07p | 3:04p | 5:03p | 6:35p | ||
| ✓ | C | North Philadelphia | 7:12a | 8:29a | 9:12a | 10:12a | 2:15p | 3:12p | 5:09p | 6:41p | |||
| ✓ | ✓ | 2 | Gray 30th Street | 7:23a | 8:42a | 9:23a | 10:23a | 2:26p | 3:23p | 5:20p | 6:54p | ||
| ✓ | 2 | Suburban Station | 7:28a | 8:47a | 9:28a | 10:28a | 2:31p | 3:28p | 5:25p | 6:59p | |||
| ✓ | 2 | Jefferson Station | 7:33a | 8:52a | 9:33a | 10:33a | 2:36p | 3:33p | 5:30p | 7:04p | |||
| ✓ | ✓ | 2 | Temple University | 7:37a | 8:57a | 9:37a | 10:37a | 2:40p | 3:37p | 5:35p | 7:08p | ||
Other schedules in the wild
MetroTransit in Minneapolis uses a transposed format, with stops as columns and trips as rows. Here's an example from their Route 2 bus timetable (its picture is in the original post).
This is useful when there a lot of trips, because with trips on the rows readers can scroll down (versus needing to scroll sideways).
The MTA in New York City is similar. Here's an example of their bx1 bus route timetable (also pictured in the original post).
What I like about all these tables is they highlight the structure behind bus and train routes. Sometimes they skip certain stops. But realistically, what makes them a route is that trips tend to make the same stops over and over.
A common alternative to using these tables is to do routing from a set start to end point. For example, a form for selecting a start and end point on SEPTA's website gives a resulting table of departure and arrival times (pictured in the original post).
Notice that the table has removed a lot of information about intermediate stops people might not care about.
In conclusion
Transit tables are richly structured displays of information. They take advantage often of the fact that a train route like Chesnut Hill West is a fixed set of stops--so that stops can be on the rows, and arrival times for trips throughout the day can be on the columns.
This is intuitive to people reading transit timetables, but can get tricky to display on the web. Timetables are a core part of navigating transit networks, so it was a fun experiment to try replicating one of Septa's timetables in Great Tables!
import tabbook
bookInit()
nbText: "# Recreating Septa Transit Timetables in Python"
attribution gtBlog("Recreating Septa Transit Timetables in Python", "septa-timetables/",
"Michael Chow and Rich Iannone", "12 Mar 2026",
"The post's four pictures of timetables (SEPTA's, MetroTransit's, the MTA's and SEPTA's " &
"trip planner) are linked, not copied: they are pictures of the agencies' own pages. The " &
"data are read from a copy of the post's files (`book/data/great-tables/septa/`).")
nbText: """
Recently, Rich and I were poking around transit data, and we were struck by the amount of structuring that goes into transit timetables.
For example, consider this weekend rail schedule table from SEPTA, Philadelphia's transit agency ([the picture is in the original post](https://posit-dev.github.io/great-tables/blog/septa-timetables/)).
Notice these big pieces:
* The vertical text on the left indicating trains are traveling "TO CENTER CITY".
* The blue header, and spanner columns ("Services" and "Train Number") grouping related columns.
* The striped background for easier reading. Also the black background indicating stations in Center City (the urban core).
Tables like this often have to be created in tools like Illustrator, and updated by hand. At the same time, when agencies automate table creation, they often sacrifice a lot of the assistive features and helpful affordances of the table.
We set out to recreate this table in Great Tables (and by we I mean 99% Rich). In this post, I'll walk quickly through how we recreated it, and share some other examples of transit timetables in the wild. For the theory behind why tables like this are useful, see [The Design Philosophy of Great Tables](https://posit-dev.github.io/great-tables/blog/design-philosophy/).
## Reading in stops and times
For this example, I simplified SEPTA's transit data down to two pieces:
* `chw-stops.csv` - detailed information about each stop location.
* `times.csv` - when a train arrives at a stop on the Chesnut Hill West line. Each row is a stop location, and each column is a trip (e.g. the 6:51am train).
To make the final table we joined these two together, to get the trips and stop information together.
"""
tabelline """
The post opens with the finished table and shows its code twice, folded at the top and with
comments further down. Here the table comes once, at the end of “Creating the table”, after the
data it is made from.
"""
tabs """
import polars as pl
stops = pl.read_csv("../data/great-tables/septa/chw-stops.csv")
times = pl.read_csv("../data/great-tables/septa/times.csv")
""", """
library(gt)
library(dplyr)
stops <- read.csv("../data/great-tables/septa/chw-stops.csv")
times <- read.csv("../data/great-tables/septa/times.csv", check.names = FALSE)
""":
nbCode:
import std/[sequtils, streams, strutils, strformat]
import nanuq
import tabelline, tabelline/nanuq, gtdata
let stops = readCsv(newStringStream(septaStopsCsv))
let times = readCsv(newStringStream(septaTimesCsv))
nbText: """
Here's a quick preview of stops.
"""
tabs """
stops.select("stop_name", "service_access", "service_cash").head()
""", """
stops |> select(stop_name, service_access, service_cash) |> head()
""":
nbCode:
echo stops.select("stop_name", "service_access", "service_cash").head()
nbText: """
Notice that the table above has the name of each stop, and a 1 or 0 in the `service_access` column to indicate whether the stop is wheelchair accessible. Note that a big challenge for this specific route is that sometimes boarding the train requires using steps, and sometimes the station requires using steps. For example, Chelton Ave (not shown) does not require steps to board the train, but the station itself is not wheelchair accessible because of steps to get to the platform.
Here's a quick preview of the times.
"""
tabs """
times.head(3)
""", """
times |> head(3)
""":
nbCode:
echo times.head(3)
nbText: """
Notice that each trip is a column (i.e. a train leaving from Chesnut Hill West at a specific time), and each row is a stop. For example, the 8210 train is the 6:51am train. (Note that schedules and train numbers can change, so this data may be out of date).
Joining these together gives us `stop_times`, with trips and stop information on the columns.
"""
tabs """
stop_times = times.join(other=stops, on="stop_name", maintain_order="left").select(
pl.lit("To Center City").alias("direction"), pl.col("*")
)
stop_times.head(3)
""", """
stop_times <-
times |>
left_join(stops, by = "stop_name") |>
mutate(direction = "To Center City", .before = 1)
stop_times |> head(3)
""":
nbCode:
let stopTimes = times.join(stops, ["stop_name"], how = JoinType.Left)
.select(lit("To Center City").alias("direction"), col("*"))
echo stopTimes.head(3)
nbText: """
Notice that in the table above, the first row tells us when each train leaves Chesnut Hill West, and information about the Chesnut Hill West stop.
## Creating the table
Below is the code for the table, with 5 key activities marked with comments. For example, the first is creating high level structure, like the header and the left-hand "To Center City" stub. Others include formatting in checkmarks, customizing columns (e.g. their width), and styling (e.g. setting background colors and fonts).
It's a lot to take in, but worth it!:
"""
tabs """
from great_tables import GT, html, style, loc, google_font
import polars as pl
import polars.selectors as cs
def h_m_p(s):
h, m, _ = [int(part) for part in s.split(":")]
ap = "a"
if h > 12:
h -= 12
ap = "p"
return f"{h}:{m:02d}{ap}"
def tick(b):
return "✓" if b else ""
transit_table = (
GT(stop_times)
# Create left-hand stub, top header, and hide extra cols --------
.tab_stub(groupname_col="direction")
.tab_header("Saturdays, Sundays, and Major Holidays")
.cols_hide(
columns=["stop_url", "zone_id", "stop_desc", "stop_lat", "stop_lon", "stop_id"]
)
# custom functions for checkmarks and time formatting -----------
.fmt(h_m_p, columns=cs.matches(r"^[0-9]{4}$"))
.fmt(tick, columns=cs.starts_with("service_"))
# relabel columns and add spanners (labels over columns) --------
.cols_label(
stop_name="Stations",
service_access="A",
service_cash="C",
service_park="P",
fare_zone=html("Fare<br>Zone"),
)
.tab_spanner(label="Services", columns=cs.starts_with("service_"))
.tab_spanner(label="Train Number", columns=cs.matches(r"^[0-9]{4}$"))
# move columns around and setting their width and alignment -----
.cols_move_to_start("fare_zone")
.cols_move_to_start(cs.starts_with("service_"))
.cols_width(
cases={c: "18px" for c in stop_times.columns if c.startswith("service_")}
)
.cols_width(cases={c: "60px" for c in stop_times.columns if c.startswith("8")})
.cols_align(align="center", columns="fare_zone")
.cols_align(align="right", columns=cs.matches(r"^[0-9]{4}$"))
# styles: striping, vertical text, background colors, fonts -----
# style header
.tab_style(
locations=loc.header(),
style=style.css(
"background-color: rgb(66, 99, 128) !important; color: white !important; font-size: 24px !important; font-weight: bold !important; border-width: 0px !important;",
),
)
# style vertical text on left
.tab_style(
locations=loc.row_groups(),
style=style.css(
"writing-mode: sideways-lr; padding-bottom: 25% !important; font-size: 24px !important; font-weight: bold !important; text-transform: uppercase !important;"
),
)
.tab_style(
style=style.css(
"background-color: black !important; color: white !important; border-top: none !important; border-bottom: none !important;"
),
locations=loc.body(columns=None, rows=list(range(-4, -1))),
)
.tab_style(
style=style.css(
'''
border-top: none !important;
border-bottom: none !important;
border-right: solid white 2px !important;
color: white !important;
'''
),
locations=loc.body(
columns=~cs.matches(r"^[0-9]{4}$"), rows=list(range(-4, -1))
),
)
.tab_style(
style=style.css("border-right: solid black 2px !important;"),
locations=loc.body(
columns=~cs.matches(r"^[0-9]{4}$"), rows=list(range(0, 10)) + [13]
),
)
.tab_options(
row_striping_background_color="#A9A9A9",
row_group_as_column=True,
)
.opt_row_striping(row_striping=True)
.opt_table_outline()
.opt_table_font(font=google_font("IBM Plex Sans"))
)
transit_table
""", """
h_m_p <- function(s) {
parts <- as.integer(strsplit(s, ":")[[1]])
h <- parts[1]
ap <- "a"
if (h > 12) {
h <- h - 12
ap <- "p"
}
sprintf("%d:%02d%s", h, parts[2], ap)
}
tick <- function(b) ifelse(b == 1, "✓", "")
trains <- grep("^[0-9]{4}$", names(stop_times), value = TRUE)
transit_table <-
stop_times |>
# Create left-hand stub, top header, and hide extra cols --------
gt(groupname_col = "direction", row_group_as_column = TRUE) |>
tab_header("Saturdays, Sundays, and Major Holidays") |>
cols_hide(columns = c(stop_url, zone_id, stop_desc, stop_lat, stop_lon, stop_id)) |>
# custom functions for checkmarks and time formatting -----------
fmt(columns = matches("^[0-9]{4}$"), fns = function(x) vapply(x, h_m_p, "")) |>
fmt(columns = starts_with("service_"), fns = tick) |>
# relabel columns and add spanners (labels over columns) --------
cols_label(
stop_name = "Stations",
service_access = "A",
service_cash = "C",
service_park = "P",
fare_zone = html("Fare<br>Zone")
) |>
tab_spanner(label = "Services", columns = starts_with("service_")) |>
tab_spanner(label = "Train Number", columns = matches("^[0-9]{4}$")) |>
# move columns around and setting their width and alignment -----
cols_move_to_start(fare_zone) |>
cols_move_to_start(starts_with("service_")) |>
cols_width(starts_with("service_") ~ px(18), starts_with("8") ~ px(60)) |>
cols_align(align = "center", columns = fare_zone) |>
cols_align(align = "right", columns = matches("^[0-9]{4}$")) |>
# styles: striping, vertical text, background colors, fonts -----
tab_style(
locations = cells_title(),
style = "background-color: rgb(66, 99, 128) !important; color: white !important; font-size: 24px !important; font-weight: bold !important; border-width: 0px !important;"
) |>
tab_style(
locations = cells_row_groups(),
style = "writing-mode: sideways-lr; padding-bottom: 25% !important; font-size: 24px !important; font-weight: bold !important; text-transform: uppercase !important;"
) |>
tab_style(
style = "background-color: black !important; color: white !important; border-top: none !important; border-bottom: none !important;",
locations = cells_body(rows = 11:13)
) |>
tab_style(
style = "border-top: none !important; border-bottom: none !important; border-right: solid white 2px !important; color: white !important;",
locations = cells_body(columns = !matches("^[0-9]{4}$"), rows = 11:13)
) |>
tab_style(
style = "border-right: solid black 2px !important;",
locations = cells_body(columns = !matches("^[0-9]{4}$"), rows = c(1:10, 14))
) |>
tab_options(row.striping.background_color = "#A9A9A9") |>
opt_row_striping(row_striping = TRUE) |>
opt_table_outline() |>
opt_table_font(font = google_font("IBM Plex Sans"))
transit_table
""":
nbCode:
proc hMP(v: Value): string =
let parts = ($v).split(":").mapIt(parseInt(it))
var h = parts[0]
var ap = "a"
if h > 12:
h -= 12
ap = "p"
&"{h}:{parts[1]:02}{ap}"
proc tick(v: Value): string =
if v == 1: "✓" else: ""
# the columns of the trains: four digits, as `cs.matches(r"^[0-9]{4}$")`
let trains = named(it.len == 4 and it.allCharsInSet(Digits))
let center = [-4, -3, -2] # the stations of Center City
let transitTable = tabella(stopTimes):
# Create left-hand stub, top header, and hide extra cols --------
tabStub groupnameCol = "direction"
tabHeader "Saturdays, Sundays, and Major Holidays"
colsHide ["stop_url", "zone_id", "stop_desc", "stop_lat", "stop_lon", "stop_id"]
# custom functions for checkmarks and time formatting -----------
fmt trains, hMP
fmt startsWith("service_"), tick
# relabel columns and add spanners (labels over columns) --------
colsLabel:
stop_name: "Stations"
service_access: "A"
service_cash: "C"
service_park: "P"
fare_zone: html"Fare<br>Zone"
tabSpanner "Services", startsWith("service_")
tabSpanner "Train Number", trains
# move columns around and setting their width and alignment -----
colsMoveToStart "fare_zone"
colsMoveToStart startsWith("service_")
colsWidth stopTimes.columns.filterIt(it.startsWith("service_")).mapIt((it, "18px"))
colsWidth stopTimes.columns.filterIt(it.startsWith("8")).mapIt((it, "60px"))
colsAlign alCenter, "fare_zone"
colsAlign alRight, trains
# styles: striping, vertical text, background colors, fonts -----
# style header
tabStyle style.css("background-color: rgb(66, 99, 128) !important; color: white !important; font-size: 24px !important; font-weight: bold !important; border-width: 0px !important;"),
loc.header()
# style vertical text on left
tabStyle style.css("writing-mode: sideways-lr; padding-bottom: 25% !important; font-size: 24px !important; font-weight: bold !important; text-transform: uppercase !important;"),
loc.rowGroups()
tabStyle style.css("background-color: black !important; color: white !important; border-top: none !important; border-bottom: none !important;"),
loc.body(rows = center)
tabStyle style.css("""
border-top: none !important;
border-bottom: none !important;
border-right: solid white 2px !important;
color: white !important;
"""),
loc.body(cols = everything() - trains, rows = center)
tabStyle style.css("border-right: solid black 2px !important;"),
loc.body(cols = everything() - trains, rows = toSeq(0 ..< 10) & @[-1])
tabOptions(rowStripingBackgroundColor = "#A9A9A9", rowGroupAsColumn = true)
optRowStriping()
optTableOutline()
optTableFont "\"IBM Plex Sans\", " & systemFonts("neo-grotesque")
nbTable transitTable
# on a phone: the stations as the stub, which stays in view while the trains scroll
let onAPhone = transitTable.tabStub("stop_name")
.tabOptions(stubSticky = true)
nbTable onAPhone
tabelline """
`tabStub(groupnameCol = ...)` chooses the group column, as `tab_stub()`, and
`rowGroupAsColumn` puts its label in a column of its own on the left. The columns of the trains
are found by a test on their names (four digits), `named(...)`, as tabelline has no regular
expressions, and the rows of Center City are counted from the end, as in Python (`-4` to
`-2`, `-1` the last). `everything() - trains` is `~cs.matches(...)`. A block of `colsLabel`
takes plain labels and `html`/`md` ones together. The ticks are the character ✓, where the post
writes the HTML entity `✓`. The R tab writes the gt way: gt has no `tab_stub()` and takes
`row_group_as_column` in `gt()`.
On a phone the table is wider than the screen and scrolls inside its box. A timetable on a
phone wants the stations to stay in place while the trains scroll: in the second table they are the stub,
and `stubSticky = true` keeps the stub in view. Neither gt nor Great Tables has this.
"""
nbText: """
## Other schedules in the wild
MetroTransit in Minneapolis uses a transposed format, with stops as columns and trips as rows. Here's an example from their [Route 2 bus timetable](https://www.metrotransit.org/route/2) (its picture is in [the original post](https://posit-dev.github.io/great-tables/blog/septa-timetables/#other-schedules-in-the-wild)).
This is useful when there a lot of trips, because with trips on the rows readers can scroll down (versus needing to scroll sideways).
The MTA in New York City is similar. Here's an example of their [bx1 bus route timetable](https://www.mta.info/schedules/bus/bx1) (also pictured in the original post).
What I like about all these tables is they highlight the structure behind bus and train routes. Sometimes they skip certain stops. But realistically, what makes them a route is that trips tend to make the same stops over and over.
A common alternative to using these tables is to do routing from a set start to end point. For example, a form for selecting a start and end point on SEPTA's website gives a resulting table of departure and arrival times (pictured in the original post).
Notice that the table has removed a lot of information about intermediate stops people might not care about.
## In conclusion
Transit tables are richly structured displays of information.
They take advantage often of the fact that a train route like Chesnut Hill West is a fixed set of stops--so that stops can be on the rows, and arrival times for trips throughout the day can be on the columns.
This is intuitive to people reading transit timetables, but can get tricky to display on the web. Timetables are a core part of navigating transit networks, so it was a fun experiment to try replicating one of Septa's timetables in Great Tables!
"""
bookSave()
On GitHub: book/blog/septa.nim