2017-07-19 52 views
1

我知道这个问题已经被问很多时候,但我想我找到了所有的方法,其中没有一个似乎工作..R:添加观察数在barplot与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 

,现在我想让它看起来像这样 编辑图形:我放在了错误的图形>应该是这样的

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") 

不过,我挣扎着增加OBSERV数量在图表上 通货膨胀我知道,我应该使用geom_text把标签上的图形,所以我想从这个post

nlabels <- table(Type) 

创建新载体,但我得到了一个错误说

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

有什么建议么?

回答

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(EDIT

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

+0

我道歉,我刚刚更新了我的图形和命令,但我会尝试你的方法为好。然而,我正在寻找将酒吧的观测数量设置在平均水平上,但我会看看我是否可以使用您的指令来玩 – Maru

+0

是的,我明白了。所以尝试'dfmean < - rawscore%>%group_by(interaction(variable,Type))%>%summarize(count = n())' – AntoineBic

+0

我编辑了我的答案。 – AntoineBic

1

在由@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

+0

这完美谢谢! – Maru