QQ Plots
DS 2023 | Communicating with Data

Overview¶
In the same way that a histogram is a special case of a bar chart, a Q-Q plot is a special case of a scatter plot.
It plots two numeric statistical features on the x and y axes, usually the quantiles of two probability distributions, and .
Hence the name “Q–Q” — short for quantile–quantile.
Q-Q plots also typically add a diagonal line plot to the figure as a reference, where .
If the sample follows the model, the points will fall along the line.
Systematic departures reveal how the two distributions differ.
and are often a model and sample, respectively, but sometimes they are two samples.
Use Cases¶
Like histograms, Q-Q plots allow the user to quickly see the statistical properties of a distribution, such as skew, tails, and outliers.
However, Q-Q plots are optimized to show how a distribution differs from a model, such as the normal distribution.
Q-Q plots can also be used to compare two samples to see if they come from the same population.
In either case, the more similar and are, the more their points will align with the identity line, i.e. the line produced by the function .
Creating a Q-Q plot from scratch¶
The essential part of creating a Q-Q plot is preparing the data, then displaying them with a scatter plot and a reference line.
When comparing a variables’s distribution against a theoretical model, the general data preparation steps are:
Rank the variable data.
Choose a numeric measurement variable, aka the sample, and sort its values in ascending order.
Assign each value a rank , starting at 1 for the smallest value and ending at for the largest.
These sorted values are the sample quantiles, .
Scale the rank values.
For each rank, apply the formula to get the cumulative probability.
where is the rank of the data point and is the total number of observations.
This effectively scales the data to values between and .
The result is an evenly spaced set probabilities.
The values tell you the percentile is associated with the variable value.
Convert the scaled ranks into theoretical quantiles.
Choose a theoretical distribution.
This is the model you want to compare your sample data against.
This is often the standard normal distribution.
Pass each to the model’s inverse cumulative distribution function (CDF).
This is the quantile function.
For the standard normal distribution this is (
norm.ppf), which maps the evenly spaced probabilities to values that are bunched near the center and spread out in the tails.The results are the theoretical quantiles, .
Plot the resulting data.
Draw a scatter plot of (the model) on the x-axis and (the sample) on the y-axis.
Overlay a reference line:
If you standardized the sample first, , use .
Otherwise use , or a line through the first and third quartiles of the points.
Points close to the line indicate a good fit; curves, S-shapes, or bent tails reveal how the sample’s distribution departs from the model.
Only the straightness matters for judging shape: if the data are normal with mean and standard deviation , the points fall near the line , so the mean and spread change only the line’s intercept and slope.
Here is an example using NumPy, Pandas, and Matplotlib.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as snsWe start by taking a random sample of 1000 observations from the normal distribution.
my_sample = np.random.normal(0, 1, 1000)
my_sample[:5]array([-1.73614512, 1.8042887 , -2.4052307 , 0.28086249, 0.19519043])We then create a data frame to store the features for our Q-Q plot.
QQ = pd.DataFrame(my_sample, columns=['q2'])
QQ['rank'] = QQ.q2.rank(method='first').astype(int)
QQ.sort_values('rank')Next, we scale the rank using the Hazen’s formula.
The result is an evenly space series of probabilities.
QQ['p'] = (QQ['rank'] - .5) / len(QQ)
QQ.head()Note that p tells you the percent of observations below it.
(len(QQ[QQ.p <= .5765]) / len(QQ)) * 10057.699999999999996Finally, we map the scaled rank onto values from the model.
Here, we convert the scaled rank p into quantile values from our model distribution q1.
To do this, we use an inverse cumuluative density function (CDF).
We can use SciPy’s scipy.stats.norm() function to perform the conversion.
import scipy.stats as stats
QQ['q1'] = stats.norm.ppf(QQ['p'])
QQ.head()Now, we just create a scatter plot with a reference line.
ax = QQ.plot.scatter('q1', 'q2') # theoretical on x, sample on y
lims = [QQ.q1.min(), QQ.q1.max()]
ax.plot(lims, lims, ls='--', c='red')
ax.set_xlabel("Theoretical quantiles (Q1)")
ax.set_ylabel("Sample quantiles (Q2)")
ax.set_title("Q-Q Plot from Scratch")
plt.show()
Using SciPy and Statsmdodels¶
Python’s two main statistical libraries, SciPy and Statsmodels, each have functions that will produce a Q-Q plot in Matplotlib for you.
Here is SciPy’s .stats.probplot() function.
Here we see it with the plot argument set, which automatically produces a plot for us.
# stats.probplot?stats.probplot(QQ.q2, dist="norm", plot=plt)
plt.show()
And here is the Statsmodels version, which by default produces a plot.
import statsmodels.api as sm
sm.qqplot(QQ.q2, line ='45')
plt.show()
In both cases, the resulting plot is a Matplotlib object that can be further manipulated using PyPlot (plt).
Using Pingouin¶
One issue with the two Q-Q plot functions described above is that neither returns a Matplotlib Axes object.
This means that it is hard to combine them with other plots and otherwise amend them.
Pingouin, another statistical package in the Python world, does return an Axes object.
It also presents a well annotated plot.
import pingouin as pgax = pg.qqplot(QQ.q2, dist='norm', color='tab:blue')
Using Seaborn¶
Seaborn supports Q-Q plots with the pplot function, which comes with the seaborn-qqplot extension.
It’s pretty bare bones, though, so you have to include the diagonal and anything else by hand.
from seaborn_qqplot import pplot
pplot(QQ, x="q1", y="q2", kind='qq', height=5, display_kws={"identity":True})
# plt.plot([-3,3], [-3,3], c='red', ls='--', lw=2) # Or do this to control color, etc.
plt.show()
What is nice about pplot is that it is very general, exposing both the x and y axes to any series of data.
So, for example, we can easily compare the distributions of two measurement variables like so:
penguins = sns.load_dataset('penguins')
pplot(penguins, x='bill_length_mm', y='bill_depth_mm', kind='qq', hue='species', height=5)
plt.show()
Comparison to histograms and density plots¶
Let’s look at an example to illustrate how Q-Q plots compare to histograms and density plots for investigating the properties of a distribution.
We use the same data set we used when looking at histograms.
healthexp = sns.load_dataset('healthexp')
healthexp.head()fig, ax = plt.subplots(2, 1, figsize=(4, 8))
S = healthexp.Life_Expectancy
S.plot.hist(density=True, alpha=.75, ax=ax[0])
S.plot.kde(ax=ax[0])
pg.qqplot(S, dist='norm', square=False, color='tab:blue', ax=ax[1])
plt.suptitle("Histogram and KDE Plots vs QQ Plot")
plt.show()
Looking at the Q-Q plot, we can see two things right away.
First, there is a good overall fit through the center of the distribution.
Roughly the middle two-thirds, between theoretical quantiles of about and +1.5.
This means that a normal model describes the bulk of this data well.
It is reasonably symmetric with no strong skew, and the central shape is essentially Gaussian.
Second, the curves at either end of the plot reveal something about the tails of the distribution.
The points lie above the line on the left and below it on the right.
This indicates that the most extreme observed values are less extreme than a normal distribution would predict.
Statisticians would say the distribution has short, light tails.
In both cases, the Q-Q plot is more informative than the other two.
It immediately directs your attention these facts.
In contrast, a histogram’s look is sensitive to the number of bins selected.
And the KDE’s is sensitive to bandwidth, which can smooth away or even invent features.
Visually, the two on the left spend almost all their visual space (data ink) on the dense center.
They squash the sparse tails into near-zero slivers
This make deviations from normality are almost impossible to see.
So, while the histogram and KDE are better for conveying overall shape, modality, and the actual data scale to a general audience, the Q-Q plot is the better diagnostic for judging how and where the distribution departs from a chosen model — especially in the tails, which is exactly where it matters most.
A final example¶
In our final example, we use the tips dataset to show how a sample can diverge from the model.
First, let’s define a simple function to plot four panels showing a histogram and density plot above the QQ plot for a given series.
def myqq(S, title=None):
fig, ax = plt.subplots(1, 2, figsize=(10, 5))
S.plot.hist(density=True, alpha=.75, ax=ax[0])
S.plot.kde(ax=ax[0])
pg.qqplot(S, dist='norm', square=False, ax=ax[1])
plt.suptitle(title)
plt.tight_layout()
plt.show()tips = sns.load_dataset('tips')myqq(tips.tip)
Overall, we can see that the plot is right-skewed. It’s normal in the middle, squeezed as the bottom and stretched at the top.
The left tail: is squeezed, flattening above the line at about -1.45.
This is because the minimum tip acts as a floor.
The right tail: is stretched, bending up and away.
This is because the largest tips sit 3 to 5 standard deviations above the mean ( max).
Here is a similar pattern:
myqq(tips.total_bill)
You can see that the plot does not work well with discrete values from a small domain.
myqq(tips['size'])
tips['size'].value_counts()size
2 156
3 38
4 37
5 5
1 4
6 4
Name: count, dtype: int64Summary¶
| Pattern | Meaning |
|---|---|
| Points on the line | Shape matches the model |
| Both ends bend up (a convex curve) | Right skew |
| Both ends bend down (a concave curve) | Left skew |
| Ends flare away from the line (an S shape) | Heavy tails |
| Ends pull in toward the line | Light tails |
| Horizontal steps | Discrete values (many ties) |
np.random.seed(42)
size = 10000
distributions = {
# Sharp peak at 0 with a long tail stretching to the right
"right_skew": np.random.exponential(scale=2.0, size=size),
# Mirrored right skew shifted forward to tail to the left
"left_skew": -1 * np.random.exponential(scale=2.0, size=size) + 20,
# Standard t-distribution with low df (3) has fat tails and heavy outliers
"heavy_tails": np.random.standard_t(df=3.0, size=size),
# Uniform distribution has zero tail behavior (all values bounded between 0 and 1)
"light_tails": np.random.uniform(low=0.0, high=1.0, size=size)
}for dist in distributions:
print(dist)
S = pd.Series(distributions[dist])
myqq(S, title=dist)
# plt.title(dist)right_skew

left_skew

heavy_tails

light_tails
