1

I'm working in a Jupyter notebook with Python 2 and want to use rpy2 to plot a heatmap.

import numpy as np
from rpy2 import robjects
from rpy2.robjects import r, pandas2ri
from rpy2.robjects import Formula, Environment
from rpy2.robjects.vectors import IntVector, FloatVector
from rpy2.robjects.lib import grid
from rpy2.robjects.packages import importr, data
from rpy2.rinterface import RRuntimeError
import warnings


a = np.array([1.5,2.3])
b = np.array([4.2,5.1])
c = np.array([[0.3, 0.6],[0.6, 0.3]])

r.image.plot(a,b,c)

gives me the error

AttributeError: 'SignatureTranslatedFunction' object has no attribute 'plot'

How do I properly pass the parameters into this function? Specs: rpy2 2.5.6 with R3.3.3 and Python 2.7

1 Answer 1

2

That doesn't work because image.plot apparently comes from the package fields. Using image from base R's graphics library, do e.g. this:

import numpy as np
from rpy2.robjects.packages import importr
from rpy2.rinterface import RRuntimeError
import rpy2.robjects.numpy2ri
from IPython.display import Image, display
from rpy2.robjects.lib import grdevices

rpy2.robjects.numpy2ri.activate()
grf = importr('graphics')

a = np.array([1.5,2.3])
b = np.array([4.2,5.1])
c = np.array([[0.3, 0.6],[0.6, 0.3]])

with grdevices.render_to_bytesio(grdevices.png, width=1024, height=896, res=150) as img:
    grf.image(a, b, c)
display(Image(data=img.getvalue(), format='png', embed=True))

gives enter image description here

To use image.plot, you'd have to run

fields = importr('fields')

and replace grf.image(a, b, c) with fields.image.plot(a, b, c)

Sign up to request clarification or add additional context in comments.

9 Comments

Thanks for the response! I can't run "from rpy2.robjects.lib import grdevices" though, it says "ImportError: cannot import name grdevices." However, I can run 'grdevices = importr('grDevices')" but it doesn't have the "render_to_bytesio" function you used. I am using rpy2 2.5.6 with R3.3.3 and Python 2.7
In fact it's telling me that "rpy2.robjects.lib" can only be completed with "grid" -- I'm not sure what grid even is
what exactly does the message say? grid is an R-package!
The message says "ImportError: cannot import name grdevices."
But I definitely have more R packages (like fields!)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.