python - Jupyter 笔记本 rpy2 Rmagics : How to set the default plot size?

标签 python r plot jupyter-notebook rpy2

我在 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/

相关文章:

python - 根据另一个不是索引数组的数组中的值从 numpy 数组中选择元素

r - 分配多个环境

Bookdown 文档中的 CSS 自定义

python - 使用 Matloptlib 将图像(只有内容,没有坐标轴或其他任何东西)保存到文件中

python - 在 Python 中选择不包括扩展名的路径的基本名称部分的最佳方法是什么?

python - 为什么我的 weakrefs 在指向一个方法时死在水中?

r - 函数可以通过tryCatch和好友粉碎吗?

python - 我有一张星系图像,我只想绘制第 500 行

r - 在 R 中的应用结构化循环中使用计数器

python - python抽象基类是否应该从对象继承