R:使用geom_text在条形图上添加观察次数

时间:2017-07-19 12:46:52

标签: r ggplot2 geom-bar geom-text

我知道这个问题经常被问到,但我尝试了我发现的所有方法,但似乎都没有。

这是我目前的数据。

df <- data.frame(ID = c(1,2,3,4), Type = c("A","B","A","B"), Score1 = c(10,20,30,40), Score2 = c(20,40,60,80))
ID   Type    Score1       Score2
1       A        10           20
2       B        20           40
3       A        30           60
4       B        40           80

现在我想制作一个看起来像这样的图表 编辑:我放置了错误的图表&gt;看起来应该是这样的

enter image description here

我可以使用reshapeggplot

来实现条形图
rawscore <- df[, c("Type","Score1", "Score2")]
rawscore <- melt(rawscore, id = c("Type"))
ggplot(rawscore, aes(type, value, fill=variable))+
geom_bar(stat="summary", fun.y="mean", position="dodge")

但是,我努力在图表上添加观察次数 我知道我应该使用geom_text将标签放在图表上,因此我尝试从此post

创建新的向量
nlabels <- table(Type)

但是我说错误

Error: Aesthetics must be either length 1 or the same as the data

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

@Florian对答案的微小改动。

library(dplyr)
rawscore <- df[, c("Type","Score1", "Score2")]
rawscore <- melt(rawscore, id = c("Type")) %>%
    group_by(variable) %>% summarize(value=mean(value), count = n())

ggplot(rawscore, aes(variable, value, fill=variable))+
    geom_bar(stat="identity") +
    geom_text(aes(label=count), vjust=0)

这完美无缺

enter image description here

答案 1 :(得分:1)

df <- data.frame(ID = c(1,2,3,4), Type = c("A","B","A","B"), Score1 = c(10,20,30,40), Score2 = c(20,40,60,80))


rawscore <- df[, c("Type","Score1", "Score2")]
rawscore <- melt(rawscore, id = c("Type"))

尝试构建另一个data.frame(编辑

library(dplyr)

dfmean <- rawscore %>% 
  group_by(interaction(variable, Type)) %>% 
  summarise(m = mean(value), count = n())
names(dfmean)[1] <- "Inter"

ggplot(rawscore, aes(x = interaction(variable, Type), y = value)) + 
  geom_bar(aes(fill = variable), stat="summary", fun.y="mean", position="dodge") +
  geom_text(data = dfmean, aes(x = Inter, y = m + 1, label = count))

enter image description here