【问题标题】:How to plot (inline) with rpy2 in Jupyter notebook?如何在 Jupyter 笔记本中使用 rpy2 绘图(内联)?
【发布时间】:2017-08-23 22:16:11
【问题描述】:

我正在学习在 Jupyter 笔记本中使用 rpy2。我在绘图方面遇到了麻烦。当我使用 rpy2 docs 中的这个示例进行交互工作时:

from rpy2.interactive import process_revents
from rpy2.robjects.packages import importr
from rpy2.robjects.vectors import IntVector
process_revents.start()

graphics = importr("graphics")
graphics.barplot(IntVector((1,3,2,5,4)), ylab="Value")

Jupyter 会打开一个包含绘图的新窗口。窗口“标题”显示:R Graphics: Device 2 (ACTIVE) (Not Responding)。我的 Jupyter 内核处于活动状态。当我尝试关闭带有绘图的窗口时,windows 声称 python.exe 没有响应,如果我强制关闭,则 jupyter 内核将重新启动。

首先:如何使 rpy2 绘图内联?第二:如果无法进行内联绘图,如何在没有python.exe无响应的情况下在窗口中进行绘图?

【问题讨论】:

    标签: python r plot jupyter rpy2


    【解决方案1】:

    看来这就是你问题的答案:https://bitbucket.org/rpy2/rpy2/issues/330/ipython-plotting-wrapper

    with rpy2.robjects.lib.grdevices.render_to_bytesio(grdevices.png, width=1024, height=896, res=150) as img:
        graphics.barplot(IntVector((1,3,2,5,4)), ylab="Value")
    IPython.display.display(IPython.display.Image(data=img.getvalue(), format='png', embed=True))
    

    【讨论】:

      【解决方案2】:

      我认为最干净的解决方案是简单地使用 %R 魔术函数。它曾经是 IPython 的一部分,但被移到了rpy2,所以你必须先将它作为扩展加载:

      %load_ext rpy2.ipython
      A = np.random.normal(100)
      %R -i A hist(A)
      

      在 Jupyter 控制台上绘制直方图。

      【讨论】:

        【解决方案3】:

        这是 Christian's answer 的稍微复杂的版本,它将绘图和内联嵌入包装到同一个上下文管理器中:

        from contextlib import contextmanager
        from rpy2.robjects.lib import grdevices
        from IPython.display import Image, display
        
        @contextmanager
        def r_inline_plot(width=600, height=600, dpi=100):
        
            with grdevices.render_to_bytesio(grdevices.png, 
                                             width=width,
                                             height=height, 
                                             res=dpi) as b:
        
                yield
        
            data = b.getvalue()
            display(Image(data=data, format='png', embed=True))
        

        用法:

        with r_inline_plot(width=1024, height=896, dpi=150):
            graphics.barplot(IntVector((1,3,2,5,4)), ylab="Value")
        

        【讨论】:

          猜你喜欢
          • 2013-10-24
          • 2022-07-21
          • 2021-07-27
          • 2021-03-22
          • 1970-01-01
          • 2015-03-01
          • 2015-10-15
          相关资源
          最近更新 更多