如何在ggplot2的条形图中添加SE错误条? [英] How do I add SE error bars to my barplot in ggplot2?

查看:310
本文介绍了如何在ggplot2的条形图中添加SE错误条?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用ggplot2作了一个简单的条形图,比较了两种昆虫的雄性和雌性的平均寿命. 我的代码看起来像这样,数据集"就是我的数据集...

I made a simple barplot with ggplot2 comparing the mean lifespan (age) of males and females for 2 insect species. My code looks like this, with "dataset" being, well, my data set...

    gplot(dataset, aes(Species, Age, fill=Sex))+
stat_summary(fun.y = mean, geom = "bar", position = "dodge")+
scale_fill_manual(values = c("Grey25", "Grey"))+
theme(legend.title = element_blank())+
scale_y_continuous(limits = c(0,15))

我尝试使用以下代码手动输入均值±SE的值来设置误差线的限制.为了简单起见,我们假设第1种雄性的均值= 10,SE = 0.5.

I tried using the following code to manually enter the value of the mean±SE to set the limits for the error bar. For the sake of simplicity, let's assume mean=10 and SE=0.5 for males of species1.

geom_errorbar(aes(ymin=9.5, ymax=10.5),width=.2,position=position_dodge(.9))

此代码确实有效,但是它为我的绘图中的每个条设置了相同的误差线.

This code does indeed work, but it sets the same error bars for each bar in my plot.

如何为绘图中的每个条添加等于相应SE的误差条?

How can I add error bars equal to the corresponding SE for each bar in my plot?

我对ggplot和R来说还很陌生,因此欢迎任何帮助/建议.

I am fairly new to ggplot and R in general so any help/advice is welcome.

推荐答案

只需要将stat_summary(geom = "errorbar", fun.data = mean_se, position = "dodge")添加到绘图中,您便不需要做其他事情:

You don't need more than to add stat_summary(geom = "errorbar", fun.data = mean_se, position = "dodge") to your plot:

library(ggplot2)

ggplot(diamonds, aes(cut, price, fill = color)) +
  stat_summary(geom = "bar", fun.y = mean, position = "dodge") +
  stat_summary(geom = "errorbar", fun.data = mean_se, position = "dodge")

如果您希望事先计算值,可以这样做:

If you prefer to calculate the values beforehand, you could do it like this:

library(tidyverse)
pdata <- diamonds %>% 
  group_by(cut, color) %>% 
  summarise(new = list(mean_se(price))) %>% 
  unnest(new)


pdata %>% 
  ggplot(aes(cut, y = y, fill = color)) +
  geom_col(position = "dodge") +
  geom_errorbar(aes(ymin = ymin, ymax = ymax), position = "dodge")

这篇关于如何在ggplot2的条形图中添加SE错误条?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆