使用geom_errorbar时数据框中的错误?

时间:2015-11-13 13:48:43

标签: r ggplot2

我的数据框(df)如下所示:

   df
 me  SD class  
 3.11 4.08  A
 2.09 3.50  B
 1.75 2.72  C
 0.34 0.85  D

其中me是平均值,SD是标准偏差。我想为每个类创建这些平均值的条形图,并在这些条形顶部添加标准偏差:

绘制条形图:

ggplot(data=df) +
  geom_bar(aes(x=class,y= me), 
           stat="identity",position="dodge")+ 
  ylab("mean")+ 
  xlab("class")+ 
  theme(
    text = element_text(size=20, colour="black"),  
    axis.text.x = element_text(angle=90, vjust=1, colour="black"), 
    axis.text.y = element_text(colour="black")) + 
  scale_y_continuous(breaks = round(seq(-2, 5, by = 0.5),1))

这很好用。

现在添加错误栏:

ggplot(data=df3) +
  geom_bar(aes(x=class,y= me), 
           stat="identity",position="dodge")+ 
  ylab("mean")+   
  xlab("class")+ 
  theme(
    text = element_text(size=20, colour="black"),  
    axis.text.x = element_text(angle=90, vjust=1, colour="black"), 
    axis.text.y = element_text(colour="black"))+ 
  scale_y_continuous(breaks = round(seq(-2, 5, by = 0.5),1))+ 
  geom_errorbar(aes(ymax = me + SD, ymin= me - SD), 
                position=position_dodge(0.9))

我收到了这个错误:

   Error in data.frame(list(ymin = c(-1.96681604736652, -1.40293149619775,  : 
    arguments imply differing number of rows: 28, 102   

1 个答案:

答案 0 :(得分:2)

x

中定义yggplot
ggplot(data=df, aes(x = class, y = me)) + 
geom_bar(stat="identity",position="dodge")+ ylab("mean")+   
xlab("class") + theme(text = element_text(size=20, colour="black"),  
axis.text.x = element_text(angle=90, vjust=1, colour="black"), 
axis.text.y = element_text(colour="black"))+ scale_y_continuous(breaks 
= round(seq(-2, 5, by = 0.5),1)) + geom_errorbar(aes(ymax = me + SD, 
ymin= me - SD), position=position_dodge(0.9))

enter image description here

可替换地:

ggplot(data=df, aes(x = class, y = me)) + 
    geom_bar(stat="identity",position="dodge")+ ylab("mean")+   
    xlab("class") + theme(text = element_text(size=20, colour="black"),  
                          axis.text.x = element_text(angle=90, vjust=1, colour="black"), 
                          axis.text.y = element_text(colour="black"))+ scale_y_continuous(breaks 
                                                                                          = round(seq(-2, 5, by = 0.5),1)) + geom_errorbar(aes(ymax = SD, 
                                                                                                                                               ymin= me - (SD-me)), position=position_dodge(0.9))

enter image description here