# 怎么用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) # R²位置
只显示上/下半部分置信带:
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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。