# 怎么用R語言ggplot2散點圖并添加擬合曲線和置信區間
## 前言
在數據可視化中,散點圖是展示兩個連續變量關系的經典工具。而添加擬合曲線和置信區間能更直觀地揭示變量間的潛在趨勢和不確定性范圍。R語言的`ggplot2`包以其優雅的語法和強大的定制能力,成為實現這一目標的理想工具。本文將詳細介紹如何使用`ggplot2`創建散點圖,并添加線性/非線性擬合曲線及置信區間。
---
## 準備工作
### 1. 安裝并加載必要的包
```r
# 如果未安裝ggplot2,先執行安裝
install.packages("ggplot2")
# 加載包
library(ggplot2)
使用R內置數據集mtcars
作為演示數據:
data(mtcars)
head(mtcars)
該數據集包含32輛汽車的11個性能指標,我們將以wt
(車重)為X軸,mpg
(每加侖英里數)為Y軸。
ggplot(data, aes(x = x_var, y = y_var)) +
geom_point()
p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point(size = 3, alpha = 0.7, color = "steelblue") +
labs(title = "汽車重量與油耗關系",
x = "重量(噸)",
y = "每加侖英里數(mpg)") +
theme_minimal()
print(p)
使用geom_smooth()
函數,默認method = “loess”(局部加權回歸),需指定method = “lm”:
p + geom_smooth(method = "lm",
formula = y ~ x,
color = "red",
se = TRUE) # se控制是否顯示置信區間
method
: 擬合方法(”lm”, “glm”, “loess”等)formula
: 擬合公式(y ~ x為線性)se
: 是否顯示置信區間(默認為TRUE)level
: 置信水平(默認0.95)二次多項式擬合示例:
p + geom_smooth(method = "lm",
formula = y ~ poly(x, 2),
color = "darkgreen")
適用于非線性關系:
p + geom_smooth(method = "loess",
span = 0.8, # 控制平滑度
color = "purple")
p + geom_smooth(method = "lm",
fill = "lightblue", # 填充色
alpha = 0.2, # 透明度
linetype = "dashed") # 邊界線類型
當數據包含分組變量時(如cyl
氣缸數):
ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) +
geom_point() +
geom_smooth(method = "lm", se = FALSE) + # 不顯示置信區間
facet_wrap(~cyl) +
scale_color_brewer(palette = "Set1")
先計算模型結果,再用geom_line()
添加:
model <- lm(mpg ~ wt, data = mtcars)
mtcars$pred <- predict(model)
ggplot(mtcars, aes(wt, mpg)) +
geom_point() +
geom_line(aes(y = pred), color = "red", size = 1)
使用ggpubr
包快速添加:
library(ggpubr)
p + stat_regline_equation(label.y = 35) + # 方程位置
stat_cor(label.y = 32) # R2位置
只顯示上/下半部分置信帶:
p + geom_smooth(method = "lm",
aes(ymin = ..ymin.., ymax = ..y..),
stat = "smooth")
library(ggplot2)
# 完整繪圖
final_plot <- ggplot(mtcars, aes(wt, mpg)) +
geom_point(aes(color = factor(cyl)), size = 3) +
geom_smooth(method = "lm", formula = y ~ poly(x, 2),
color = "black", fill = "gray80") +
scale_color_manual(values = c("#E69F00", "#56B4E9", "#009E73")) +
labs(title = "汽車重量與油耗關系(按氣缸數分組)",
subtitle = "二次多項式擬合曲線",
x = "重量(噸)",
y = "每加侖英里數(mpg)",
color = "氣缸數") +
theme_bw() +
theme(legend.position = "top")
# 保存圖形
ggsave("scatter_with_CI.png", final_plot, width = 8, height = 6)
通過ggplot2
的geom_smooth()
函數,我們可以輕松實現各種擬合曲線和置信區間的添加。關鍵要點包括:
1. 選擇適當的擬合方法(線性/非線性)
2. 合理調整置信區間樣式增強可讀性
3. 利用分組和分面展示多維關系
4. 通過輔助包增強圖形信息量
掌握這些技巧后,您將能創建更具洞察力的數據可視化作品。 “`
注:實際使用時需替換示例圖片鏈接為真實生成的圖形。本文代碼已在R 4.2.0 + ggplot2 3.4.0環境下測試通過。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。