[英]How to plot error bars for grouped bar chart using ggplot2?
I have a data set with two different factors (Place and Value) for one variable (bTemp) and I grouped the data based on the two factors, then generated the standard error (sem) for these data groups (ie I generated the st. error for data under field max, lab max, field min, etc.).我有一个数据集,其中一个变量(bTemp)有两个不同的因素(位置和值),我根据这两个因素对数据进行分组,然后为这些数据组生成标准误差(sem)(即我生成了 st.字段最大值、实验室最大值、字段最小值等下的数据错误)。
I tried to plot the st.我试图 plot st。 errors of the grouped data onto my grouped bar chart, but I am only getting one st.
分组数据的错误到我的分组条形图上,但我只得到一个。 error bar for each cluster of mean bars rather than two (one for each mean bar in the cluster).
每个平均条集群的误差条,而不是两个(集群中的每个平均条一个)。 I checked my grouped data frame and it is generating the st.
我检查了我的分组数据框,它正在生成 st。 errors properly.
错误正确。 So there must be something wrong with how I am defining the error bars in geom_errorbar.
所以我在 geom_errorbar 中定义误差线的方式一定有问题。
str(LabFieldData)
'data.frame': 324 obs. of 3 variables:
$ Place: Factor w/ 2 levels "Field","Lab": 1 1 1 1 1 1 1 1 1 1 ...
$ Value: Factor w/ 3 levels "Max","Mean","Min": 3 3 3 3 3 3 3 3 3 3 ...
$ bTemp: num 26.5 26.7 26.1 28.1 26.6 26.8 23.9 26.1 28.5 26.4 ...
#Group data by place (lab,field) and value(min,mean,max)
LabFieldData %>% group_by(Place,Value) %>%
mutate(sem = sd(bTemp)/sqrt(length(bTemp))) %>%
#Plot bar plot of means by value (mean, min, max) and color by place (lab, field)
ggplot(mapping = aes(Value, bTemp, color = Place)) +
geom_bar(mapping = aes(color = Place, fill = Place), stat = "summary", position="dodge") +
geom_errorbar(stat = 'summary', mapping = aes(ymin=bTemp-sem,ymax=bTemp+sem),
position=position_dodge(0.9),width=.1, color = "black", size = 1) +
scale_y_continuous(name = "Body Temperature (°C)", breaks = c(0,5,10,15,20,25,30,35),
limits=c(0,34)) + scale_x_discrete(name=element_blank(),limits=c("Min","Mean","Max")) +
theme(legend.title = element_blank()) + scale_color_hue()
You were very close, you need to specify the fill in the ggplot function and not in the geom_bar function.您非常接近,您需要在 ggplot function 中而不是在 geom_bar function 中指定填充。
LabFieldData %>% group_by(Place,Value) %>%
mutate(sem = sd(bTemp)/sqrt(length(bTemp))) %>%
#Plot bar plot of means by value (mean, min, max) and color by place (lab, field)
ggplot(mapping = aes(Value, bTemp, color = Place, fill=Place)) +
geom_bar(stat = "summary", position="dodge") +
geom_errorbar(stat = 'summary', mapping = aes(ymin=bTemp-sem,ymax=bTemp+sem),
position=position_dodge(0.9), width=.1, color = "black", size = 1) +
scale_y_continuous(name = "Body Temperature (°C)", breaks = c(0,5,10,15,20,25,30,35), limits=c(0,34)) +
scale_x_discrete(name=element_blank(), limits=c("Min","Mean","Max")) +
theme(legend.title = element_blank()) + scale_color_hue()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.