Sub topic 6
Histograms, Box Plots and Density Plots
This chapter covers the three chart types that show how values in a column are spread out: histograms, box plots and density plots. It assumes you can build a DataFrame, select columns, and call df.plot with kind or the df.plot.<kind> accessors from earlier chapters. Matplotlib must be installed. Density plots also need SciPy.
Why distribution charts differ from the others
Line and bar charts use the index as the x axis and draw one mark per row. Distribution charts work differently. They ignore the index and look only at the values in each numeric column. The x axis (or y axis, for box plots) shows the value range, and the chart summarizes how many rows fall where.
| Chart | `kind` | Accessor | Shows | Extra requirement |
|---|---|---|---|---|
| Histogram | `"hist"` | `df.plot.hist` | Counts of values per bin | None |
| Box plot | `"box"` | `df.plot.box` | Median, quartiles, outliers | None |
| Density plot | `"kde"` or `"density"` | `df.plot.kde` | Smoothed estimate of the distribution | SciPy |
Histograms
A histogram splits the range of values into equal-width intervals called bins. It then counts how many values fall into each bin and draws a bar of that height. The example below builds two columns of random scores and overlays their histograms.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
rng = np.random.default_rng(0)
scores = pd.DataFrame({
"math": rng.normal(70, 10, 500),
"art": rng.normal(65, 15, 500),
})
scores.plot.hist(bins=20, alpha=0.5)
plt.show()By default, a histogram of a DataFrame draws all numeric columns on the same axes. Two arguments make that readable:
binssets the number of bins. The default is 10. Too few bins hide the shape, and too many make the chart noisy. You can also pass a list of bin edges, such asbins=[0, 50, 60, 70, 80, 100], for uneven intervals.alphasets transparency from 0 (invisible) to 1 (solid). Without it, the column drawn last covers the others.
Other useful arguments:
stacked=Truestacks the columns instead of overlaying them.orientation="horizontal"draws horizontal bars.density=Truerescales the bar heights so the total area is 1. Use it when the columns have different row counts and you want to compare shapes, not counts.cumulative=Truedraws a running total of the counts.by="column"splits one column into a histogram per group.
Choosing the number of bins
The bin count changes how the data looks. With 500 values, 5 bins produce a blocky outline and 100 bins produce gaps and spikes. Try several values before you decide. A common starting point is the square root of the row count, which is about 22 for 500 rows.
fig, axes = plt.subplots(1, 3, figsize=(10, 3), sharey=True)
for ax, n in zip(axes, [5, 20, 100]):
scores["math"].plot.hist(bins=n, ax=ax, title=f"bins={n}")
plt.tight_layout()
plt.show()The ax argument tells pandas which matplotlib Axes to draw on. Later chapters cover it in detail.
Histograms of a single column
A Series has the same plot.hist method. With one column there is nothing to overlay, so you rarely need alpha.
scores["math"].plot.hist(bins=20, edgecolor="white", title="Math scores")
plt.show()The edgecolor argument draws a thin outline around each bar, which makes the bin boundaries easy to see.
Box plots
A box plot summarizes a column in five numbers plus outliers. Each box covers the middle half of the data. The line inside the box marks the median.
- The bottom of the box is the first quartile (Q1). A quarter of the values are below it.
- The line inside the box is the median, the middle value.
- The top of the box is the third quartile (Q3). A quarter of the values are above it.
- The whiskers extend from the box to the most extreme values within 1.5 times the interquartile range (IQR = Q3 − Q1) of the box edges.
- Points beyond the whiskers are drawn individually as outliers.
scores.plot.box()
plt.show()Each numeric column gets its own box on a shared value axis. This makes box plots a compact way to compare many columns, because you can read the center, spread and outliers of each at once.
Grouped box plots
To compare a column across categories, use the by argument. pandas draws one box per group.
data = pd.DataFrame({
"group": rng.choice(["A", "B", "C"], 300),
"value": rng.normal(50, 12, 300),
})
data.plot.box(column="value", by="group")
plt.show()You can also use vert=False to draw the boxes horizontally, which helps when column names are long.
Box plots versus histograms
A box plot hides the shape of the distribution. Two columns with a very different shape, such as one hump versus two humps, can produce the same box. Use a histogram when shape matters and a box plot when you need to compare many columns or spot outliers quickly.
Density plots
A density plot draws a smooth curve instead of bars. It uses kernel density estimation (KDE), which places a small bell-shaped curve on every data point and adds them up. The result approximates the underlying distribution without depending on bin edges.
scores.plot.kde()
plt.show()The call scores.plot(kind="density") is identical. If SciPy is missing, pandas raises an ImportError when you call this method. Install it with pip install scipy.
The bandwidth
The bw_method argument controls how smooth the curve is. A small value follows the data closely and can show spurious bumps. A large value smooths the curve and can hide real structure.
ax = scores["math"].plot.kde(bw_method=0.2, label="bw=0.2")
scores["math"].plot.kde(bw_method=0.8, label="bw=0.8", ax=ax)
ax.legend()
plt.show()Edge effects
A KDE curve extends past the smallest and largest values, because each bell curve has tails. For data that cannot be negative, such as prices or ages, the curve can show density below zero, where no data exists. When that matters, use a histogram or set xlim to cut the axis at the real limit.
Combining a histogram with a density curve
You can draw both on one chart to see the bars and the smoothed shape together. Use density=True on the histogram so both use the same vertical scale.
ax = scores["math"].plot.hist(bins=20, density=True, alpha=0.5)
scores["math"].plot.kde(ax=ax)
ax.set_xlabel("Math score")
plt.show()Without density=True, the histogram bars show counts, which can be in the hundreds, while the KDE curve has values near 0.04. The curve would then look flat along the bottom of the chart.
Common problems
- No numeric data. If the DataFrame has only text columns, pandas raises
TypeError: no numeric data to plot. Select numeric columns first, or usedf.select_dtypes("number"). - Missing values. pandas drops
NaNvalues from each column before drawing distribution charts, so columns can have different counts. This is usually what you want, but checkdf.isna().sum()if the shape looks off. - Overlapping histograms. Forgetting
alphamakes the front histogram hide the one behind it. - Different scales. Columns measured in very different units, such as dollars and years, are drawn on one axis. The smaller one becomes a thin spike. Plot such columns separately with
subplots=True. - Index columns are ignored. If you wanted the index on the axis, you want a line or bar chart. Distribution charts never use it.
Putting it together
The next example draws all three charts for the same column in one figure, so you can compare what each one shows.
fig, axes = plt.subplots(1, 3, figsize=(11, 3))
scores["art"].plot.hist(bins=20, ax=axes[0], title="Histogram")
scores["art"].plot.box(ax=axes[1], title="Box plot")
scores["art"].plot.kde(ax=axes[2], title="Density")
plt.tight_layout()
plt.show()All three charts show the same data. The histogram shows counts per bin. The box plot shows the median, quartiles and outliers. The density plot shows the smoothed curve.
Exercise
You have a DataFrame df with columns height and weight, and you want to compare the two distributions on one chart. Calling df.plot.hist() shows only one clear histogram, because the other is hidden behind it. Which argument fixes this, and how would you compare the same two columns using a plot that does not hide anything?
Show answer
Pass alpha, for example df.plot.hist(alpha=0.5, bins=20), so overlapping bars are semi-transparent. Alternatively, df.plot.hist(stacked=True) stacks them. A box plot, df.plot.box(), draws each column in its own box and never overlaps. If height and weight have very different scales, use subplots=True so each gets its own panel.
Exercise
Why can a density plot of a column of ages show a curve below age 0, and what are two ways to avoid misleading the reader?
Show answer
A KDE places a bell curve on each data point, and each curve has tails that extend past the data range, so the sum is nonzero below the minimum value. Two fixes are to switch to a histogram, which only draws bars where data exists, or to restrict the axis with xlim=(0, None), as in df["age"].plot.kde(xlim=(0, None)).