简体   繁体   English

在IPython笔记本中使用rpy2?

[英]using rpy2 with IPython notebooks?

Is it possible to use rpy2 (calling ggplot2) with IPython notebooks, and then save them (and share on NBViewer like other notebooks http://nbviewer.ipython.org/ )? 是否可以在IPython笔记本中使用rpy2(调用ggplot2),然后保存它们(和其他笔记本http://nbviewer.ipython.org/一样在NBViewer上共享)? Is there any challenge in having the rpy2 ggplots appear in the notebook and/or interactively? 让rpy2 ggplots出现在笔记本中和/或交互式是否有任何挑战? It would be helpful if someone could provide an example session and its output of making a ggplot2 figure within a notebook using rpy2 in IPython. 如果有人能够在IPython中使用rpy2提供示例会话及其在笔记本中制作ggplot2数字的输出,将会很有帮助。

This was written without looking the code in rmagic. 这是在没有查看rmagic中的代码的情况下编写的。 They have have a more clever way to do it (I have 11 lines of code). 他们有一个更聪明的方法(我有11行代码)。

import uuid
from rpy2.robjects.packages import importr 
from IPython.core.display import Image

grdevices = importr('grDevices')
def ggplot_notebook(gg, width = 800, height = 600):
    fn = '{uuid}.png'.format(uuid = uuid.uuid4())
    grdevices.png(fn, width = width, height = height)
    gg.plot()
    grdevices.dev_off()
    return Image(filename=fn)

To try it: 尝试一下:

from rpy2.robjects.lib import ggplot2
from rpy2.robjects import Formula
datasets = importr('datasets')
mtcars = datasets.__rdata__.fetch('mtcars')['mtcars']
p = ggplot2.ggplot(mtcars) + \
    ggplot2.aes_string(x='mpg', y='cyl') + \
    ggplot2.geom_point() + \
    ggplot2.geom_smooth() + \
    ggplot2.facet_wrap(Formula('~ am'))

ggplot_notebook(p, height=300)

It's possible with the rmagic extension, which uses rpy2. rmagic扩展可以使用rpy2。 You seem to need to print() the figure to show it, though. 你好像需要print()图来显示它。 Here's an example session: http://nbviewer.ipython.org/5029692 这是一个示例会话: http//nbviewer.ipython.org/5029692

If you prefer to use rpy2 directly, it must be possible. 如果您希望直接使用rpy2,则必须可以。 Have a look at the rpy2 documentation for ggplot2 . 看看ggplot2的rpy2文档 To get it into the notebook, you can draw to a PNG/SVG device, then read it from the Python side (this is what rmagic does). 要将它放入笔记本中,您可以绘制到PNG / SVG设备,然后从Python端读取它(这就是rmagic所做的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM