Hydro
Hydro

Reputation: 1117

saving multiple ggplot in a single pdf documents in R?

Is there a way to save all the plots as a single pdf document

library(tidyverse)
library(lubridate)

set.seed(123)

DF1 <- data.frame(Date = seq(as.Date("2001-01-01"), to= as.Date("2003-12-31"), by="day"),
                  A = runif(1095, 0,10),
                  D = runif(1095,5,15))
DF1 %>% pivot_longer(names_to = "Variable", values_to = "Value", -Date) %>% 
  ggplot(aes(x = Date, y = Value))+
  geom_line()+
  facet_wrap(~Variable)+
  ggsave("Plot1.pdf", dpi = 200, height = 6, width = 8)


DF2 <- data.frame(Date = seq(as.Date("2005-03-01"), to= as.Date("2005-05-31"), by="day"),
                  Z = runif(92, 0,10))

DF2 %>% ggplot(aes(x = Date, y = Z))+
  geom_line()+
  ggsave("Plot2.pdf", dpi = 200, height = 6, width = 8)

Upvotes: 0

Views: 1560

Answers (1)

Duck
Duck

Reputation: 39595

For your data, you could save the plots and then using pdf. If you have plenty of plots it would be better to create a list with the plots and the export them. Here the code for your plots (You can play with height and width parameters of pdf):

library(tidyverse)
library(lubridate)

set.seed(123)

DF1 <- data.frame(Date = seq(as.Date("2001-01-01"), to= as.Date("2003-12-31"), by="day"),
                  A = runif(1095, 0,10),
                  D = runif(1095,5,15))
DF1 %>% pivot_longer(names_to = "Variable", values_to = "Value", -Date) %>% 
  ggplot(aes(x = Date, y = Value))+
  geom_line()+
  facet_wrap(~Variable) -> G1

DF2 <- data.frame(Date = seq(as.Date("2005-03-01"), to= as.Date("2005-05-31"), by="day"),
                  Z = runif(92, 0,10))

DF2 %>% ggplot(aes(x = Date, y = Z))+
  geom_line()->G2
#Export
pdf('Yourfile.pdf',height = 6, width = 8)
plot(G1)
plot(G2)
dev.off()

Upvotes: 2

Related Questions