7

I'm learning to use rpy2 in Jupyter notebook. I'm having troubles with the plotting. When I use this example from the rpy2 docs for interactive work:

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 opens a new window with the plot. The window "title" reads: R Graphics: Device 2 (ACTIVE) (Not Responding). My Jupyter kernel is active. When I try to close the window with the plot, windows claims that python.exe is not responsing and if I force close then the jupyter kernel restarts.

First: How can I make rpy2 plot inline? Second: If inline plotting is not possible, how to get the plot in a window without python.exe becoming unresponsive?

Artturi Björk
  • 3,643
  • 6
  • 27
  • 35

3 Answers3

3

It seems that this is the answer to your question: 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))
cs224
  • 328
  • 2
  • 12
2

I think the cleanest solution is to simply use the %R magic function. It used to be part of IPython, but got moved to rpy2, so you have to load it as an extension first:

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

plots a histogram to the Jupyter console.

nth
  • 1,442
  • 15
  • 12
1

This is slightly more sopthisticated version of Christian's answer which wraps the plotting and inline embedding into the same context manager:

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

Usage:

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