0

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))
pogibas
  • 27,303
  • 19
  • 84
  • 117
cephalopod
  • 1,826
  • 22
  • 31
  • Yes, but for the plot I am working on, I need to use "stacked", hence, `position_dodge` does not work for me in this instance – cephalopod Jan 11 '19 at 01:04
  • Possible duplicate of [draw the sum value above the stacked bar in ggplot2](https://stackoverflow.com/questions/30656846/draw-the-sum-value-above-the-stacked-bar-in-ggplot2) – VFreguglia Jan 11 '19 at 01:27

1 Answers1

1

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

enter image description here

pogibas
  • 27,303
  • 19
  • 84
  • 117