Sub topic 12
Plotting distributions and group comparisons
Tables of numbers hide shapes. A histogram shows skew, gaps, and odd spikes that describe() flattens into a few statistics. A grouped bar chart makes a survival gap between groups visible at a glance. This chapter uses the pandas plotting API, which draws with matplotlib, to look at single columns and at groups.
It assumes you have already loaded the Titanic train.csv into df, built the AgeGroup column, and used groupby with agg. You also need pandas and matplotlib installed, and a notebook or script where plt.show() opens a figure.
Choosing a plot for the question
Pick the plot from the question and the column types, not from habit.
| Question | Column types | Plot | pandas call |
|---|---|---|---|
| How are values spread? | One numeric | Histogram | `s.plot.hist()` |
| Where are the median, spread, and outliers per group? | Numeric by category | Box plot | `df.boxplot(column=..., by=...)` |
| How does a rate or mean differ by group? | Category and an aggregate | Bar chart | `grouped.plot.bar()` |
| How many rows per category? | One category | Bar chart of counts | `s.value_counts().plot.bar()` |
Setup
Every example below uses this setup. In a plain script, plt.show() blocks until you close the window. In a notebook, figures usually appear inline.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("train.csv")
df["AgeGroup"] = pd.cut(
df["Age"],
bins=[0, 12, 18, 40, 60, 120],
labels=["child", "teen", "adult", "middle_aged", "senior"],
)Histograms: the shape of one column
A histogram cuts the value range into bins and counts how many rows fall in each.
ax = df["Age"].plot.hist(bins=30, title="Age distribution")
ax.set_xlabel("Age")
plt.show()
print("rows:", len(df), "plotted:", df["Age"].notna().sum())Two things matter here.
- Missing values are dropped silently. The histogram draws only the non-missing ages. The
printline shows the gap. Age is missing for about a fifth of passengers, so the picture describes the passengers with a recorded age, not everyone. - The bin count changes the story. With 5 bins you see one broad hump. With 30 you see the spike of infants and a bump in the twenties. With 100 you mostly see noise. Try two or three values and trust only the features that survive the change.
Fare is a different case. A few very large fares stretch the axis and squeeze most passengers into the first bar. A log scale helps.
ax = df["Fare"].plot.hist(bins=40, title="Fare distribution (log y-axis)")
ax.set_yscale("log")
ax.set_xlabel("Fare")
plt.show()The log scale is on the y-axis, so bar heights are compressed. Say so in the title or label, because a reader may take tall and short bars at face value.
Comparing a distribution across groups
To compare ages of those who survived and those who did not, draw two histograms on the same axes. Use density=True so each histogram is scaled to its own total. Otherwise the larger group dominates.
fig, ax = plt.subplots()
for label, group in df.groupby("Survived"):
group["Age"].plot.hist(
bins=range(0, 85, 5),
alpha=0.5,
density=True,
label=f"Survived={label}",
ax=ax,
)
ax.set_xlabel("Age")
ax.legend()
plt.show()Using the same bins for both groups matters. If each histogram picked its own bins, the bars would not line up and you could not compare them.
Box plots: spread per group
A box plot shows the median, the middle half of the data, and points beyond the whiskers for each group. It handles several groups in one small figure.
df.boxplot(column="Fare", by="Pclass")
plt.suptitle("")
plt.title("Fare by passenger class")
plt.ylabel("Fare")
plt.show()by= makes pandas add its own super-title, so plt.suptitle("") clears it. First-class fares have a much higher median and a long tail of high values. That tail is the reason the raw histogram looked squeezed.
Bar charts of grouped means
The groupby result from the previous chapters plots directly. A mean of a 0/1 column is a rate, so this is a survival-rate chart.
ax = df.groupby("Pclass")["Survived"].mean().plot.bar(title="Survival rate by class")
ax.set_ylabel("Survival rate")
ax.set_ylim(0, 1)
plt.show()Setting set_ylim(0, 1) is deliberate. Matplotlib may otherwise choose an axis that starts above zero, which makes small gaps look large. For a rate, the full 0 to 1 range is the honest default.
Bars hide how many rows each one rests on. Put the count on the chart.
stats = df.groupby("AgeGroup", observed=True)["Survived"].agg(["count", "mean"])
ax = stats["mean"].plot.bar(title="Survival rate by age group")
ax.set_ylim(0, 1)
ax.set_ylabel("Survival rate")
for i, n in enumerate(stats["count"]):
ax.text(i, stats["mean"].iloc[i] + 0.02, f"n={n}", ha="center")
plt.show()If a bar rests on 20 passengers, its height is far less certain than a bar resting on 400. Writing n= above each bar lets a reader see that.
Two grouping variables
To split by class and sex, unstack() moves the inner group level into columns. Pandas then draws one cluster of bars per class and one bar per sex.
rates = df.groupby(["Pclass", "Sex"])["Survived"].mean().unstack()
print(rates)
ax = rates.plot.bar(title="Survival rate by class and sex")
ax.set_ylabel("Survival rate")
ax.set_ylim(0, 1)
plt.show()The chart shows that sex separates survival within every class, so class alone does not explain the sex gap. It does not show how many passengers sit in each bar. Check that with count before you lean on a conclusion.
Common errors
- Forgetting
plt.show()in a script. Nothing appears, and there is no error. - Plotting a non-numeric column with
hist.df["Sex"].plot.hist()fails because the values are strings. Count categories first:df["Sex"].value_counts().plot.bar(). - Overlapping figures. Two plot calls without
plt.show()or a freshplt.subplots()between them can draw onto the same axes. - Comparing counts across unequal groups. Raw counts of survivors by class mostly reflect class sizes. Plot rates, or use
density=Truefor distributions. - Unlabeled axes and transformed scales. Label axes. If you used a log scale, state it.
- Reading the plot without checking missing data. A group with many missing values can look different only because of who is missing.
What plots can and cannot tell you
A histogram suggests, but does not prove, that a column has two groups mixed together. A bar chart shows a gap between groups, not the reason for it. In the Titanic data, class, sex, age, and fare are tangled with each other, so a single bar chart can credit one factor with an effect that belongs to another. Treat each chart as a lead for the next question, and write down what you saw together with its caveats. The final chapters return to this.
Exercise
You draw df.groupby("Embarked")["Survived"].mean().plot.bar() and see that one port has a rate near 0.55 while the others are near 0.34 and 0.39. What two pieces of information should you add before reporting this, and how do you get them in code?
Show answer
First, the number of passengers behind each bar, because a rate from a small group is unreliable. Use df.groupby("Embarked")["Survived"].agg(["count", "mean"]) and write n above each bar. Second, the number of rows with a missing Embarked value, which the groupby drops by default. Use df["Embarked"].isna().sum(), or df["Embarked"].value_counts(dropna=False). You could also check whether class mix differs by port, since class is tied to survival.
Exercise
Write code that draws overlapping histograms of Fare for each Pclass on one set of axes, using the same bins, density scaling, and a legend. Use a log y-axis and say why density=True helps.
Show answer
fig, ax = plt.subplots() for label, group in df.groupby("Pclass"): group["Fare"].plot.hist(bins=range(0, 520, 20), alpha=0.5, density=True, label=f"Class {label}", ax=ax) ax.setyscale("log") ax.setxlabel("Fare") ax.legend() plt.show() density=True scales each histogram to its own total, so the large third class does not hide the smaller first and second classes. Shared bins keep the bars comparable.