This is really a follow-on question from here Showing data values on stacked bar chart in ggplot2
In the following plot, I also want to include the column totals, eg: the first stack should show a total of 963 (168+259+226+340):
Year <- c(rep(c("2006-07", "2007-08", "2008-09", "2009-10"), each = 4))
Category <- c(rep(c("A", "B", "C", "D"), times = 4))
Frequency <- c(168, 259, 226, 340, 216, 431, 319, 368, 423, 645, 234, 685, 166, 467, 274, 251)
Data <- data.frame(Year, Category, Frequency)
library(ggplot2)
ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
geom_bar(stat = "identity") +
geom_text(size = 3, position = position_stack(vjust = 0.5))
You have to create another summarised table (sum of Frequency by Year) and add it to plot as another geom_text
layer with vjust
> 1 to be above the bar.
dfSum <- aggregate(Data$Frequency, list(Data$Year), sum)
ggplot(Data, aes(Year, Frequency, fill = Category, label = Frequency)) +
geom_bar(stat = "identity") +
geom_text(size = 3, position = position_stack(vjust = 0.5)) +
geom_text(aes(Group.1, x, label = x), dfSum, inherit.aes = FALSE,
position = position_stack(vjust = 1.05))