1

Im trying to combine this graph i made in ggplot [![enter image description here][1]][1]

with a few more graphs (an example shown below) in a single PDF file. But the 1st graph is on one page, the next graph 2 is in page 2, graph 3 in page 3 and so on.

[![enter image description here][2]][2]

My problem is that i cant seem to combine the graphs in 1 pdf file as i keep getting an error where I cant open the PDF file. Ive tried to modify the code ive seen here: Printing multiple ggplots into a single pdf, multiple plots per page

but it cant seem to work

(this part is for the 4 graphs in 1 page)

pdf("plots.pdf", onefile = TRUE)

plot1 <- ggplot(data = FBMKLCI.df) +
 theme_minimal() +
  geom_line(aes(x = Date, y = PX_LAST., color = 
PE)) +
  scale_color_continuous(low = 'green', high='red') +
  labs(y="", colour = "PE") +
  theme(legend.position = 'bottom', 
        plot.title = element_text(colour = 'blue', face = 'bold'),
        legend.key.width = unit(1, "cm")) +
  ggtitle('FBMKLCI') 


plot2<- ggplot(data = FBM70.df) +
  theme_minimal() +
  geom_line(aes(x = Date, y = PX_LAST., color = 
PE)) +
  scale_color_continuous(low = 'green', high='red') +
  labs(y="",colour = "PE")+
  theme(legend.position = 'bottom', 
        plot.title = element_text(colour = 'blue', face = 'bold'),
        legend.key.width = unit(1, "cm")) +
  ggtitle('FBM70')

plot3 <- ggplot(....

plot4<-...

grid.arrange(plot1, plot2, plot3, plot4, ncol=2)

(this part is for the graphs in the next pages)

p <- list()

for(i in 1:3) {
  p[[i]] <- list()

  p[[i]][[1]] <- ggplot(data = plot1) +
    theme_minimal() +
    facet_wrap(~Sector, nrow = 5, scales="free_y") +
    geom_line(aes(x = Date, y = BEST_EPS.BEST_FPERIOD_OVERRIDE.1GY, color = 
    Sector)) +
    theme(legend.position="none")

  p[[i]][[2]] <- ggplot(data = plot2) +
  theme_minimal() +
  facet_wrap(~Sector, nrow = 5, scales="free_y") +
  geom_line(aes(x = Date, y = eps.rev3mo, color = Sector)) +
  theme(legend.position="none")

  p[[i]][[3]] <- ggplot(data = plot3) +
  theme_minimal() +
  facet_wrap(~Sector, nrow = 5, scales="free_y") +
  geom_line(aes(x = Date, y = eps.rev3mo, color = Sector)) +
  theme(legend.position="none")

}

print(p)

dev.off()

I apologise in advance as this is my first time using ggplot2. Really appreciate and thanks in advance for the help.

1 Answers1

2

Maybe this helps,

enter image description here

library(ggplot2)
library(gridExtra)

page1 <- replicate(4, ggplot(), simplify = FALSE)
other <- replicate(3, replicate(6, ggplot(), simplify = FALSE), simplify = FALSE)

pdf("multipage.pdf", width=6, height = 4)
grid.arrange(grobs = page1, ncol=2)
print(marrangeGrob(grobs = unlist(other, recursive = FALSE), ncol=3,nrow=2))
dev.off()
baptiste
  • 75,767
  • 19
  • 198
  • 294