user2716568 user2716568 - 2 months ago 7
R Question

Create data labels for frequency plot in ggplot2?

In this question, a frequency figure can be created using ggplot. For example:

f <- factor(sample(letters[1:5], 100, r=T))
h <- table(f) / length(f)
dat <- data.frame(f = f)
ggplot(dat, aes(x=f, y=..count.. / sum(..count..), fill=f)) + geom_bar()


How do I now obtain data labels for each individual bar within the figure?

Thank you.

Answer

You can add geom_text():

library(ggplot2)
ggplot(dat, aes(x=f, y=..count.. / sum(..count..), fill=f)) + 
  geom_bar() +
  geom_text(stat = "count", aes(label=..count../100))

enter image description here