Haroon Lone
Haroon Lone

Reputation: 2949

Save grid plots drawn within a loop automatically in R

I have time-series data of 6 months and I want to plot it in grid manner like this enter image description here

As a reproducible example, let us the following code:

library(xts)
seq <- seq(as.POSIXct("2015-03-01"),as.POSIXct("2015-03-30"), by = "60 mins")
timeseries_ob <- xts(data.frame(rnorm(length(seq),30,2)),seq)
looplength <- length(unique(.indexmday(timeseries_ob)))
par(mfrow=c(4,3))
pdf("temp.pdf")
for(i in 1:looplength){
  daydata <- timeseries_ob[.indexmday(timeseries_ob)%in%i,]
  plot(daydata,type="l",main="")
}
dev.off()

With this code, plots get automatically saved, but they are not in the grid manner. Each plot gets saved in different page of pdf. Is there any other way to save above plots in a grid manner automatically.

Note: I don't want to use facet_grid, because these plots are generated within a loop and I believe with ggplot it might become complex to draw.

Upvotes: 0

Views: 211

Answers (1)

J_F
J_F

Reputation: 10362

You have to use the par(mfrow = c(4,3)) command between pdf(...) and dev.off().
This will lead to your desired result!

Upvotes: 2

Related Questions