使用ggplot和facet_wrap绘制多个图

时间:2018-05-31 14:50:58

标签: r ggplot2 dplyr facet-wrap

示例数据

set.seed(123)
df <- data.frame(loc.id = rep(c(1:3), each = 4*10), 
                        year = rep(rep(c(1980:1983), each = 10), times = 3),
                        day = rep(1:10, times = 3*4),
                        x = sample(123:200, 4*3*10, replace = T),
                        start = 123,
                        end = 200)

我希望使用loc.id将每个facet_wrap的图表保存在单个页面中,并将每个loc.id保存在单独的页面中作为pdf。以下 循环这样做:

loc.vec <- 1:3

pdf("my.pdf")

for(l in  seq_along(loc.vec)){

  loc.id <- loc.vec[l]
  df.sub <- df[df$loc.id == loc.id,]

  pp <- ggplot(df.sub,aes(x = day, y = x)) + geom_line() +
          facet_wrap(~year) + 
          geom_vline(aes(xintercept = df.sub$start)) + 
          geom_vline(aes(xintercept = df.sub$end))
  print(pp)
}
dev.off()

我可以在没有循环的情况下实现吗?

由于

2 个答案:

答案 0 :(得分:1)

以下是使用purrr的解决方案:

library(tidyverse)

f_plot <- function(id) {
  df %>%
    filter(loc.id == id) %>%
    ggplot(., aes(x = day, y = x)) + 
    geom_line() +
    facet_wrap(~year) + 
    geom_vline(aes(xintercept = start)) + 
    geom_vline(aes(xintercept = end))
}

pdf("my2.pdf")
map(loc.vec, f_plot)
dev.off()

答案 1 :(得分:1)

考虑by(作为tapply的面向对象的包装器),通过 loc.vec 因子对数据帧进行切片,并通过绘图运行子集:

process_plots <- function(df.sub) {    
  ggplot(df.sub, aes(x = day, y = x)) + 
    geom_line() + facet_wrap(~year) + 
    geom_vline(aes(xintercept = df.sub$start)) + 
    geom_vline(aes(xintercept = df.sub$end))      
}

pdf("my.pdf")    
by(df, df$loc.vec, process_plots)
dev.off()