我想绘制带有误差条的堆积条形图。我有一个包含五个变量的数据框。 Var1包含处理对Var2
中三种不同物种的影响。治疗的效果以变量value
给出。变量start
和end
包含误差线的值。我想以Var1和Var2的顺序应该相同的方式绘制堆积条形图。像这样:
这个数字只是一个例子。一些示例数据:
Var1 Var2 value start end
Eff1 spe1 0.73 0.72 0.74
Eff2 spe1 0.25 0.24 0.26
Eff3 spe1 0.007 0.006 0.008
Eff1 spe2 0.69 0.68 0.7
Eff2 spe2 0 0 0
Eff3 spe2 0.3 0.29 0.31
Eff1 spe3 0.78 0.77 0.79
Eff2 spe3 0 0 0
Eff3 spe3 0.212 0.2 0.22
表中的值与上图不匹配。谢谢你的建议。
答案 0 :(得分:2)
df <- read.table(text="
Var1 Var2 value ybegin yend
Eff1 spe1 0.73 0.72 0.74
Eff2 spe1 0.25 0.24 0.26
Eff3 spe1 0.007 0.006 0.008
Eff1 spe2 0.69 0.68 0.7
Eff2 spe2 0 0 0
Eff3 spe2 0.3 0.29 0.31
Eff1 spe3 0.78 0.77 0.79
Eff2 spe3 0 0 0
Eff3 spe3 0.212 0.2 0.22", header = T)
str(df)
df[df$Var1 == "Eff2", "ybegin"] <- df[df$Var1 == "Eff2", "ybegin"] + df[df$Var1 == "Eff1", "value"]
df[df$Var1 == "Eff2", "yend"] <- df[df$Var1 == "Eff2", "yend"] + df[df$Var1 == "Eff1", "value"]
df[df$Var1 == "Eff3", "ybegin"] <- df[df$Var1 == "Eff3", "ybegin"] + df[df$Var1 == "Eff2", "ybegin"]
df[df$Var1 == "Eff3", "yend"] <- df[df$Var1 == "Eff3", "yend"] + df[df$Var1 == "Eff2", "yend"]
library(ggplot2)
dodge <- position_dodge(width = 0.9)
cols <- c("black", "white", "darkgrey")
limits <- aes(ymax = yend , ymin = ybegin)
ggplot(df, aes(x = Var2, y = value, fill = Var1)) + geom_bar(stat="identity", color = "black") +
scale_fill_manual(values = cols) +
geom_errorbar(limits, colour = "red", width = 1, position = dodge) +
theme_bw() +
theme(panel.grid.major = element_blank() ,panel.grid.minor = element_blank())
答案 1 :(得分:1)
在我看来,带有错误栏的堆积条形图不是最佳选择。为了比较一个带有错误栏的躲避条形图的例子:
ggplot(df, aes(x=Var2, y=value, fill=Var1)) +
geom_bar(stat="identity", color="black", position=position_dodge(width = 0.9)) +
geom_errorbar(aes(ymax=yend, ymin=ybegin), width=0.6, position=position_dodge(width = 0.9)) +
theme_bw() +
theme(panel.grid.major.x = element_blank(), panel.grid.minor = element_blank())
导致: