Search code examples
rplotwarningspar

Warnings when restoring graphical parameters


I am writing my first R package and currently working on a function to make a plot using some particular graphical parameters. I want the user defined graphical parameters to get restored after the plot is made but always get same warning messages:

opar <- par()
par(oma = c(5, 4, 0, 0) + 0.1, mar = c(0, 0, 1, 1) + 0.1)
par(opar)

Warning messages:
1: In par(opar) : graphical parameter "cin" cannot be set
2: In par(opar) : graphical parameter "cra" cannot be set
3: In par(opar) : graphical parameter "csi" cannot be set
4: In par(opar) : graphical parameter "cxy" cannot be set
5: In par(opar) : graphical parameter "din" cannot be set
6: In par(opar) : graphical parameter "page" cannot be set

Is there a better way of doing that? I know the suppressWarnings() function but 1. I don't want the messages to get hided and 2. if the function is called two times, a warning message appears:

> There were 12 warnings (use warnings() to see them)

Solution

  • The ... in my comments were merely a placeholder for whatever you intend to put in there. (I tend to think lots of code in comments can be difficult to read, so I just shortened it.)

    Literally:

    opar <- par(oma = c(5, 4, 0, 0) + 0.1, mar = c(0, 0, 1, 1) + 0.1)
    # other code that uses those settings
    # when you are ready to reset to the original settings for oma and mar,
    par(opar)
    

    This is provided in a similar example in the doc, ?par.

    One example of how doing it this way is different from saving all of the parameters with opar <- par(no.readonly=TRUE) is that this only reset/restores the parameters that you explicitly changed. It is feasible that others might have changed as a side-effect of other actions (outside of this intent).