ggplot中X轴列名相同时如何仅在单个X值添加数据点?
问题描述
本人完全不懂编程,若表述有误还请见谅。我正在使用R语言通过ggplot绘图,现有数据集的图表已绘制完成,想要手动添加误差棒,但数据集不符合需求,打算先添加均值数据点再基于该点制作误差棒。但由于X轴值相同,数据点被添加到了每个分面列中。附上代码:
ggplot(well_data4, aes(x = E2F4, y = Colonies, color = Clone, fill = E2F4)) + geom_point(aes(color = Clone), size = 2) + geom_point(aes(x=("-/-"), y=2837.3333, color = "black")) + labs(title = "HT29 Colony Survival", x = "Concentration of SN-38 (nM)", y = "Number of colonies") + scale_color_manual(values = c('11' = "darkturquoise", "7" = "darkturquoise", "2" = "darkturquoise","Control"= "darkorchid")) + scale_fill_discrete(labels = c("-/- = E2F4 Knockout", "+/+ = E2F4 Wild Type")) + guides(color = guide_legend(override.aes = list(size=3)), fill = guide_legend(override.aes =list(size=2))) + facet_wrap(~Well, nrow = 1, strip.position = "bottom") + theme_minimal() + theme(strip.placement = "outside", panel.spacing = unit(0, "cm"), strip.text = element_text(size = 10, margin = margin(b=15)), legend.title = element_text(size = 10), plot.title = element_text(margin = margin(b=10)))
我曾尝试添加该行代码:geom_point(aes(x=("-/-"), y=2837.3333, color = "black")),还试图指定仅在"0"对应的分面列添加,但操作始终无效,恳请帮忙解决!
解决方案
问题出在你用了facet_wrap(~Well)做分面,默认情况下geom_point会在所有分面里重复绘制这个手动点。要让它只出现在指定的Well(比如Well=0)分面中,需要给这个手动点指定对应的Well值,同时把颜色参数移出映射范围:
关键修改点
替换原来的手动点代码为:
geom_point(data = data.frame(Well = "0", E2F4 = "-/-", Colonies = 2837.3333), aes(x = E2F4, y = Colonies), color = "black", size = 2)
完整代码
ggplot(well_data4, aes(x = E2F4, y = Colonies, color = Clone, fill = E2F4)) + geom_point(aes(color = Clone), size = 2) + # 指定分面的手动均值点 geom_point(data = data.frame(Well = "0", E2F4 = "-/-", Colonies = 2837.3333), aes(x = E2F4, y = Colonies), color = "black", size = 2) + labs(title = "HT29 Colony Survival", x = "Concentration of SN-38 (nM)", y = "Number of colonies") + scale_color_manual(values = c('11' = "darkturquoise", "7" = "darkturquoise", "2" = "darkturquoise","Control"= "darkorchid")) + scale_fill_discrete(labels = c("-/- = E2F4 Knockout", "+/+ = E2F4 Wild Type")) + guides(color = guide_legend(override.aes = list(size=3)), fill = guide_legend(override.aes = list(size=2))) + facet_wrap(~Well, nrow = 1, strip.position = "bottom") + theme_minimal() + theme(strip.placement = "outside", panel.spacing = unit(0, "cm"), strip.text = element_text(size = 10, margin = margin(b=15)), legend.title = element_text(size = 10), plot.title = element_text(margin = margin(b=10)))
补充:添加误差棒
如果要基于这个均值点加误差棒,同样用geom_errorbar并传入相同的小数据集即可:
geom_errorbar(data = data.frame(Well = "0", E2F4 = "-/-", Colonies = 2837.3333, ymin = 2500, ymax = 3100), aes(x = E2F4, ymin = ymin, ymax = ymax), color = "black", width = 0.2)
内容的提问来源于stack exchange,提问作者astaf
相关产品推荐
相关产品推荐

