【问题标题】:Jupyter Notebook rpy2 Rmagics: How to set the default plot size?Jupyter Notebook rpy2 Rmagics:如何设置默认绘图大小?
【发布时间】:2017-04-06 07:45:39
【问题描述】:

我在 Jupyter 笔记本中使用 %%R 单元魔法。我知道您可以设置每个单元格的绘图大小,例如:

%%R -w 800 -h 600

但我想为整个 notebook/R 会话设置一个默认值。

我看过the documentation,看过this blog post on the R Jupyter Notebook Kernel,并看过Plot Size - Using ggplot2 in IPython Notebook (via rmagic) 按单元格设置绘图大小,但除非我错过了一些明显的东西,否则似乎没有办法为 R 魔法中的绘图设置默认绘图大小。

这可能吗?是否有隐藏设置,或者必须为每个单元格单独设置-w-h

【问题讨论】:

    标签: python r plot jupyter-notebook rpy2


    【解决方案1】:

    好问题。目前我认为默认设置是 R 默认设置,但使用 jyputer 默认设置是有意义的(如果有的话 - 我需要查一下)。

    如果“R 魔法”使用 R 中的默认绘图设置,以下 hack 将起作用。不幸的是它没有。

    %%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)
    

    在 bitbucket 上的 rpy2 跟踪器上打开一个问题以请求该功能是有意义的。

    【讨论】:

    • 嗨 lgautier,感谢您的回答,但是到目前为止,该代码还没有运气;我试过lst$w &lt;- 100lst$h &lt;- 100 没有效果。删除条件 if (is.null(lst$w/h))s 也不起作用。我想知道 Jupyter/rpy2 默认是否会覆盖 R 设置。
    • lst$width/list$height 有和没有list$units &lt;- "px" 也不起作用,看过stat.ethz.ch/R-manual/R-devel/library/grDevices/html/png.html 并尝试了这些。
    • 确实不行。我查看了 rmagic 中的代码,它没有使用 R 默认值。我正在修改答案。
    【解决方案2】:

    老问题,但我也有同样的痒,找到了这个页面,然后设法刮了它,所以希望这对某人有用。

    解决方法是猴子补丁 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-25
      • 2019-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-02
      • 1970-01-01
      • 2018-09-06
      相关资源
      最近更新 更多