Monklife Monklife - 3 months ago 31
R Question

How to get plots in several pdf pages using ggplot2

Hello stackoverflow community,

I need help in figuring out how 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. Any help will be appreciated!!!

Answer

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

Comments