Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in R Programming by (7.3k points)
edited by

I'd like to show data values on a stacked bar chart in ggplot2. Here is my attempted code

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)

p <- qplot(Year, Frequency, data = Data, geom = "bar", fill = Category,     theme_set(theme_bw()))

p + geom_text(aes(label = Frequency), size = 3, hjust = 0.5, vjust = 3, position =     "stack") 

enter image description here

I'd like to show these data values in the middle of each portion. Any help in this regard will be highly appreciated. Thanks

1 Answer

0 votes
by
edited by

You can set the position argument to stack in the geom_text function as follows:

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

Output:

image

Browse Categories

...