【问题标题】:Adding errorbars to horizontal barplot in R将误差线添加到 R 中的水平条形图
【发布时间】:2018-06-01 11:32:35
【问题描述】:

非常感谢社区对我的小 R 问题的帮助。我到处搜索,但还没有找到解决方案。

我的数据如下所示:

trait2 <- c('A','B','C','D')
rg <- c (0.5480, 0.4801, 0.2805, -0.2480)
se <- c(0.0495, 0.0908, 0.0548, 0.0957)

trait2   rg      se
A       0.5480  0.0495
B       0.4801  0.0908
C       0.2805  0.0548
D       -0.2480  0.0957

我使用这段代码绘制了一个基本的条形图:

barplot1 <- barplot(data$rg,
main="correlation between traits",
xlab="rG",  
border="blue", 
las=1, 
horiz=TRUE, 
names.arg=data$trait2, 
cex.names=0.5,
xlim=range(-0.4,0.6,0.1) )

效果很好:

但我在使用此代码时遇到错误栏问题:

arrows(barplot1, 
   data$rg- data$se,
   data$rg+ data$se,
   lwd= 1.5,angle=90,code=3,length=0.05)

出现错误栏,但没有出现在它们应该出现的位置:

这可能很简单,但如果有人能帮助我,我会非常感激。 最好的,阿伦

【问题讨论】:

    标签: r plot bar-chart


    【解决方案1】:

    如果horiz = FALSE,那么你的arrows代码块应该是

    arrows(x0 = barplot1, 
           y0 = data$rg - data$se,
           x1 = barplot1,
           y1 = data$rg + data$se,
           lwd= 1.5,angle=90,code=3,length=0.05)
    

    但是,由于horiz = TRUE,你需要切换x0y0x1y1的位置。在基础 R 中执行此操作的完整代码是:

    barplot1 <- barplot(data$rg,
                        main="correlation between traits",
                        xlab="rG",  
                        border="blue", 
                        las=1, 
                        horiz = TRUE,
                        names.arg=data$trait2, 
                        cex.names=0.5,
                        xlim=range(-0.4,0.6,0.1))
    
    
    segments(data$rg - data$se, barplot1, data$rg + data$se , barplot1,
             lwd = 1.5)
    
    arrows(data$rg - data$se, barplot1, data$rg + data$se, barplot1, 
           lwd = 1.5, angle = 90,
           code = 3, length = 0.05)
    


    ggplot2 中更容易做到这一点。

    ggplot(data, aes(trait2, rg)) + geom_col(color = "blue") + 
      geom_errorbar(aes(ymin = rg - se, ymax = rg + se), width = 0.3) + 
      coord_flip() + 
      theme_bw()
    

    【讨论】:

    • 非常感谢!我尝试了很多不同版本的箭头函数,但那个版本不在其中,尽管现在看起来很合乎逻辑。再次感谢您!
    猜你喜欢
    • 2016-01-04
    • 2017-02-28
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 2020-12-31
    • 1970-01-01
    相关资源
    最近更新 更多