Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put multiple plots with inner plots in a M x N layout without messing up the par()s?

I make a plot within a plot.

(I use curve() here for simplicity, but this also refers to plot().)

curve(exp(x), 0, 1, col=4)
.op <- par(
  fig=c(grconvertX(c(.05, .4), to='ndc'),
        grconvertY(c(2, 2.75), to='ndc')),
  mar=c(1, 1, 1, 1),
  new=TRUE
)
curve(sin(x), 0, 2*pi)
par(.op)

enter image description here

Repeating this in a for loop basically works well. However, when I try use a 2x2 layout, the figures are spread over four different plots instead of being shown on one.

layout(matrix(1:4, 2, 2))
for (i in 1:4) {
  curve(exp(x), 0, 1, col=4)
  .op <- par(
    fig=c(grconvertX(c(.05, .3), to='ndc'),
          grconvertY(c(2, 2.75), to='ndc')),
    mar=c(1, 1, 1, 1),
    new=TRUE
  )
  curve(sin(x), 0, 2*pi)
  par(.op)
}

For some reason the inner par messes up the outer one. I also tried to op <- par(mfrow=); ... par(op) instead of layout, but with same result.

How can I fix that?

like image 472
jay.sf Avatar asked Sep 17 '25 12:09

jay.sf


1 Answers

Try using screen instead.

split.screen(c(2,2))
for (i in 1:4) {
  screen(i)
  curve(exp(x), 0, 1, col=4)
  title(paste("i=",i))

  .op <- par(
    fig=c(grconvertX(c(.05, .3), to='ndc'),
          grconvertY(c(2, 2.75), to='ndc')),
    mar=c(1, 1, 1, 1),
    new=TRUE
  )
  curve(sin(x), 0, 2*pi)
  par(.op)
}

enter image description here

like image 94
Edward Avatar answered Sep 19 '25 04:09

Edward