Density Plots
DS 2023 | Communicating with Data

Overview¶
A density plot is something like a continuous version of a histogram.
Like a histogram, it represents the distribution of a continuous variable.
But instead of using binning and counting, it estimates a probability density function using more sophisticated methods, such as kernel estimation.
A density plot may be thought of as a special case of a line graph where the x axis represents an increasing numeric value, and the y axis represents an estimate or frequency.
However, the density plot does not represent a trend. Instead, it is more like the function use case.
Like line graphs, they may also be rendered as area charts to show accumulation.
Use Cases¶
Like histograms, density plots provide a quick way to inspect the centrality and dispersion of a distribution.
They allow you to inspect the shape of a distribution for modality, skew, and kurtosis.
They can also surface outliers and mutliple populations.
Density plots are more opiniated than histograms — they posit a function behind the data.
Instead of showing counts, it shows the density of data points within a given range.
Density plots are particularly useful for larger datasets.
Creating a density plot from scratch¶
Density plots are constructed using a method called kernel density estimation (KDE).
This is why they are often called KDE plots, as in Pandas (see below).
The image below gives a good idea of how they are constructed.
For each data point, a gaussian distribution is generated.
These are the kernels.
Then, these kernels are added up to produce the resulting curve.
In practice the algorithm may be more complicated — for example the parameters of the kernels may vary — but this is the essential idea.

To show how we can create one of these, let’s use the dataset we used in our discussion of histograms, the healthexp dataset from Seaborn.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as snshealthexp = sns.load_dataset('healthexp')
healthexp = healthexp.set_index(['Year', 'Country'])
healthexp.head()Let’s specifically focus on the Life_Expectancy variable.
We pull out the series and call it le_data.
le_data = healthexp.Life_ExpectancyTo generate the curve, we will use SciPy’s gaussian_kde function.
from scipy.stats import gaussian_kdeHere we supply our data to the imported function to generate an object kde.
This object will be able to generate the curve.
kde = gaussian_kde(le_data)To generate the curve, we need to know what values our x axis will have.
That is, we need to specify what part of the domain of Life_Expectancy we want to project onto the x axis.
Here we define it in terms of the minimum and maximum values of our input data, plus a little padding — 5 years on either side.
x = np.linspace(le_data.min() - 5, le_data.max() + 5, 100)Now we can generate from , i.e. .
y = kde(x)With and in hand, we can just plot the data as a line.
plt.plot(x, y)
plt.show()
This is density plot.
Area under curve (AUC)¶
An important property of a density plot is that the area under its curve must sum up to 1.
This is because it represents all of the probability in the function.
To verify this, we can use NumPy’s trapezoid function to estimate the area.
auc = np.trapezoid(y, x).round(2)
aucnp.float64(1.0)And, indeed, it turns out to be 1.
Using Pandas KDE method¶
Now let’s have Pandas create the plot.
healthexp.Life_Expectancy.plot.kde()
plt.show()
It is basically identical to the one we created above.
This is because Pandas uses gaussian_kde under the hood.
Notice how it is a smoothed version of the histogram.
healthexp.Life_Expectancy.plot.hist()
plt.show()
How to read a density plot¶
To understand how to read a density plot, let’s compare it to the histogram.
Reading the y axis:
Whereas the y axis of a histogram is a count (aka frequency),
the y axis of a density plot is, as the name implies, a density.
What is density?
In physics, density is the amount of weight per unit of volume.
Here, it is the amount of probability per unit of area.
You can think of it as the proportion of the data at the x value.
Let’s explore this with an example.
An example¶
In our example, since Life_Expectancy is measured in years, its density is a proportion per span of years.
How would we find out the proportion of the data associated with 70 years from our plot?
First, know that the probability of any single point is 0 since it has no width and therefore no area.
So, to get area of 70, we want the area under the curve between 70 and 71, the orange area.
This will include all float values in the dataset between the two values, i.e. .
The area corresponds to the probability of a
Life_Expectancyvalue to be 70.Or: from 70 to 71.
ax = healthexp.Life_Expectancy.plot.kde()
# We use fill between with our earlier demonstration plot
ax.fill_between(x, y, 0, where=(x >= 69.9) & (x < 71), color='tab:orange')
ax.text(72, .01, "$P(recorded = 70) ≈ .02$")
ax.axvline(70, lw=.5, ls='--', c='gray')
ax.axvline(71, lw=.5, ls='--', c='gray')
ax.axhline(0, lw=.5, c='gray')
plt.show()
If we wanted to get the actual area corresponding to this span, we could compute it using np.trapezoid, as above.
age_span_x = np.linspace(70, 70.99)
age_span_y = kde(age_span_x)
round(np.trapezoid(age_span_y, age_span_x), 3)np.float64(0.016)We find that , or of the observations have an age value of 70.
So, instead of reading the height, as you would in a histogram, you read the area.
Another example¶
To reinforce this idea, consider that the curve above peaks at about 0.106 near 78.2 years.
The number 0.106 is not the proportion of observations at 78.2.
Again, a single x value has no width, and a proportion requires a width.
The area under the curve between 78 and 81 years is 0.298, so about of the observations fall in that interval.
Counted directly, of them do.
Comparing heights¶
Consider the density plots for the two measurement variables in our dataset.
healthexp.iloc[:,:2].plot.kde(subplots=True, sharey=False, sharex=False)
plt.show()
Note that y axis values (heights) cannot be compared across variables.
The curve for
Life_Expectancypeaks at about 0.106 per year.The curve for
Spending_USDpeaks at about 0.0002 per dollar.
Both describe the same 274 observations and both enclose an area of 1.
But the actual domain that is projected onto the y axis is a function of the units for the data:
Since area is function of height and width, as you increase the number of x units, the size of y must decrease if the total is to remain constant.
Comparing two density plots¶
So, to compare density plots for different variables, you want to compare shapes, not magnitudes.
The domains of the x axes and ranges of the y axes vary among variables for density plots, as explained above.
So, in the example below, we turn off sharing by the x and y axes.
healthexp.plot.kde(subplots=True, layout=(1,2), sharex=False, figsize=(12,4))
plt.show()
Adjusting the aesthetics¶
Notice that Pandas renders subplots as if each plot comes from the same domain, as would be the case this were a wide table, where each plot represents a subset of a single variable.
By convention, Pandas uses color to differentiate the plots and the legend to label them.
In this example, however, each plot represents a different variable.
Given this, you may want to change the aesthetics, so that each plot is designated by a title, not a legend, and that the colors of the two plots are the same.
healthexp.plot.kde(subplots=True, layout=(1,2), sharex=False, figsize=(12,4),
color='tab:blue', title=[col for col in healthexp.columns], legend=False)
plt.show()
Finally, using a more complex pattern, you can overlay them.
fig, ax1 = plt.subplots(figsize=(7,5))
# A bit of a hack that you have to remember
# since we are twinning both the x and y axes
ax_right = ax1.twinx()
ax2 = ax_right.twiny()
healthexp['Life_Expectancy'].plot.kde(ax=ax1, color='tab:blue', label='Life Expectancy', legend=False)
healthexp['Spending_USD'].plot.kde(ax=ax2, color='tab:orange', label='Spending USD', legend=False)
# Pandas re-enables ax2's y-axis on the left, so we hide it and use ax_right instead
ax2.yaxis.set_visible(False)
# Align the colors of the ticks and spines for readability
ax1.tick_params(axis='x', colors='tab:blue')
ax1.tick_params(axis='y', colors='tab:blue')
ax2.tick_params(axis='x', colors='tab:orange')
ax_right.tick_params(axis='y', colors='tab:orange')
# Combine the legends from both independent spaces
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')
plt.show()
Normalizing units¶
One problem with the plot comparisons above is that, because the heights of the two curves are made to be equal, the difference between a flattened and a peaked curve is lost.
To truly compare the two curves, it is necessary to normalize their units by projecting both onto a common scale.
You can do this with SciKit Learn’s minmax_scale function.
from sklearn.preprocessing import minmax_scale
cols = ['Life_Expectancy', 'Spending_USD']
scaled = healthexp[cols].apply(minmax_scale)
scaled.head()ax = scaled.plot.kde(figsize=(7, 5), title="Comparison with normalized units")
The advantage with this comparison is that we can see the shapes, but we lose the units.
One solution would by to populate the upper and right spines with the actual units.
Showing multiple groups¶
If we want to show how the density plots of countries differ, we first create a wide table that projects the domain of country onto axis 1.
In this table, each column represents a subset of the variable country.
life_exp_wide = healthexp.Life_Expectancy.unstack()
life_exp_wide.head()Now we can plot it and Pandas will treat each column as a plot line.
life_exp_wide.plot.kde()
plt.show()
You can color in the area under each curve by iterating through each line and applying the fill_between method.
ax = life_exp_wide.plot.kde()
# Iterate through the individual lines
for line in ax.lines:
ax.fill_between(line.get_xdata(), line.get_ydata(), alpha=0.4)
plt.show()
You also show them as subplots.
life_exp_wide.plot.kde(subplots=True, figsize=(15, 10), layout=(3,3), sharey=True,
title=list(life_exp_wide.columns), legend=False, color='tab:blue')
plt.suptitle("Life Expectancy by Country")
plt.show()
Interpreting the results¶
Looking at the life expectancy variable condition by country, what we can learn from these plots?
In particular, what does the height and shape of the plot for USA tell us?
Using Seaborn¶
Seaborn’s version of density plots has a simple argument to achieve the same effect.
sns.kdeplot(life_exp_wide, fill=True)
plt.show()
Seaborn’s version also allows you to by-pass having to pivot the tidy table.
Instead of first setting the columns to Country in the pivot function, you can just set the hue (i.e. color) to Country.
sns.kdeplot(healthexp, x='Life_Expectancy', hue='Country', fill=True)
plt.show()
Combining histograms and density plots¶
Sometimes we want to hedge our bets and show both histograms and density plots at the same time.
One way to do this is to set density = True on the histogram and then plot both an the same axes object.
healthexp.Life_Expectancy.plot.hist(density=True, alpha=.75)
healthexp.Life_Expectancy.plot.kde(lw=2)
plt.show()
Another pattern is to use ax.twinx(), as we did in our lesson on Line Graphs.
This preserves the y axis domains of both plots.
ax1 = healthexp.Life_Expectancy.plot.hist(alpha=.75)
ax2 = ax1.twinx()
healthexp.Life_Expectancy.plot.kde(ax=ax2, color='tab:orange', lw=2)
plt.show()
Note, however, the misalignment of the two axes.
Even though they represent different domains, they should align at 0.
To align the two axes, we use ylim to force the y axis of the second plot to be use 0 as its bottom value.
ax1 = healthexp.Life_Expectancy.plot.hist(alpha=.75)
ax2 = ax1.twinx()
healthexp.Life_Expectancy.plot.kde(ax=ax2, color='tab:orange', lw=2, ylim=(0, None))
plt.show()
Choosing a bandwidth¶
If a density plot is a smoothed histogram, the obvious question is how much smoothing to apply.
This is analogous to choosing the number of bins in a histogram.
This is governed by the bandwidth, which sets the width of each of the gaussian kernels.
A narrow bandwidth makes each kernel a thin spike, and the resulting curve follows the data closely.
A wide bandwidth makes each kernel a broad hill, and the curve flattens toward a single smooth mound.
Pandas exposes this parameter as the bw_method argument, which it hands off to SciPy.
Below we draw the same variable three times, over a histogram of the same data for reference.
bandwidths = {
"Narrow": .15,
"Scott's rule": .33,
"Wide": .5
}fig, axes = plt.subplots(1, 3, figsize=(15, 4), sharex=True, sharey=True)
for i, bw in enumerate(bandwidths):
# PLot the histogram
healthexp.Life_Expectancy.plot.hist(ax=axes[i], bins=25, density=True, alpha=.4, color='tab:gray')
# Plot the KDE
healthexp.Life_Expectancy.plot.kde(ax=axes[i], bw_method=bandwidths[bw], color='tab:blue', lw=2)
# Name things
axes[i].set_title(bw)
axes[i].set_xlabel('Life Expectancy')
plt.suptitle('The same data under three bandwidths')
plt.tight_layout()
plt.show()
The left panel describes two populations.
The right panel describes one broad population.
Notice also that the wide curve assigns density below 70 and above 85, although no country in the dataset falls outside the range 70.6 to 84.7.
That is a general property of the method, and the subject of our last section.
When density plots mislead¶
The smoothness of a density plot is itself a claim about the world.
It asserts that the underlying variable is continuous.
When that assertion is false, the density plot misleads in ways that the histogram does not.
Small samples¶
With few observations, the curve is mostly bandwidth and very little data.
If density plots are useful for larger datasets, the converse is also true: they are not useful for small ones.
Given a dozen points, each kernel becomes a visible bump, and a reader will take those bumps for modes.
A histogram is the better choice at that size; it shows the reader how little data there is.
Discrete and categorical data¶
A density plot of a die roll, a star rating, or a count of children per household draws a smooth curve through values that cannot occur.
The curve will do impossible things like assign density to 2.4 children.
Bounded variables¶
Kernel density estimation knows nothing about the actual domain of a variable.
Even though a test score out of 100, a proportion, an age, a duration have hard boundaries, the kernels placed near those boundaries spill across them.
This is called boundary bias, and it costs you twice:
density is assigned to impossible values
and the density at the boundary itself is underestimated.
To see how much boundary bias affects the example above, consider that we might have applied SciPy’s gaussian_kde function directly to our dataset.
healthexp['le_kde'] = kde(healthexp['Life_Expectancy'].values)Then we can compare these data to the plot normally produced.
This produces a plot where the tails of the curve are removed.
# An area plot of the KDE values assigned to each observation
ax = healthexp.sort_values('Life_Expectancy').plot.area(
x='Life_Expectancy', y='le_kde', alpha=.5,
ylim=(0, None),
title="KDE of Life Expectancy",
figsize=(8,4),
legend=False
)
# The default KDE plot
healthexp['Life_Expectancy'].plot.kde(ax=ax)
plt.show()
Although we will not measure it here, you can see that a significant amount of probability mass is devoted to unseen data.
This is because KDE is a model of the data.
It predicts that if more samples were taken, some of them would fall instead the tails.