user217285
user217285

Reputation: 366

Passing python objects to R functions in rpy2

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

Upvotes: 1

Views: 1322

Answers (1)

erocoar
erocoar

Reputation: 5893

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)

Upvotes: 2

Related Questions