如何在同一画布重叠绘制两个emmeans对象的估计边际均值图
问题背景
现有两个emmeans输出表如下:
emm_1 $emmeans Order rate SE df asymp.LCL asymp.UCL 1 19.3 1.51 Inf 16.5 22.5 2 26.0 2.33 Inf 21.8 31.0 emm_2 $emmeans Order rate SE df asymp.LCL asymp.UCL 1 25.6 1.62 Inf 22.6 28.9 2 18.8 2.34 Inf 14.8 24.0
最初尝试的绘图代码如下,运行后仅显示第二张emmeans的图:
plot(emm_1,col="steelblue4") + theme_bw() + labs(title = "Choice1", x = "Estimated marginal mean", y = "Order") + theme(plot.title = element_text(hjust = 0.5)) + scale_x_continuous(breaks = seq(0, 33,5), limits =c(0,33)) par(new=TRUE) plot(emm_2,col="green") + theme_bw() + labs(title = "Choice2", x = "Estimated marginal mean", y = "Order") + theme(plot.title = element_text(hjust = 0.5)) + scale_x_continuous(breaks = seq(0, 33,5), limits =c(0,33))
问题原因与解决方法
问题原因
par(new=TRUE)是R基础绘图系统的参数,对你当前使用的ggplot2绘图系统完全无效,每次运行ggplot的+语法生成的绘图对象,只有最后打印的那个会显示在画布上,之前的会被直接覆盖。
实现方案
该需求完全可以实现,有两种常见实现方式,按需选择:
方案1:两组数据放在同一坐标轴内绘制
先把两个emmeans结果提取出来,添加分组标识后合并,再统一绘图,最终两组结果会展示在同一个坐标系下,用颜色区分组别:
# 加载需要的包 library(emmeans) library(ggplot2) library(dplyr) # 提取emmeans数据并添加分组标识 emm1_df <- as.data.frame(emm_1$emmeans) %>% mutate(group = "Choice1") emm2_df <- as.data.frame(emm_2$emmeans) %>% mutate(group = "Choice2") all_emm <- bind_rows(emm1_df, emm2_df) all_emm$Order <- factor(all_emm$Order) # 将Order转成因子方便绘图 # 统一绘图 ggplot(all_emm, aes(x = rate, y = Order, color = group)) + geom_point(position = position_dodge(width = 0.3), size = 2) + geom_errorbarh(aes(xmin = asymp.LCL, xmax = asymp.UCL), height = 0.2, position = position_dodge(width = 0.3)) + theme_bw() + labs(title = "两组估计边际均值对比", x = "Estimated marginal mean", y = "Order", color = "组别") + theme(plot.title = element_text(hjust = 0.5)) + scale_x_continuous(breaks = seq(0, 33,5), limits =c(0,33)) + scale_color_manual(values = c("Choice1" = "steelblue4", "Choice2" = "green"))
方案2:分面展示两组结果
如果希望保留两个独立的子图,排布在同一画布中,可以用patchwork包拼接两个ggplot对象:
# 加载patchwork包 library(patchwork) # 分别生成两个绘图对象 p1 <- plot(emm_1,col="steelblue4") + theme_bw() + labs(title = "Choice1", x = "Estimated marginal mean", y = "Order") + theme(plot.title = element_text(hjust = 0.5)) + scale_x_continuous(breaks = seq(0, 33,5), limits =c(0,33)) p2 <- plot(emm_2,col="green") + theme_bw() + labs(title = "Choice2", x = "Estimated marginal mean", y = "Order") + theme(plot.title = element_text(hjust = 0.5)) + scale_x_continuous(breaks = seq(0, 33,5), limits =c(0,33)) # 横向拼接两个图(如果要纵向拼就换成p1/p2) p1 + p2
内容的提问来源于stack exchange,提问作者Camila Jones
相关产品推荐
相关产品推荐

