Ted Mosby Ted Mosby - 1 month ago 12
R Question

Selecting bars if total goes over a value in ggplot2

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


Lets say I have the code/data above. I'm only interested in plotting values if they total(stack) to above 1000. Is this possible with a simple subset command in the ggplot code?

Answer

I don't think it is possible within ggplot itself, but it is relatively straightforward to do with dplyr and you can then pass in just the data you want to plot. E.g.:

Data %>%
  group_by(Year) %>%
  mutate(Total = sum(Frequency)) %>%
  filter(Total > 1000)