Creating Q-Q Plots: Tools in Python and R
You'll learn: How to generate Q-Q plots using Python's statsmodels and scipy libraries, and R's base graphics to diagnose residual normality after fitting regression models.
Why Q-Q Plots Matter for Regression Diagnostics
Once you've fit a linear model and extracted residuals, you need to check if they follow a normal distribution—one of the key assumptions. Q-Q plots (which you've already learned to interpret) are the visual tool for this job. Now it's time to actually create them using standard software tools.
Creating Q-Q Plots in Python
Using statsmodels: After fitting a regression model with statsmodels, use the built-in diagnostic plot:
import statsmodels.api as sm
# Assume 'model' is your fitted OLS model
sm.qqplot(model.resid, line='s')
The line='s' parameter adds the 45-degree reference line (standardized theoretical quantiles).
Using scipy: For more manual control, scipy offers a direct function:
from scipy import stats
import matplotlib.pyplot as plt
stats.probplot(model.resid, dist="norm", plot=plt)
plt.show()
This compares your residuals against a normal distribution and plots the reference line.
Creating Q-Q Plots in R
R's base graphics make this remarkably simple:
# Assume 'model' is your fitted lm() model
qqnorm(residuals(model))
qqline(residuals(model))
qqnorm() creates the plot, and qqline() adds the theoretical normal line for comparison.
When to Use Which Tool
All three approaches produce essentially the same diagnostic plot. Choose based on your workflow: statsmodels integrates seamlessly with regression objects, scipy offers flexibility, and R's base functions are concise and standard.
Key Takeaway: Generate Q-Q plots using sm.qqplot() or stats.probplot() in Python, or qqnorm() + qqline() in R—these built-in tools quickly visualize whether your residuals approximate normality.