FairyOnIce
FairyOnIce

Reputation: 2614

Create R plot containing multiple panels where each panel is saved as .png/.pdf

I want to create a big plot which contains four subplots made by plot() function. All the subplots are saved as png/pdf file format. Is there way in R to import these plots to R then create a big plot that contains all the subplots?

Upvotes: 1

Views: 2318

Answers (2)

SlowLearner
SlowLearner

Reputation: 7997

Would it not be easier to fix the problem at source by creating each plot, laying them out together then saving them as one file? The grid layout functions should work with the base plot function as far as I can tell. Here's a simple example using ggplot2. If you use ggplot you could perhaps also use the facet functions. Code follows after image.

screenshot

library(ggplot2)
library(grid)

set.seed(23456)
mydf <- data.frame(mydate = seq(as.Date('2012-01-01'), as.Date('2012-12-01'), by = '1 month'),
                   run1 = runif(12, 100, 200),
                   run2 = runif(12, 300, 400),
                   run3 = runif(12, 1000, 2000),
                   run4 = runif(12, 2000, 3000))

p1 <- ggplot(data = mydf) +
         geom_line(aes(x = mydate, y = run1))

p2 <- ggplot(data = mydf) +
         geom_line(aes(x = mydate, y = run2))

p3 <- ggplot(data = mydf) +
         geom_line(aes(x = mydate, y = run3))

p4 <- ggplot(data = mydf) +
         geom_line(aes(x = mydate, y = run4))


png(filename = paste("multipleplot.png", sep = ""), width = 600, height = 600, units = "px", res = NA)
grid.newpage()
pushViewport(viewport(layout = grid.layout(2, 2, widths = c(300, 300))))

vplayout <- function(x, y)
    viewport(layout.pos.row = x, layout.pos.col = y)

print(p1, vp = vplayout(1,1))
print(p2, vp = vplayout(1,2))
print(p3, vp = vplayout(2,1))
print(p4, vp = vplayout(2,2))
dev.off()

Upvotes: 1

IRTFM
IRTFM

Reputation: 263331

The 'grImport' package has functions to read pdf files, convert to RGML and then import for use within the grid graphics framework.

The 'png' package has a readPNG function.

And as thelatemail is suggesting if you have both the data and the code that created these plots, you may want either to look at the layout function or to use par with arguments mfrow, mfcol, or mfg.

Upvotes: 1

Related Questions