Sub topic 12
Plotting Distributions and Group Comparisons
This chapter assumes you can load the Titanic CSV into a DataFrame called df, and that you have already built the AgeGroup column and run groupby summaries. You also need matplotlib installed. Tables tell you the numbers. Plots show the shape of the data, such as skew, gaps, and outliers, that summary statistics can hide.
The pandas plotting API
Every Series and DataFrame has a .plot accessor. It draws with matplotlib, so you can use matplotlib functions such as plt.xlabel and plt.show to adjust the result. Two plot types cover most first-pass work:
- A histogram (
.plot.hist) shows how one numeric column is distributed. - A bar chart (
.plot.bar) compares one number across groups.
Plotting a distribution
A histogram splits the values into bins and counts how many fall in each. The bins argument sets how many bins there are.
import matplotlib.pyplot as plt
df["Age"].plot.hist(bins=30, title="Age distribution")
plt.xlabel("Age")
plt.show()
df.groupby("Pclass")["Survived"].mean().plot.bar(title="Survival rate by class")
plt.ylabel("Survival rate")
plt.show()The first chart uses only passengers with a known Age. pandas drops missing values before it draws, so the histogram does not show the missing ones. Check the missing count you found earlier before you trust the shape.
Try different bins values, such as 10, 30, and 60. Too few bins hide detail. Too many make the chart noisy. If the picture changes a lot between settings, treat any pattern you see as weak.
Plotting a group comparison
The second chart works in two steps. groupby("Pclass")["Survived"].mean() produces a Series indexed by class. Calling .plot.bar() on that Series draws one bar per index value. This is the general pattern: aggregate first, then plot the aggregated result.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Nothing appears in a script | `plt.show()` is missing | Call `plt.show()` after each plot |
| Two charts drawn on top of each other | Plots share one figure | Call `plt.show()` between them, or use `plt.figure()` |
| `TypeError: no numeric data to plot` | The column is text, or it has a non-numeric dtype | Check `df.dtypes` and convert the column |
| Histogram looks different from `describe()` | Missing values were dropped silently | Compare `df["Age"].count()` with `len(df)` |
| Bars appear in an odd order | Index is sorted alphabetically or by value | Use `.sort_index()` or `.sort_values()` before plotting |
Reading the charts
For the age histogram, look for where most passengers sit, whether the distribution is symmetric or skewed, and whether there is a separate bump (for example, young children). For the class chart, compare bar heights, then ask what else differs between classes, such as sex ratio or age. A chart suggests a question. It does not answer why.
Exercise
You draw df.groupby("AgeGroup", observed=True)["Survived"].mean().plot.bar() and the "senior" bar is the lowest. What should you check before reporting that seniors survived least?
Show answer
Check how many passengers are in the senior group, for example with agg(["count", "mean"]). A small group makes the rate unstable. Also remember that rows with a missing Age are excluded from every AgeGroup, so the chart covers only passengers with a known age. Other factors such as class or sex could also explain the difference.
Exercise
Write code that draws a histogram of Fare with 40 bins and a title, then labels the x-axis. Why might the chart look heavily skewed?
Show answer
df["Fare"].plot.hist(bins=40, title="Fare distribution"); plt.xlabel("Fare"); plt.show(). Most passengers paid low fares and a few paid very high ones, so the distribution has a long right tail that pushes most of the data into the first few bins.