ggplot中的循环和子集化

时间:2016-03-16 05:12:56

标签: r loops ggplot2

我在循环中对数据进行子集化以创建多个ggplots时遇到了困难。目标是为每个唯一的id值创建一个图。 我认为问题在于填充=原因我认为也需要进行子集化。

## 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之外完成。无论如何,我需要循环快速。

1 个答案:

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

产量: enter image description here