A_Skelton73
A_Skelton73

Reputation: 1190

Creating Multiple Plots in Multiple files with ggplot2 in R

Having an unusual problem with creating multiple files in R with ggplot2.

I've got multiple plots to create for multiple people, so I'm creating all the plots for each person in a pdf. So it goes something like this...

for(i in 1:10)
{
    pdf(paste("person",i,".pdf",sep=""))
    ggplot2(...)+.........
    ggplot2(...)+.........
    ggplot2(...)+.........
    ggplot2(...)+.........
    dev.off()
}

I've verified that all the code to create the plots is working and that creating a single pdf works, no problems there. The problem arises when I try to run the loop, it creates the files, but they're blank. I've tried everything I can think of and can't seem to find any information about this. I've tried in RStudio (Windows) and command line (ubuntu), both create the same issue.

Any insight or an alternative would be appreciated, thanks

Upvotes: 1

Views: 991

Answers (1)

Nate Pope
Nate Pope

Reputation: 1706

You need to use print for each plot want you output into a pdf.

library(ggplot2)
dat = data.frame(x1=rnorm(10), x2=rnorm(10))
for(i in 1:2){
    pdf(paste("person",i,".pdf",sep=""))
    p1 = ggplot(dat, aes(x=x1)) + geom_histogram()
    p2 = ggplot(dat, aes(x=x2)) + geom_histogram()
    print(p1)
    print(p2)
    dev.off()
    }

Upvotes: 3

Related Questions