使用ggplot将数据频率添加到条形图

时间:2017-10-24 19:43:01

标签: r ggplot2

这是我使用ggplot创建条形图的代码。

library(tidyverse)
    dat= data_frame(rating=1:5, No=c(167,82, 132, 182, 200), Yes=c(28, 22, 20, 27, 29))
    dat = dat %>%
      gather(key=color, value=value, -rating)
    d = ggplot(data=dat, aes(x=rating, y=value, fill=color)) + 
      geom_bar(stat='identity', position='dodge')+ labs(fill = "headache", y = "frequency") 

    d = d + scale_fill_manual(values=c("blue", "yellow"))

    d = d  + theme_bw() + theme(panel.border = element_blank(), panel.grid.major = element_blank(),
                                 panel.grid.minor = element_blank(), axis.line = element_line(colour = "black")) 

我需要将每个数据的频率添加到每个条形的顶部。有什么建议吗?

1 个答案:

答案 0 :(得分:3)

尝试添加此内容:

d + geom_text(aes(label = value), 
              size = 3, 
              color = "black",
              position = position_dodge(width = 0.9),
              vjust = -2)