2016-03-16 31 views
0

我很难在一个循环内创建多个ggplots的子集数据。目的是为每个唯一的id值创建一个图表。 我相信问题在于fill = reason,我相信它也需要子集。在ggplot循环和子集

## 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是一个字符串(虽然它可能会被转换为数字)。我在这个论坛上的某处读到,子集化最好在ggplot之外完成。无论如何,我需要循环快。

+2

(http://stackoverflow.com/questions/ 5963269) – zx8754

+1

我认为这对于(我在seq_along(myid))'应该是'for(我在myid中)'? seq_along给出1:n的数字,例如:'seq_along(letters [1:3])' – zx8754

+0

道歉为不包括一个可重复的例子(我通常这样做)。 –

回答

1

在这里猜测有点没有数据,但我认为这是你想要的。请注意,我安排不同的id地块对方下使用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) 

产量:[?如何使一个伟大的[R重复的例子] enter image description here

+0

谢谢@Mike。这工作很好。 –