1

I am trying to create some plots in a loop in the following way: What I want to achieve is to plot the plots below each other into one single plot. For this I've read that I could use par(mfrow) but I am unsure where to put it in my loop. At the moment single graphs are created which are divided into two but only the upper part is plotted.

I know that I could do it the following way:

par(mfrow=2:1)
plot(...)
plot(...)

but with this solution I would have to call the plot command everytime for each plot. In the end I would like to have about 20 very narrow plots stacked on top of each other and I don't want to call them everytime. How could I do this independently?

Here is the code I've been using so far:

xy <- structure(list(NAME = structure(c(2L, 2L, 1L, 1L), .Label = c("CISCO", "JOHN"), class = "factor"), ID = c(41L, 41L, 57L, 57L), X_START_YEAR = c(1965L, 1932L, 1998L, 1956L), Y_START_VALUE = c(960L, -45L, 22L, -570L), X_END_YEAR = c(1968L, 1955L, 2002L, 1970L), Y_END_VALUE = c(960L, -45L, 22L, -570L), LC = structure(c(1L, 1L, 2L, 2L), .Label = c("CA", "US"), class = "factor")), .Names = c("NAME", "ID", "X_START_YEAR","Y_START_VALUE", "X_END_YEAR", "Y_END_VALUE", "LC"), class = "data.frame", row.names = c(NA,-4L))
ind <- split(xy,xy$ID)
# Plots
for (i in ind){
  xx = unlist(i[,grep('X_',colnames(i))])
  yy = unlist(i[,grep('Y_',colnames(i))])    
  fname <- paste0(i[1, 'ID'],'.png')
  png(fname, width=1679, height=1165, res=150)
  par(mar=c(6,8,6,5))
  par(mfrow=2:1)
  plot(xx,yy,type='n', xlab=NA, ylab="Value [mm]",ylim = range(c(yy,-.5,.5))) 
  i <- i[,-1]
  segments(i[,2],i[,3],i[,4],i[,5],lwd=2)
  abline(h=0)
  dev.off()
} 

EDIT: Up until now I tried to use an approach by adding the resulting pngs in one plot after they are being created as described here (R: crop multiple pngs and combine them into a single plot), but this approach is not that straightforward because of problems with cropping and output resolution...

Community
  • 1
  • 1
kurdtc
  • 1,551
  • 5
  • 21
  • 39
  • I see you're only calling `plot()` once. That will only make one plot. What do you want in the bottom half? – MrFlick Dec 19 '14 at 05:54
  • @MrFlick Ideally I would have the second plot which is created in the loop in the bottom half. – kurdtc Dec 19 '14 at 06:08
  • Well, it seems like you're asking why the plot isn't appearing, and that would be because you're not writing code to plot it. Am I missing something here? – MrFlick Dec 19 '14 at 06:10
  • 1
    Does [this SO answer](http://stackoverflow.com/questions/26811175/how-to-loop-through-and-produce-plots-on-the-same-page/26811291#26811291) do what you need? – eipi10 Dec 19 '14 at 06:14
  • 4
    just move the mfrow part outside of the loop. oh and the png and dev.off parts too – rawr Dec 19 '14 at 06:18

0 Answers0