如何使用ggplot2绘制比较两个变量分布的QQ图(非理论分布对比)
qqplot()) Got it, so you want to generate a quantile-quantile plot that compares the distributions of two actual variables (not one variable against a theoretical distribution) using ggplot2—specifically replicating qqplot(iris$Petal.Length, iris$Petal.Width) from base R. Let’s walk through two straightforward approaches.
Approach 1: Manual calculation (no extra packages needed)
ggplot2 doesn’t have a built-in function for this exact use case, but we can easily compute the quantiles ourselves and plot them. Here’s how:
- Calculate matching quantiles for both variables (we’ll use 100 quantile points for smoothness, but you can adjust this number).
- Turn the quantiles into a tidy data frame.
- Plot the points and add a reference line (to compare how closely the distributions align).
library(tidyverse) # Step 1: Calculate quantiles for both variables num_quantiles <- 100 length_quantiles <- quantile(iris$Petal.Length, seq(0, 1, length.out = num_quantiles)) width_quantiles <- quantile(iris$Petal.Width, seq(0, 1, length.out = num_quantiles)) # Step 2: Create a tidy data frame qq_df <- tibble( `Petal.Length Quantiles` = length_quantiles, `Petal.Width Quantiles` = width_quantiles ) # Step 3: Build the QQ plot ggplot(qq_df, aes(x = `Petal.Length Quantiles`, y = `Petal.Width Quantiles`)) + geom_point(size = 1.5, alpha = 0.7) + # Add semi-transparent points geom_abline(slope = 1, intercept = 0, color = "#e74c3c", linetype = "dashed") + # Reference line labs( title = "QQ Plot: Petal Length vs Petal Width", x = "Quantiles of Petal Length", y = "Quantiles of Petal Width" ) + theme_minimal()
The dashed red line represents where points would lie if the two distributions were identical. Deviations from this line show differences in spread or shape between the two variables.
Approach 2: Use the qqplotr package (simpler, purpose-built)
If you want a more streamlined solution, the qqplotr package extends ggplot2 to support two-variable QQ plots directly. It handles the quantile calculations behind the scenes:
First, install the package if you haven’t already:
install.packages("qqplotr")
Then use stat_qq_point() and stat_qq_line() to create the plot:
library(qqplotr) ggplot(iris, aes(sample = Petal.Width)) + stat_qq_point(aes(quantiles = Petal.Length), size = 1.5, alpha = 0.7) + stat_qq_line(aes(quantiles = Petal.Length), color = "#e74c3c", linetype = "dashed") + labs( title = "QQ Plot: Petal Length vs Petal Width (using qqplotr)", x = "Quantiles of Petal Length", y = "Quantiles of Petal Width" ) + theme_minimal()
This will produce a nearly identical plot to the manual method, but with less code to write.
Both approaches give you the same core functionality as base R’s qqplot()—they just let you leverage ggplot2’s customization features (like themes, point styling, and labels) for a more polished final figure.
内容的提问来源于stack exchange,提问作者Vincenzo

