如何在R中绘制同面板双回归曲线(含标准误,无需转置数据)
R实现同一面板绘制多组weight回归曲线并添加标准误
步骤说明
我们可以借助ggplot2和dplyr包实现需求,无需转置原始长格式数据,通过数据筛选与配对合并构建绘图数据集,再完成可视化。
完整代码
# 加载所需包 library(ggplot2) library(dplyr) # 原始数据集 df <- tibble::tibble( cultivar = rep(c("cv1", "cv2", "cv3"), each = 5L), treatment = rep(c("Control", "Type 1", "Type 2", "Type 3", "Type 4"), 3), weight = c(10.6475, 25.355, 34.455, 40.355, 49.4225, 11.33571, 26.47, 31.04, 34.59167, 49.00857, 14.03, 32.5, 19.73, 47.705, 56.74), std_err = c( 1.111796, 1.232541, 3.174625, 2.887711, 1.478566, 1.244666, 2.491744, 4.798628, 5.259148, 4.009993, 0.62, 0.6, 1.34, 0.015, 2.32 ) ) # 提取cv1的基准数据,用于后续配对 cv1_base <- df %>% filter(cultivar == "cv1") %>% select(treatment, weight_cv1 = weight, se_cv1 = std_err) # 构建cv1与cv2的配对数据集 cv1_cv2_df <- df %>% filter(cultivar == "cv2") %>% left_join(cv1_base, by = "treatment") %>% mutate(comparison_group = "cv1 vs cv2") # 构建cv1与cv3的配对数据集 cv1_cv3_df <- df %>% filter(cultivar == "cv3") %>% left_join(cv1_base, by = "treatment") %>% mutate(comparison_group = "cv1 vs cv3") # 合并两个配对数据集 plot_data <- bind_rows(cv1_cv2_df, cv1_cv3_df) # 绘制图形 ggplot(plot_data, aes(x = weight_cv1, y = weight, color = comparison_group)) + # 绘制数据点 geom_point(size = 3) + # 添加y轴方向的标准误误差棒(对应对比品种) geom_errorbar(aes(ymin = weight - std_err, ymax = weight + std_err), width = 0.5) + # 添加x轴方向的标准误误差棒(对应cv1) geom_errorbarh(aes(xmin = weight_cv1 - se_cv1, xmax = weight_cv1 + se_cv1), height = 0.5) + # 绘制线性回归曲线及置信区间 geom_smooth(method = "lm", se = TRUE, alpha = 0.2) + # 设置坐标轴与图例标签 labs(x = "cv1 重量", y = "对比品种重量", color = "对比组") + # 使用简洁主题 theme_minimal()
代码解释
- 数据预处理:通过
filter提取cv1的基准数据,再分别与cv2、cv3的数据按treatment字段配对,添加分组标识后合并,全程未转置原始数据。 - 绘图元素说明:
geom_point绘制每个treatment对应的配对数据点;geom_errorbar和geom_errorbarh分别添加y轴(对比品种)和x轴(cv1)的标准误误差棒;geom_smooth(method = "lm")自动拟合线性回归曲线,并显示95%置信区间。
内容的提问来源于stack exchange,提问作者J.K Kim
相关产品推荐
相关产品推荐

