首页 > 解决方案 > 如何在 ggplot 瀑布图上添加误差线?

问题描述

我想在我的瀑布图中的所有条形图中添加误差线。

这是一个示例数据和我用来创建绘图的代码:

library(dplyr)
library(ggplot2)
set.seed(100)

df<-tibble(Year= c(2001, 2001, 2001, 2001, 2002, 2002, 2002, 2002, 2003, 2003, 2003, 2003), Vals = abs(rnorm(12)*5), Affil = as.factor(c(1,2,1,2,1,2,1,2,1,2,1,2)), SD=rnorm(12, 1, 0.5))
df[c(T, T, F, F),]$Vals <- -(df[c(T, T, F, F),]$Vals)


p <- ggplot(data = df, aes(Year,Vals)) + 
  geom_bar(stat = "identity", aes(fill=Affil), position=position_dodge()) + 
  geom_errorbar(aes(ymin=Vals-SD, ymax=Vals+SD), width=.2, position=position_dodge(.9))
p + theme_bw(base_size = 16) + geom_hline(aes(yintercept=0), size=1.25) 

对于每一年,应该有 2 对误差线。两个代表每年Affil,2 个代表与每年相关的正值和负值Affil。我尝试过内联过滤dplyr,逐步添加错误栏,但解决方案变得繁琐且无法正常工作。

标签: rggplot2

解决方案


我可以通过为错误栏分配color美学来做到这一点:

p <- ggplot(data = df, aes(Year,Vals)) + 
  geom_bar(stat = "identity", aes(fill=Affil), position=position_dodge()) + 
  geom_errorbar(aes(ymin=Vals-SD, ymax=Vals+SD, color=Affil), width=.2, position=position_dodge(0.9))
p + theme_bw(base_size = 16) + geom_hline(aes(yintercept=0), size=1.25) +
  scale_color_manual(values=c("firebrick4","darkblue"))

在此处输入图像描述

为了避免重叠您可以使用的误差position_jitterdodge线,但这会产生一些奇怪的线条,对于我搜索的内容,您可以通过这样做来解决:使用 `jitterdodge` 时在 ggplot 中对齐点和误差线


推荐阅读