R中带有误差条的堆积条形图 [英] stacked bar plot with error bars in R
问题描述
我想绘制带有误差线的堆积条形图.我有一个包含五个变量的数据框.Var1 在Var2
中包含处理对三个不同物种的影响.处理的效果以变量 value
给出.变量 start
和 end
包含误差线的值.我想以 Var1 和 Var2 的顺序应该相同的方式绘制堆积条形图.像这样:
I want to plot a stacked bar plot with error bars. I have a data frame with five variables. Var1 contains the effects of treatments on three different species in Var2
. The effects of treatments are given in variable value
. Variable start
and end
contains the values for error bars. I want to plot a stacked bar plot in a way that orders of Var1 and Var2 should be same. Something like this:
这个数字只是一个例子.一些示例数据:
This figure is just an example. Some example data:
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
表中的数值与上图不符.谢谢你的建议.
The values in table does not match to the figure above. Thank you for the suggestions.
推荐答案
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())
这篇关于R中带有误差条的堆积条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!