[R] plotting and saving diagrams automatically

David Winsemius dwinsemius at comcast.net
Sun Dec 23 00:18:39 CET 2012


On Dec 22, 2012, at 12:34 PM, eliza botto wrote:

> 
> [if the format of my email is changed or is difficult to understand, a text file is attached for easy understanding]Dear useRs,
> i was wondering that if its possible in R to automatically generate plots and get it saved at the desired location? i have 
> data of cancer patients, from about 1000 cities around the world. i have converted that data into a list (called tcp) and 
> that list has 1000 sublists. the sublists are named, according to the city name. the orientation of the sublists are as 
> follow
> $ Tokyo
> month	2009	2010	20111	515	356	1212	444	145	1203	478	147	1244	147	236	1245	785	142	1256	478	111	4787	478	856	7858	147	786	4569	147	122	12310	786	123	14711	123	787	25812	110	898	369
> $ Nagoya 
> month	1955	1956	19641	512	444	7712	441	145	4703	445	156	4744	145	236	7845	785	147	4456	447	178	9887	478	980	8858	189	886	7869	145	722	18310	756	123	16711	145	127	24812	110	128	259
> what i wanted to do is the following
> 
> 1- drawing curve of each column in the sublist against the first column of each sublist(month vs patients). 
> 2- drawing average curve of each city over the yearly curves. (for example, for tokyo, overlay average curve of 2009,2010 
> and 2011 on already generated 3 curves).
> 3-saving the resulting diagram on a suitable location in my pc.
> i used the following commands for these three operations
>> jpeg("C:/world survey/ Tokyo.jpg")>matplot(tcp$ Tokyo[,-1], type = "l", col="grey", xlab="TIME(month)", ylab="patients")>apply(Tokyo,1,mean)>data.frame(Tokyo)>avgTokyo<-as.matrix(Tokyo, ncol=1)>lines(avgTokyo, lwd = 2)
> As as you can see that i have 1000 cities to work on, isnt there any other suitable way of doing that??i am interested in knowing about "function" command. because when i used the following command 
>> lapply(seq_along(tcp), function(i) matplot(tcp[[i]][,1],tcp[[i]][,-1], type="l",col="grey"))
> i did plot every city' diagram but didnt save it anywhere.
> Could you please guide me how to plot and save simultaneously all the firgure in one go?

The 'pdf' function would allow you to make multi-page objects, arguably more useful than the startegy you are proposing. Or you could use your loop to construct names for 1000 separate jpeg files.

lapply( names(tcp), function(i) filnam <- paste0(i, ".jpg")
                                 jpeg(filnam)
                                  matplot(tcp[[i]][,1],tcp[[i]][,-1], type="l",col="grey")
                                  dev.off()
      )

If you didn't use the names you will not be able to recover them inside the function, since only the object itself is passed.
-- 

David Winsemius
Alameda, CA, USA




More information about the R-help mailing list