Reputation: 3805
Sample data
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)
I want to save the plot of each loc.id
for all years in a single page using facet_wrap
and each loc.id
in separate pages as a pdf. Following
loop does this:
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()
Can I achieve without the loop?
Thanks
Upvotes: 0
Views: 1042
Reputation: 107567
Consider by
(being the object-oriented wrapper to tapply
) to slice dataframe by the loc.vec factor and run subsets through plot:
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()
Upvotes: 1
Reputation: 3938
Here is a solution using 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()
Upvotes: 1