0

I'm doing a plot in R using a simple layout:

layout(matrix(c(1,2),1,2))

After I have drawn the two sides of the plot, I need to return to the first to draw two more lines (that span to the other side, and only after drawing the second side I will know the right coordinates).

I know I can use frame() to move between frames, but it only goes forward, and when it returns to the beginning, it clears the whole drawing. Is it possible to move a frame back?

Rodrigo
  • 4,706
  • 6
  • 51
  • 94
  • 3
    `dev.set(dev.prev())` – Ricardo Saporta Oct 07 '14 at 20:56
  • 2
    @RicardoSaporta Do you mean like `layout(matrix(c(1,2),1,2)); plot(1:10, 1:10); plot(10:1, 1:10); dev.set(dev.prev()); abline(h=5)`? That doesn't seem to work (as in I expected the `abline` to appear in the first plot). `dev.set()` seems to control the devices, but `layout` doesn't change devices as far as I can tell so I don't understand why that would work. Can you give a more complete answer below to test it? – MrFlick Oct 07 '14 at 21:26
  • It would probably be a better idea to post a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output. It may be possible to do what you want without returning to the previous frame. – MrFlick Oct 07 '14 at 21:47

2 Answers2

2

Despite the warnings you can use par(mfg=...) to control the focus of plotting when using layout:

layout(matrix(1:4,2,2)); 
plot(1:10, 1:10);
plot(10:1, 1:10);  
par(mfg=c(1,1)); 
abline(h=5)

I would not have expected dev.set(dev.prev()) to work since I think it's all being written to the same device.

IRTFM
  • 258,963
  • 21
  • 364
  • 487
0

IRTFM is correct, but if the different graphs in the layout have different scaling, then you may have to reset the scale after changing the target frame for new graphical elements added to the previous frame to be scaled correctly.

Modifying IRTFM's example a bit to demonstrate, note that this code does not produce the expected result of a horizontal line in the first graph at a value of 5 due to inconsistent scaling.

layout(matrix(1:4,2,2))
plot(1:10, 1:10)
plot(12:1, 1:12)
par(mfg=c(1,1))
abline(h=5)

However, the following code produces the expected result of a horizontal line in the first graph at a value of 5 due to resetting the appropriate scale before adding the abline element.

layout(matrix(1:4,2,2))
plot(1:10, 1:10)
plot(12:1, 1:12)
par(mfg=c(1,1))
plot.window(xlim = c(1, 10), ylim = c(1, 10))
abline(h=5)

Changing to an arbitrary frame in a layout is possible with the "mfg" graphics parameter, but you will need to reset the window scaling for any added elements to appear on the same scale as previously established. Same goes for use of mfrow or mfcol graphics parameters to create multipanel graphs.