Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get plots in several pdf pages using ggplot2

Tags:

r

ggplot2

I need help to process graphs into multiple pdf pages. Here is my current code:

file <- read.csv(file="file.csv") 
library(ggplot2)
library(gridExtra)
library(plyr)

gg1 <- ggplot() +
  geom_line(aes(x=TIME, y=var1, colour = "z1"), file) +
  geom_line(aes(x=TIME, y=var2, colour = "z2"), file) + 
  geom_point(aes(x=TIME, y=var3), file) + facet_wrap( ~ ID, ncol=5)+ 
  xlab("x") +
  ylab("Y") +
  ggtitle(" x ") + scale_colour_manual(name="Legend",
    values=c(z1="red", z2 ="blue")) + theme(legend.position="bottom")   
gg10 = do.call(marrangeGrob, c(gg1, list(nrow=4, ncol=4)))
ggsave("need10.pdf", gg10)

Here is the image created, without splitting my images

enter image description here

I wish to have a code to get my plots in a 4 by 4 layout in multiple pages. The last two lines of my code need adjustment and I do not know how to fix it myself.

like image 416
Monklife Avatar asked Aug 09 '16 19:08

Monklife


People also ask

How do I make multiple plots into one PDF in R?

To save multiple plots to the same page in the PDF file, we use the par() function to create a grid and then add plots to the grid. In this way, all the plots are saved on the same page of the pdf file. We use the mfrow argument to the par() function to create the desired grid.

Which ggplot2 connects multiple operations?

Integrating the pipe operator with ggplot2 The pipe operator can also be used to link data manipulation with consequent data visualization.

How do I show multiple Ggplots together?

The function ggarrange() [ggpubr] provides a convenient solution to arrange multiple ggplots over multiple pages. After specifying the arguments nrow and ncol, ggarrange()` computes automatically the number of pages required to hold the list of the plots. It returns a list of arranged ggplots.


1 Answers

The ggplus wrapper appears to do what you want. I changed a couple of things in the code block below from your original: facet_wrap is commented out, and file is moved to ggplot so that it doesn't have to be re-specified in each geom_*:

gg1 <- ggplot(file) +
  geom_line(aes(x=TIME, y=var1, colour = "z1")) +
  geom_line(aes(x=TIME, y=var2, colour = "z2")) + 
  geom_point(aes(x=TIME, y=var3)) +
  # facet_wrap( ~ ID, ncol=5) +
  xlab("x") +
  ylab("Y") +
  ggtitle(" x ") + 
  scale_colour_manual(name="Legend",
    values=c(z1="red", z2 ="blue"),
    labels=c("X","Y")) +
  theme(legend.position="bottom")   

devtools::install_github("guiastrennec/ggplus")
library(ggplus)
pdf("need10.pdf")
gg10 <- facet_multiple(plot=gg1, facets="ID", ncol = 4, nrow = 4)
dev.off()

enter image description here enter image description here

like image 182
Weihuang Wong Avatar answered Sep 19 '22 06:09

Weihuang Wong