【问题标题】:How to make a barplot with two y-variables side by side and standar errors如何制作具有两个并排 y 变量和标准误差的条形图
【发布时间】:2019-07-12 15:31:28
【问题描述】:

我有一个如下图所示的数据框:

df1<- data.frame(Hour=c(0,6,12,18,24,0,6,12,18,24),
                 meanType=c("mean_A","mean_A","mean_A","mean_A","mean_A","mean_B","mean_B","mean_B","mean_B","mean_B"),
                 mean=c(7.3,6.8,8.9,3.4,12.1,6.3,8.2,3.1,4.8,13.2),
                 Se=c(1.3,2.1,0.9,3.2,0.8,0.9,0.3,1.8,1.1,1.3))
df1

   Hour meanType mean  Se
1     0   mean_A  7.3 1.3
2     6   mean_A  6.8 2.1
3    12   mean_A  8.9 0.9
4    18   mean_A  3.4 3.2
5    24   mean_A 12.1 0.8
6     0   mean_B  6.3 0.9
7     6   mean_B  8.2 0.3
8    12   mean_B  3.1 1.8
9    18   mean_B  4.8 1.1
10   24   mean_B 13.2 1.3

我想创建一个条形图,其中 X 轴上的小时数表示出现在数据框中的实际小时数,我还想在每个条形图上添加一个误差条,指示与每个平均值相关的误差。

这是我目前得到的:

Plot1<-ggplot(df1,aes(Hour,mean,fill=meanType))+
  geom_bar(aes(x=Hour, y=mean, fill=meanType),stat="identity",position="dodge")+
  geom_errorbar(aes(x=Hour,y=mean,ymin=mean-Se, ymax=mean+Se), width=0.4, colour="orange", alpha=0.9, size=0.5)
Plot1

但是,我不知道为什么,但是误差条没有得到很好的调整,并且在 X 轴上,小时数似乎是“随机的”(不是我数据框中真正拥有的小时数)。

有谁知道如何解决这些问题?

【问题讨论】:

    标签: r ggplot2 geom-bar


    【解决方案1】:

    您需要将position_dodge() 添加到您的geom_errorbar。此外,无需在每个geom 中重复您的aes。可以使用scale_x 添加中断。

    library(ggplot2)
    
    ggplot(df1,aes(x=Hour,y=mean,fill=meanType))+
      geom_bar(stat="identity",position="dodge")+
      geom_errorbar(aes(ymin=mean-Se,ymax=mean+Se), 
                    width=0.2,colour="black",alpha=0.9,size=0.5,position=position_dodge(5)) +
      scale_x_continuous(breaks = df1$Hour) 
    

    【讨论】:

      【解决方案2】:

      题中的代码有两个问题。

      • x 轴必须是离散的,才能标记所有值。这可以通过将Hour 强制转换为"factor" 来解决。
      • 错误栏也必须有position_dodge()

      所以其余代码或多或少相同,只要它们相同,就会删除重复的aes

      Plot1 <- ggplot(df1, aes(factor(Hour), mean, fill = meanType)) +
        geom_bar(stat = "identity", position = position_dodge()) +
        geom_errorbar(aes(ymin = mean - Se, ymax = mean + Se),
                      position = position_dodge(0.9),
                      width = 0.4, colour = "orange", 
                      alpha = 0.9, size = 0.5)
      
      Plot1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-24
        • 2020-08-13
        • 2013-02-15
        • 2022-08-20
        • 2014-08-02
        相关资源
        最近更新 更多