I'm attempting to place labels on a stacked bar plot using this approach (though if there's now a better approach I'm open to what ever):
Showing data values on stacked bar chart in ggplot2
Here's my original plot:
dat <- data.frame(with(mtcars, table(cyl, gear)))
ggplot(dat, aes(x = gear, fill = cyl)) +
geom_bar(aes(weight=Freq), position="stack") +
geom_text(position = "stack", aes(x = gear, y = Freq,
ymax = 15, label = cyl), size=4)
Here's my attempt to center labels in each fill section:
dat2 <- ddply(dat, .(cyl), transform, pos = cumsum(Freq) - 0.5*Freq)
library(plyr)
ggplot(dat2, aes(x = gear, fill = cyl)) +
geom_bar(aes(weight=Freq), position="stack") +
geom_text(position = "stack", aes(x = gear, y = pos,
ymax = 15, label = cyl), size=4)
How can I center the labels in each fill section?