R: Adding number of observation on the barplot with geom_text

Maru picture Maru · Jul 19, 2017 · Viewed 7.6k times · Source

I know that this question has been asked very often, but I tried all the method I found and none of them seems to work..

This is my current data.

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

and now I want to make a graph that looks like this Edit: I placed the wrong graph > It should look like this

enter image description here

I am able to achieve the bar graph using the reshape and ggplot

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

However, I struggles to add the number of observation on the graph I know that I should use geom_text to put the label on the graph, so I tried creating the new vector from this post

nlabels <- table(Type)

but I got an error saying

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

Any suggestions?

Answer

abichat picture abichat · Jul 19, 2017
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"))

Try to construct another 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