我在 Jupyter 笔记本中使用 %%R
细胞魔法。我知道您可以为每个单元格设置绘图大小,例如:
%%R -w 800 -h 600
但我想为整个笔记本/R session 设置一个默认值。
我看过the documentation , 见过 this blog post on the R Jupyter Notebook Kernel ,并看过Plot Size - Using ggplot2 in IPython Notebook (via rmagic)关于按单元格设置绘图大小,但除非我错过了一些明显的东西,否则似乎没有办法为 R 魔法中的绘图设置默认绘图大小。
这可能吗?是否有隐藏设置,或者必须为每个单元格单独设置 -w
和 -h
?
最佳答案
老问题,但我只是有同样的痒,找到了这个页面,然后设法抓到了它,所以希望这对某人有用。
解决方法是猴子修补 rpy2
,它直接调用 R 的 png
方法,而无需设置默认参数。请注意,这种方法通常是一个坏主意,而且很脆弱,但无法避免。为 rpy2
提出一个包含默认参数机制的功能请求可能是值得的。
下面是猴子补丁:
# 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
关于python - Jupyter 笔记本 rpy2 Rmagics : How to set the default plot size?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40745163/