在R中为自定义条形图功能添加误差线

时间:2017-06-01 12:29:25

标签: r bar-chart correlation

我有一个函数来制作自定义条形图,用于绘制看起来像这样的相关系数

    olsenbar <- function(i , axisnames = FALSE , data = rs) {
   barplot(
     data[,i] ,
     main = colnames(data)[i] ,
     horiz = TRUE ,
     border = FALSE ,
     space = NULL , col = c ("dimgray") , 
     axes = FALSE ,
     axisnames = axisnames ,
     cex.names = 2 ,
     cex.main = 2 ,
     ylab = "" ,
     xlab = "" ,
     xlim = c(-1,1))
   axis( side = 1 , at = c(-1.0,0,1.0) , cex.axis = 1.6)
   abline( v = 0 , lty = 1 , lwd = 3 , col = grey(0.5))
   abline( v = seq( -1 , 1 , 0.1 ) , lty = 3 )}

我想申请一些看起来如下的相关词。该数据包括相关系数和相应的置信区间以及具有另一个变量的p值。

df
                       lower     r upper    p
Hcy response           -0.28  0.53  0.90 0.18
Cysteine response      -0.48  0.34  0.84 0.41
Methionine response    -0.44  0.38  0.86 0.36
Cystathionine response -0.10  0.65  0.93 0.08
Glutation response     -0.83 -0.31  0.51 0.46
Taurine response       -0.31  0.51  0.89 0.20

当我将上述功能应用于此时

olsenbar( 2 , data = df , axisnames = TRUE )

我最终得到以下情节

Barplot

但是,我想在条形图中输入相应的置信区间,但我似乎无法解决这个问题。据我了解,为这些条形图制定误差条有点棘手,无论我尝试什么,我都无法工作。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

使用ggplot2

library(ggplot2)
ggplot(df, aes(names, r)) +
    geom_col(fill = 'dimgray') +
    geom_errorbar(aes(ymin = lower, ymax = upper), width = .5, size = 1) +
    geom_hline(yintercept = 0) +
    scale_y_continuous(limits = c(-1, 1), position = 'top', breaks = c(-1, 0, 1), minor_breaks = seq(-1, 1, .1)) +
    coord_flip() +
    theme(panel.grid = element_blank(),
          panel.grid.major.x = element_line(linetype = 3, colour = 'black'),
          panel.grid.minor.x = element_line(linetype = 3, colour = 'black'),
          panel.background = element_rect('white')
          )

数据:

df <- read.table(text = 'names lower     r upper    p
"Hcy response"           -0.28  0.53  0.90 0.18
                 "Cysteine response"      -0.48  0.34  0.84 0.41
                 "Methionine response"    -0.44  0.38  0.86 0.36
                 "Cystathionine response" -0.10  0.65  0.93 0.08
                 "Glutation response"     -0.83 -0.31  0.51 0.46
                 "Taurine response"       -0.31  0.51  0.89 0.20', h = T)