首页 > 解决方案 > 如何使用 ggplot2 绘制分组条形图的误差线?

问题描述

我有一个数据集,其中一个变量(bTemp)有两个不同的因素(位置和值),我根据这两个因素对数据进行分组,然后为这些数据组生成标准误差(sem)(即我生成了 st.字段最大值、实验室最大值、字段最小值等下的数据错误)。

我试图绘制圣。分组数据的错误到我的分组条形图上,但我只得到一个。每个平均条集群的误差条,而不是两个(集群中的每个平均条一个)。我检查了我的分组数据框,它正在生成 st。错误正确。所以我在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()

标签: rggplot2dplyr

解决方案


您非常接近,您需要在 ggplot 函数中而不是在 geom_bar 函数中指定填充。

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()

在此处输入图像描述


推荐阅读