如何在Jupyter笔记本中使用rpy2进行(内联)绘图?

7

我正在学习在Jupyter笔记本中使用rpy2。 我在绘图方面遇到了一些问题。 当我使用rpy2文档中的交互式工作示例时:

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无响应的情况下获取绘图窗口?

3个回答

3

看起来这是你问题的答案: 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控制台绘制一个直方图。


1
这是Christian答案的稍微复杂一些的版本,它将绘图和内联嵌入包含在同一个上下文管理器中:
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")

有没有一种方法可以在显示在笔记本上的同时保存它? - BML

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接