Lesson 41 · Pandas Full Course
Line, Bar, Histogram and Box Plots in Pandas: Pick the Right Chart | Pandas Course #41
In this lesson you'll be able to: Draw line plots of trends, with several lines and a moving average Compare groups with sorted, grouped and stacked bar…
- CoursePandas Full Course
- Lesson41 of 65
- FormatJupyter notebook · 41 code cells
- Data2 datasets
What you'll learn
Datasets used in this lesson
Save these next to the notebook. In Google Colab, upload them with the 📁 icon on the left first.
- tips.csv preview9.5 KB
- flights.csv preview2.3 KB
📓 Full notebook
Download .ipynbPandas 41: Creating Line, Bar, Histogram, and Box Plots#
In this lesson you'll be able to:
- Draw line plots of trends, with several lines and a moving average
- Compare groups with sorted, grouped and stacked bar charts
- Read the shape of data with histograms and choose good bins
- Compare spreads and spot outliers with box plots
- Pick the right chart and combine all four in one figure Data: airline passengers 1949-1960 and restaurant tips
Warm-up: one-line charts#
Lesson 40 used .plot(kind=...) on the tips data. Same data, same tool.
import pandas as pd
import matplotlib.pyplot as plt
tips = pd.read_csv("data/pandas/tips.csv")
tips["pct"] = tips["tip"] / tips["total_bill"] * 100
print(tips.groupby("time")["pct"].median().round(1))
tips["pct"].plot(kind="hist", bins=20, title="Tip as % of bill",
xlabel="Tip (%)")
plt.show()
Line plots: change over time#
Problem: see a trend and a seasonal pattern in a time series.
flights = pd.read_csv("data/pandas/flights.csv")
print(flights.shape)
flights.head(3)
Common mistake: the wrong month code when building dates
text = flights["year"].astype(str) + "-" + flights["month"]
pd.to_datetime(text, format="%Y-%b")
flights["date"] = pd.to_datetime(text, format="%Y-%B")
air = flights.set_index("date")["passengers"]
print(air.head(3))
ax = air.plot(figsize=(9, 4), title="Monthly airline passengers")
ax.set_xlabel("Month")
ax.set_ylabel("Passengers (thousands)")
plt.show()
print(air.iloc[0], air.iloc[-1])
Quick check: which month is the busiest in most years?
peak = flights.loc[flights.groupby("year")["passengers"].idxmax()]
peak["month"].value_counts()
wide = flights.pivot(index="month", columns="year",
values="passengers")
months = flights['month'].unique()
wide = wide.reindex(months)
wide[[1949, 1955, 1960]].head(3)
ax = wide[[1949, 1955, 1960]].plot(marker="o", figsize=(9, 4),
title="Seasonal pattern")
ax.set_xlabel("Month")
ax.set_ylabel("Passengers (thousands)")
plt.show()
ax = air.plot(label="Monthly", alpha=0.5, figsize=(9, 4))
trend = air.rolling(12).mean()
trend.plot(ax=ax, label="12-month average", linewidth=2)
ax.set_title("Passengers with a 12-month average")
ax.set_ylabel("Passengers (thousands)")
ax.legend()
plt.show()
print(trend.dropna().iloc[[0, -1]].round(1))
air.plot(logy=True, figsize=(9, 4), title="Passengers, log scale",
ylabel="Passengers (log scale)", xlabel="Month")
plt.show()
yoy = air.pct_change(12) * 100
ax = yoy.plot(figsize=(9, 4), title="Growth on the same month a "
"year before")
ax.set_ylabel("Growth (%)")
plt.show()
print(yoy.loc["1950"].mean().round(1), yoy.loc["1960"].mean().round(1))
Your turn#
Plot only the summer months, June to August, as three lines over the years.
summer = wide.loc[["June", "July", "August"]].T
ax = summer.plot(marker="o", title="Summer months over the years")
ax.set_ylabel("Passengers (thousands)")
plt.show()
print(summer.loc[1960])
Bar plots: compare categories#
Problem: compare totals or averages across groups.
order = ["Thur", "Fri", "Sat", "Sun"]
tips["day"] = pd.Categorical(tips["day"], categories=order,
ordered=True)
bills = tips["day"].value_counts(sort=False)
print(bills)
ax = bills.plot(kind="bar", rot=0, color="steelblue",
title="Bills per day")
ax.set_xlabel("Day")
ax.set_ylabel("Bills")
plt.show()
Common mistake: averaging a table that has text columns
tips.groupby("day", observed=True).mean()
cols = ["total_bill", "tip"]
avg = tips.groupby("day", observed=True)[cols].mean()
ax = avg.plot(kind="bar", rot=0, title="Average bill and tip")
ax.set_ylabel("Dollars")
plt.show()
print(avg.round(2))
yearly = flights.groupby("year")["passengers"].sum()
ax = yearly.sort_values().plot(kind="barh", color="darkorange",
title="Passengers per year")
ax.set_xlabel("Passengers (thousands)")
plt.show()
print(yearly.iloc[[0, -1]])
ax = bills.plot(kind="bar", rot=0, color="slategray",
title="Bills per day", ylabel="Bills")
ax.bar_label(ax.containers[0])
plt.show()
print(bills.sum())
mix = pd.crosstab(tips["day"], tips["smoker"], normalize="index")
ax = mix.plot(kind="bar", stacked=True, rot=0,
title="Smokers share by day")
ax.set_ylabel("Share of bills")
plt.show()
print(mix.round(2))
Your turn#
Bar chart: average total bill for each party size.
by_size = tips.groupby("size")["total_bill"].mean()
ax = by_size.plot(kind="bar", rot=0, title="Average bill by party")
ax.set_xlabel("Party size")
ax.set_ylabel("Average bill ($)")
plt.show()
print(by_size.round(2))
Histograms: the shape of a distribution#
Problem: see where values cluster, and how far they stretch.
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
tips["total_bill"].plot(kind="hist", bins=5, ax=axes[0],
title="5 bins", xlabel="Bill ($)")
tips["total_bill"].plot(kind="hist", bins=40, ax=axes[1],
title="40 bins", xlabel="Bill ($)")
plt.tight_layout()
plt.show()
Quick check: is the bill histogram symmetric, or does it lean?
print(tips["total_bill"].mean().round(2))
print(tips["total_bill"].median())
print(tips["total_bill"].skew().round(2))
ax = tips.loc[tips["time"] == "Lunch", "total_bill"].plot(
kind="hist", bins=20, alpha=0.5, density=True, label="Lunch")
tips.loc[tips["time"] == "Dinner", "total_bill"].plot(
kind="hist", bins=20, alpha=0.5, density=True, label="Dinner",
ax=ax)
ax.set_title("Bills: lunch vs dinner")
ax.set_xlabel("Bill ($)")
ax.legend()
plt.show()
print(tips.groupby("time")["total_bill"].median())
ax = tips["total_bill"].plot(kind="hist", bins=50, cumulative=True,
density=True, histtype="step",
title="Share of bills up to each value")
ax.set_xlabel("Bill ($)")
ax.set_ylabel("Share of bills")
plt.show()
print((tips["total_bill"] <= 20).mean().round(2))
Your turn#
Histogram of tip %, with a dashed line at the median.
med = tips["pct"].median()
ax = tips["pct"].plot(kind="hist", bins=30, title="Tip %")
ax.axvline(med, color="red", linestyle="--", label="Median")
ax.set_xlabel("Tip (% of bill)")
ax.legend()
plt.show()
print(round(med, 1))
Box plots: spreads and outliers#
Problem: compare whole distributions across groups at once.
axes = tips.plot.box(column="total_bill", by="day",
figsize=(8, 4), ylabel="Bill ($)")
plt.show()
print(tips.groupby("day", observed=True)["total_bill"].median())
q1, q3 = tips["total_bill"].quantile([0.25, 0.75])
limit = q3 + 1.5 * (q3 - q1)
outliers = tips[tips["total_bill"] > limit]
print(round(limit, 2), len(outliers))
Quick check: which month has the widest spread across the years?
ax = wide.T.plot(kind="box", figsize=(10, 4), rot=45,
title="Passengers by month, 1949-1960")
ax.set_ylabel("Passengers (thousands)")
plt.show()
spread = wide.max(axis=1) - wide.min(axis=1)
print(spread.idxmax(), spread.max())
Common mistake: a box plot of a text column
tips["time"].plot(kind="box")
axes = tips.plot.box(column="tip", by="time", figsize=(7, 4),
ylabel="Tip ($)")
plt.show()
print(tips.groupby("time")["tip"].median())
Your turn#
Box plot of tip % by party size. Which size tips the highest share?
axes = tips.plot.box(column="pct", by="size", figsize=(8, 4),
ylabel="Tip (% of bill)")
plt.show()
print(tips.groupby("size")["pct"].median().round(1))
Choose and combine the four#
Problem: match each question to a chart, then build one figure.
- Change over time? line | Compare groups? bar
- Shape of one column? histogram | Spread across groups? box
Common mistake: indexing a 2 by 2 grid with one number
fig, axs = plt.subplots(2, 2, figsize=(10, 7))
tips["total_bill"].plot(kind="hist", ax=axs[2])
fig, axs = plt.subplots(2, 2, figsize=(10, 7))
air.plot(ax=axs[0, 0], title="Line: passengers over time")
yearly.plot(kind="bar", ax=axs[0, 1], title="Bar: per year")
tips["total_bill"].plot(kind="hist", bins=20, ax=axs[1, 0],
title="Histogram: bills")
tips.plot.box(column="tip", by="time", ax=axs[1, 1])
axs[1, 1].set_title("Box: tip by time")
fig.tight_layout()
plt.show()
import os
os.makedirs("output/pandas", exist_ok=True)
fig.savefig("output/pandas/l41_four_charts.png", dpi=100)
img = plt.imread("output/pandas/l41_four_charts.png")
print(img.ndim, img.shape[2])
Mini-project: how did air travel grow, 1949-1960?#
Plan: growth with bars, the summer peak with lines, the seasonal swing with boxes.
growth = yearly.iloc[-1] / yearly.iloc[0]
print(round(growth, 2))
change = yearly.pct_change() * 100
print(change.round(1).describe()[['min', 'mean', 'max']])
ax = change.plot(kind="bar", rot=45, color="seagreen",
title="Growth on the year before (%)")
ax.set_ylabel("Growth (%)")
plt.show()
print(change.idxmin(), change.min().round(1))
stats = flights.groupby("year")["passengers"].agg(["min", "max"])
stats["swing"] = stats["max"] - stats["min"]
stats["ratio"] = (stats["max"] / stats["min"]).round(2)
stats.iloc[[0, 5, -1]]
ax = stats[["swing"]].plot(marker="o", legend=False,
title="Gap between peak and low month")
ax.set_ylabel("Passengers (thousands)")
plt.show()
first, last = stats["ratio"].iloc[0], stats["ratio"].iloc[-1]
july = (peak["month"] == "July").sum()
print(f"Traffic grew {growth:.1f}x; July peaked in "
f"{july} of 12 years; "
f"peak/low ratio {first} -> {last}.")
Recap#
- Line: trends over time; add a rolling mean or log scale
- Bar: compare groups; sort, group or stack the bars
- Histogram: the shape of one column; bins change the story
- Box: spreads and outliers across groups, with column= and by=
- Grids use axs[row, col]; save the figure with savefig
Challenges#
- Line plot of December passengers across the years.
- Grouped bars of average tip by day, split by smoker.
- Box plot of tip % by day. Which day has the widest spread?
What's next#
Lesson 42: Integrating Pandas with Matplotlib and Seaborn Take full control of figures, and make statistical charts with seaborn.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



