示例数据
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()
我可以在没有循环的情况下实现吗?
由于
答案 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()