为条形图添加带标签的置信区间

时间:2017-01-18 14:31:15

标签: r ggplot2

鉴于以下数据:

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的置信区间。我希望在图表中标记这些值。

我尝试修改df.plot以包含此信息并使用geom_errorbar,但我最终只有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

最后,我不确定如何将标签添加到间隔的顶部和底部。

1 个答案:

答案 0 :(得分:1)

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