如何在ggplot中合并两组带置信区间的分组散点误差棒图
合并两组Bootstrap结果的ggplot图表
要把两组Bootstrap结果的图表合并,最简洁的方式是先将两个数据框合并并添加分组标识,再通过ggplot的分组或分面功能实现。以下是具体实现步骤:
步骤1:合并数据框
给d1和d2分别添加一个用于区分数据集的列(比如dataset),然后合并成一个数据框:
# 添加分组标识 d1$dataset <- "d1" d2$dataset <- "d2" # 合并数据 combined_data <- rbind(d1, d2)
步骤2:绘制合并后的图表
方式1:同一面板内区分两组数据(错位显示)
通过position_dodge让同一pqual下的两组数据错开显示,同时用颜色区分数据集:
ggplot(data = combined_data, aes(x = pqual, y = V1, color = dataset, group = dataset)) + geom_point(position = position_dodge(width = 0.3), size = 3) + geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.2, position = position_dodge(width = 0.3)) + scale_y_continuous(limits = c(0.5, 2), breaks = c(0.5, 1, 1.5, 2)) + scale_colour_manual(values = c("d1" = "aquamarine3", "d2" = "darkgoldenrod3"), labels = c("Dataset 1", "Dataset 2")) + theme_grey(base_size = 22) + labs(title = "Q10 Bootstrap Results", x = "pqual", y = "Q10", color = "Dataset")
方式2:分面显示(独立栏位)
如果希望两组数据保持独立但在同一图表中,用facet_wrap实现横向/纵向分栏:
ggplot(data = combined_data, aes(x = pqual, y = V1, color = pqual)) + geom_point(size = 3) + geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.2) + scale_y_continuous(limits = c(0.5, 2), breaks = c(0.5, 1, 1.5, 2)) + scale_colour_manual(values = c("scst" = "aquamarine3", "svar" = "aquamarine4", "ycst" = "darkgoldenrod3", "yvar" = "darkgoldenrod4")) + theme_grey(base_size = 22) + labs(title = "Q10 Bootstrap Results", x = "pqual", y = "Q10") + facet_wrap(~dataset) # 横向分栏,若需纵向可改用facet_grid(dataset~.)
原始数据与参考代码
你的原始数据和绘图代码如下:
# 原始数据 d1 <- structure(list(pqual = c("scst", "svar", "ycst", "yvar"), V1 = c(1.57018534500418, 0.813141641335401, 1.83263172676745, 1.08637937362865), lower = c(1.46430733516951, 0.754261886214852, 1.83263172676745, 1.04296652726617), median = c(1.56519136055835, 0.813147324264586, 1.83263172676745, 1.08589629982024), upper = c(1.684225201556, 0.875420698794502, 1.83263172676745, 1.12960240657212)), class = "data.frame", row.names = c("bootscstd", "bootsvard", "bootycstd", "bootyvard")) d2 <- structure(list(pqual = c("scst", "svar", "ycst", "yvar"), V1 = c(1.52392776239251, 0.795105955855431, 1.7049070356902, 0.866155843608828), lower = c(1.42095510456812, 0.740169509961879, 1.67591486183307, 0.831244001139425), median = c(1.52198888072917, 0.794298998427312, 1.70461432040644, 0.864517118120389), upper = c(1.63130199180125, 0.85303654089534, 1.73294982674048, 0.908100088043788)), class = "data.frame", row.names = c("bootscst", "bootsvar", "bootycst", "bootyvar")) # 原始绘图代码 Q10dplot <- ggplot(data=Q10d, aes(x=pqual, y=V1, col=pqual))+ geom_point()+ geom_errorbar(aes(ymin=lower, ymax=upper), width=.2)+ scale_y_continuous(limits=c(0.5,2), breaks = c(0.5,1,1.5,2))+ scale_colour_manual(values=c("scst" = "aquamarine3", "svar" = "aquamarine4", "ycst" = "darkgoldenrod3", "yvar" = "darkgoldenrod4"))+ theme_minimal()+ ggtitle("Q10 d")+ xlab("pqual") + ylab("Q10")+ theme_grey(base_size = 22) Q10dplot
内容的提问来源于stack exchange,提问作者Nate Trf
相关产品推荐
相关产品推荐

