0

I'm having difficulties subsetting data within a loop to create multiple ggplots. The objective is to create a plot for each unique value of id. The problem I believe is in fill = reason which I believe needs subsetting too.

## Calendar plot loop
id.calendar <- function(daily, na.rm = TRUE, ...){

myid <- unique(daily$id)

for (i in seq_along(myid)) { 

calendar <-
ggplot(subset(dat, dat$id==myid[i]),
       aes(monthweek, weekdayf, fill = reason)) +
  geom_tile(colour = "grey80") +
  facet_grid(year~monthf)

print(calendar)
}
}

Error: Insufficient values in manual scale. 9 needed but only 6 provided. 

dat$id is a string (though it could be converted to numeric). I read somewhere in this forum that subsetting is best done outside of ggplot. Regardless, I need the loop to be fast.

Thomas Speidel
  • 1,369
  • 1
  • 14
  • 26

1 Answers1

1

Guessing a bit here as there is no data, but I think this is what you want. Note that I arranged the different id plots underneath each other using arrangeGrob:

library(ggplot2)
library(grid)
library(gridExtra)

id.calendar <- function(daily,na.rm = TRUE,...) {

    myid <- unique(daily$id)

    gpl <- list()
    n <- length(myid)
    for(i in 1:n) {

        df <-subset(dat,dat$id == myid[i])
        title <- sprintf("ID %s has %d elements",myid[i],nrow(df))
        gpl[[i]] <-  ggplot(df,
            aes(monthweek,weekdayf,fill = reason)) +
            geom_tile(colour = "grey80") +
            facet_grid(year ~ monthf) +
            labs(title=title)
    }
    glst <<- gpl
    calendar <- arrangeGrob(grobs=gpl,nrow=n)
    grid.draw(calendar)
}

# fake up some data
n <- 50
id <- sample(c("A","B","C"),n,replace=T)
mw <- sample(1:4,n,replace=T)
wd <- sample(0:6,n,replace=T)
mm <- sample(1:12,n,replace=T)
year <- sample(2011:2014,n,replace=T)
reason <- sample(c("Reason1","Reason2","Reason3","Reason4"),n,replace=T)
daily <- data.frame(id=id)
dat <- data.frame(id=id,monthweek=mw,year=year,monthf=mm,weekdayf=wd,reason=reason)

id.calendar(daily)

Yielding: enter image description here

Mike Wise
  • 22,131
  • 8
  • 81
  • 104