Reputation: 3412
I'm using the %%R
cell magics in Jupyter notebooks. I'm aware that you can set the plot size for each cell with, e.g.:
%%R -w 800 -h 600
But I would like to set a default for the whole notebook/R session.
I've looked at the documentation, seen this blog post on the R Jupyter Notebook Kernel, and have seen Plot Size - Using ggplot2 in IPython Notebook (via rmagic) on setting the plot size by cell, but unless I've missed something obvious, there doesn't appear to be a way to set the default plot size for plots in R magics.
Is this possible? Is there a hidden setting, or must -w
and -h
be set for every cell individually?
Upvotes: 11
Views: 2335
Reputation: 31
Old question, but I just had the same itch, found this page, and then managed to scratch it, so hopefully this is useful to someone.
The workaround is monkey-patching rpy2
which calls R's png
method directly without a way to set default arguments. Note that this approach is usually a Bad Idea, and brittle, but cannot be avoided. It would probably be worthwhile to make a feature request for rpy2
to include a mechanism for default arguments.
So here goes the monkey-patching:
# these are the defaults we want to set:
default_units = 'in' # inch, to make it more easily comparable to matpplotlib
default_res = 100 # dpi, same as default in matplotlib
default_width = 10
default_height = 9
# try monkey-patching a function in rpy2, so we effectively get these
# default settings for the width, height, and units arguments of the %R magic command
import rpy2
old_setup_graphics = rpy2.ipython.rmagic.RMagics.setup_graphics
def new_setup_graphics(self, args):
if getattr(args, 'units') is not None:
if args.units != default_units: # a different units argument was passed, do not apply defaults
return old_setup_graphics(self, args)
args.units = default_units
if getattr(args, 'res') is None:
args.res = default_res
if getattr(args, 'width') is None:
args.width = default_width
if getattr(args, 'height') is None:
args.height = default_height
return old_setup_graphics(self, args)
rpy2.ipython.rmagic.RMagics.setup_graphics = new_setup_graphics
Upvotes: 1
Reputation: 11565
Good question. Currently I think that the default are the R default settings, but it would make sense to use jyputer defaults (if there are any - I'd need look that up).
The following hack would work... if "R magic" was using the default plotting settings in R. Unfortunately it does not.
%%R
my_png <- function(...) {
lst <- as.list(...)
if (is.null(lst$w)) {
lst$w <- 1000 # default width
}
if (is.null(lst$h)) {
lst$h <- 700 # default height
}
do.call("png", lst)
}
options(device=my_png)
It would make sense to open an issue on the rpy2 tracker on bitbucket to request the feature.
Upvotes: 0