Ted Mosby
Ted Mosby

Reputation: 1456

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?

Upvotes: 0

Views: 22

Answers (1)

Mark Peterson
Mark Peterson

Reputation: 9570

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)

Upvotes: 1

Related Questions