【问题标题】:looping and subsetting in ggplotggplot中的循环和子集
【发布时间】:2016-03-16 05:12:56
【问题描述】:

我在一个循环中对数据进行子集化以创建多个 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 之外完成。无论如何,我需要快速循环。

【问题讨论】:

  • 我认为for (i in seq_along(myid)) 应该是for (i in myid) ? seq_along 给出 1:n 的数字,例如:seq_along(letters[1:3])
  • 很抱歉没有包含可重现的示例(我通常会这样做)。

标签: r loops ggplot2


【解决方案1】:

在这里猜测一下,因为没有数据,但我认为这就是你想要的。请注意,我使用arrangeGrob 将不同的id 图排列在彼此下方:

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)

产量:

【讨论】:

    猜你喜欢
    • 2020-02-24
    • 2021-06-10
    • 2015-01-15
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    • 2021-06-23
    相关资源
    最近更新 更多