Sub topic 6
Histograms, Box Plots and Density Plots
This chapter assumes you can build a DataFrame, select numeric columns, and call df.plot with a kind argument. Matplotlib must be installed. Distribution charts show how values spread out, instead of how they change over time or differ by category.
What a distribution chart shows
A line or bar chart plots one value per row. A distribution chart takes a whole column and summarizes its shape: where values cluster, how wide they spread, and whether outliers exist. Each numeric column becomes one distribution, so the index does not become the x axis.
| Chart | `kind` | Best for |
|---|---|---|
| Histogram | `"hist"` | Counting how many values fall into each bin |
| Box plot | `"box"` | Comparing median, spread and outliers across columns |
| Density plot | `"kde"` or `"density"` | A smooth curve of the shape |
Histograms
A histogram splits the value range into bins and counts the values in each one. The bins argument sets the number of bins. When a DataFrame has several columns, the bars overlap, so lower alpha (transparency) to see both.
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()The art column is wider because its standard deviation is larger. Two options are often useful. stacked=True stacks the bars instead of overlaying them. orientation="horizontal" turns the chart on its side.
Box plots
A box plot draws one box per column. The box spans the first to third quartile, and the line inside it marks the median. The whiskers reach to the most extreme values within 1.5 times the interquartile range. Points beyond the whiskers are drawn individually as outliers.
scores.plot.box()
plt.show()Box plots are compact, so they suit comparing many columns. They hide the shape, though. A column with two peaks can look the same as one with a single peak.
Density plots
A density plot, or kernel density estimate (KDE), draws a smooth curve instead of bars. It needs SciPy installed. Without it, pandas raises an ImportError.
scores.plot.kde()
plt.show()The curve is smoothed, so it can extend past the real minimum and maximum of the data. Use bw_method to control smoothing. A smaller number follows the data more closely.
scores.plot.density(bw_method=0.3)
plt.show()Choosing between them
Common problems
- Overlapping bars hide each other. Set
alphabelow 1, or plot one column at a time. - The shape changes with
bins. Try several values before drawing conclusions. Too few bins hide detail, and too many look noisy. - Missing values.
NaNvalues are dropped silently, so the counts can be lower than the row count. - Non-numeric columns. Text columns are skipped. If none are numeric, pandas raises
TypeError: no numeric data to plot.
Exercise
Exercise
You have a DataFrame scores with columns math and art. Write one line that draws overlapping histograms with 30 bins where both are visible. Then name the package kde needs besides pandas and matplotlib.
Show answer
scores.plot.hist(bins=30, alpha=0.5) makes the bars semi-transparent so they can be seen through each other. The kde kind requires SciPy.
Exercise
A box plot shows two columns with the same median and the same box size. Why might a histogram still show a difference between them?
Show answer
A box plot reduces each column to a few summary numbers. A histogram shows the full shape, so it can reveal that one column has two peaks while the other has one.