简体   繁体   中英

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/ )? Is there any challenge in having the rpy2 ggplots appear in the notebook and/or interactively? 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.

This was written without looking the code in rmagic. They have have a more clever way to do it (I have 11 lines of code).

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. You seem to need to print() the figure to show it, though. Here's an example session: http://nbviewer.ipython.org/5029692

If you prefer to use rpy2 directly, it must be possible. Have a look at the rpy2 documentation for ggplot2 . 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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