Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop in R to create and save series of ggplot2 plots with specified names

Tags:

loops

r

ggplot2

I have a data frame in R with POSIXct variable sessionstarttime. Each row is identified by integer ID variable of a specified location . Number of rows is different for each location. I plot overall graph simply by:

myplot <- ggplot(bigMAC, aes(x = sessionstarttime)) + geom_freqpoly()

Is it possible to create a loop that will create and save such plot for each location separately?
Preferably with a file name the same as value of ID variable?
And preferably with the same time scale for each plot?

like image 462
radek Avatar asked Jul 06 '10 22:07

radek


2 Answers

Not entirely sure what you're asking but you can do one of two things.

a) You can save each individual plot in a loop with a unique name based on ID like so:

ggsave(myplot,filename=paste("myplot",ID,".png",sep="")) # ID will be the unique identifier. and change the extension from .png to whatever you like (eps, pdf etc).

b) Just assign each plot to an element of a list. Then write that list to disk using save That would make it very easy to load and access any individual plot at a later time.

like image 81
Maiasaura Avatar answered Nov 15 '22 09:11

Maiasaura


I am not sure if I get what you want to do. From what I guess, i suggest to write a simple function that saves the plot. and then use lapply(yourdata,yourfunction,...) . Since lapply can be used for lists, it´s not necessary that the number of rows is equal.

HTH

use something like this in your function:

    ggsave(filename,scale=1.5)
like image 30
Matt Bannert Avatar answered Nov 15 '22 10:11

Matt Bannert