I've created this plot with following code:
library(ggplot2); library(reshape2); library(plyr)
likert <- data.frame(age = c(rep("young", 5), rep("middle", 5), rep("old", 5)),
score1 = c(rep("unlikely", 1), rep("likely", 1), rep("very likely", 13)),
score2 = c(rep("disagree", 6), rep("neutral", 4), rep("agree", 5)),
score3 = c(rep("no", 5), rep("maybe", 7), rep("yes", 3)))
meltedLikert <- melt(dlply(likert, .(age), function(x) llply(x, table)))
names(meltedLikert) <- c("score", "count", "variable", "age")
ggplot(meltedLikert[meltedLikert$variable != "age",], aes(variable, count, fill=score)) +
geom_bar(position="dodge", stat="identity") +
geom_text(data=data.frame(meltedLikert), aes(variable, count, group=score, label=meltedLikert$score), size=4) +
facet_grid(age ~ .)
How can I label position text so each label of score
sits over the corresponding bar for variable
top of each bar?
As per the answer in the linked question, adding
position = position_dodge(width=0.9)
to thegeom_text
call lines up the values:However, I also wanted to point out a few other things. You should no use
meltedLikert$score
in theaes()
call; you should only refer to things in the data frame that is passed asdata
. Also,meltedLikert
is already adata.frame
, so callingdata.frame()
on it is not necessary (though doesn't do any harm).The real improvement is in how you create your tabulation to begin with. Consider this instead:
You can fix the ordering of the bars by fixing them in the original data:
Of course, at this point, the colors don't actually add anything since everything is labeled directly on the graph, so I'd just get rid of them entirely.