示例数据
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)
我想使用facet_wrap
将所有loc.id
的情节保存在一个页面中,并将每个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()
我可以在没有循环的情况下实现吗?
谢谢
以下是使用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()
考虑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()