1

I am trying to create stack bar with counts and Group levels in the same graph (inside of plot). since the group variable has 25 levels, I prefer to bring the name of group levels inside of plot (since we have 25 different colour and is difficult for visualization).I took help from "Showing data values on stacked bar chart in ggplot2". I was wondering how can I add the name of each group level inside of graph.

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(dplyr)  
Data <- group_by(Data,Year) %>%
 mutate(pos = cumsum(Frequency) - (0.5 * Frequency))

library(ggplot2)
#plot bars and add text
p <- ggplot(Data, aes(x = Year, y = Frequency)) +
     geom_bar(aes(fill = Category), stat="identity") +
     geom_text(aes(label = Frequency, y = pos), size = 3)
Community
  • 1
  • 1
shoorideh
  • 173
  • 5
  • 16

1 Answers1

3

Something along these lines would do the trick:

p <- ggplot(Data, aes(x = Year, y = Frequency)) +
  geom_bar(aes(fill = Category), stat="identity", show.legend = FALSE) +
  geom_text(aes(label = Frequency, y = pos), size = 3, nudge_y = -25) +
  geom_text(aes(label = Category, y = pos), size = 3, nudge_y = 25)

which plots

plot with labels on stacked bars

Customize as you like.

alistaire
  • 42,459
  • 4
  • 77
  • 117
  • Hi, Could you please give me an advice regarding reordering these cells based on their frequencies. – shoorideh Jan 25 '16 at 10:49
  • 1
    Put `arrange(desc(Frequency))` (for smallest bars at the top; remove `desc` for the reverse) in your `dplyr` chain *before the `mutate`*. – alistaire Jan 25 '16 at 15:58