The Problem
Real data moment
Real NYC TLC trip data, resampled to a daily average trip distance — the first real plot of this course:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_parquet("yellow_tripdata_2025-01.parquet")
clean = df[df["trip_distance"].between(0, 100)].set_index("tpep_pickup_datetime")
daily = clean["trip_distance"].resample("D").mean()
daily is ready. How it gets drawn matters more than it looks like it should.
The gotcha
Here's the other way — the plt.plot() shortcut most tutorials open with, applied to two supposedly separate plots:
plt.plot(daily.index[:10], daily.values[:10])
plt.title("Attempt 1")
print(len(plt.gca().lines))
plt.plot(daily.index[:10], daily.values[:10] * 2) # forgot plt.figure() first
print(len(plt.gca().lines))
print(len(plt.get_fignums()))
1
2
1
Two plt.plot() calls, one real figure — the second call drew onto the same axes as the first, not a new one. plt.plot() doesn't create a figure each time; it draws on whichever figure pyplot currently considers "active," and without an explicit new plt.figure() call, that's still the first one. Both lines are now silently layered on top of each other in "Attempt 1."
This is invisible until there's more than one plot in the same script
A single plot never reveals this — there's only ever one figure to be "current." The bug only appears the moment a script produces two or more plots, and by then the first plot may already have been saved, screenshotted, or shown, with the second plot's data quietly drawn into it.
Now the same two-plot situation, done correctly:
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].plot(daily.index[:10], daily.values[:10])
axes[0].set_title("Daily average (raw)")
axes[1].plot(daily.index[:10], daily.values[:10] * 2)
axes[1].set_title("Scaled x2 (comparison)")
print(len(axes[0].lines), len(axes[1].lines))
1 1
One line on each axes, correctly separated — because axes[0].plot(...) and axes[1].plot(...) name exactly which axes each call targets, with no "currently active" ambiguity involved at all.
A script calls plt.plot(x1, y1), then later plt.xlabel("time"), then plt.plot(x2, y2), then plt.title("Result"), intending two separate plots. What actually happens?
Without an explicit plt.figure() call between them, every one of these pyplot calls targets the same currently-active figure — there was never a second figure created at all. The result is one figure holding two overlapping lines, one xlabel, and one title, not the two separate, individually-labeled plots the code visually appears to be building.