2017-01-18 84 views
1

鑑於以下數據:用標籤添加置信區間以柱狀圖

df.plot <- data.frame(x=c("outcome name","outcome name"), 
         Condition=c("A","B"), 
         Score=c(41.5,51.8)) 

我可以生成以下圖表:

enter image description here

有了這個代碼:

ggplot(df.plot, aes(x=x, y=Score, fill=Condition)) + 
    geom_bar(position = 'dodge', stat='identity', width=.5) + 
    xlab(NULL) + coord_cartesian(ylim=c(0,100)) + 
    geom_text(aes(label=round(Score,2)), position=position_dodge(width=0.5), vjust=-0.25) 

我想添加一個置信區間的「B」欄從27.5到76.1。我希望這些值在圖中標出。

我試圖修改包含這些信息,並使用geom_errorbar但我endup與2個間隔這一翻譯的只有我一個條件「B」

df.plot <- data.frame(x=c("outcome name","outcome name"), 
         Condition=c("A","B"), 
         Score=c(41.5,51.8), 
         lb = c(NULL,27.5), 
         ub = c(NULL,76.1)) 

ggplot(df.plot, aes(x=x, y=Score, fill=Condition)) + 
    geom_bar(position = 'dodge', stat='identity', width=.5) + 
    xlab(NULL) + coord_cartesian(ylim=c(0,100)) + 
    geom_errorbar(aes(ymin = lb, ymax = ub), 
       width = 0.2, 
       linetype = "dotted", 
       position = position_dodge(width = 0.5), 
       color="red", size=1) + 
    geom_text(aes(label=round(Score,2)), position=position_dodge(width=0.5), vjust=-0.25) 

enter image description here

最後,我不知道怎麼樣將標籤添加到間隔的頂部和底部。

回答

2

NA用於缺失值不NULL

這應該工作,你希望:

df.plot <- data.frame(x=c("outcome name","outcome name"), 
        Condition=c("A","B"), 
        Score=c(41.5,51.8), 
        lb = c(NA,27.5), 
        ub = c(NA,76.1)) 


ggplot(df.plot, aes(x=x, y=Score, fill=Condition)) + 
    geom_bar(position = 'dodge', stat='identity', width=.5) + 
    xlab(NULL) + coord_cartesian(ylim=c(0,100)) + 
    geom_errorbar(aes(ymin = lb, ymax = ub), 
      width = 0.2, 
      linetype = "dotted", 
      position = position_dodge(width = 0.5), 
      color="red", size=1) + 
    geom_text(aes(label=round(Score,2)), position=position_dodge(width=0.5), vjust=-0.25) + 
    geom_text(aes(y = lb, label = lb), position=position_dodge(width=0.5), vjust=2) 

improved version