Grill parameter settings using rpy2

I am trying to plot a heat map or color intensity using data from a numpy array using rpy2 and a grid. I am using python 2.6.2, R 2.10.1, rpy2 2.1.9, not sure which version of the lattice. I got it working perfectly, except that I need to change the default lattice setting for the color ramp used to plot the levels of the corresponding variable (z). In particular, I want a grayscale instead of the default magenta punch. Here is the code for creating a dummy frame and creating a gray scale scale for vanilla R:

library(lattice)

x <- rep(seq(1,10), each=10)
y <- rep(seq(1,10), 10)
z <- abs(rnorm(100))
z <- z/max(z)
df <- data.frame(x=x, y=y, z=z)

grayvector <- gray(seq(0,1,1/100))

foo <- levelplot(z ~ x * y, data=df, col.regions = grayvector)
print foo

With rpy2, I cannot set the col.regions argument. According to the documentation, rpy2 should convert any. characters in the arguments to _. However, this does not work, since using col_regions ignores the argument. Here is the python code that creates levelplot, but without shades of gray:

from __future__ import division
import rpy2.robjects as ro
from rpy2.robjects.packages import importr
r = ro.r
lattice = importr("lattice")

grayvector = r.gray( r.seq(0, 1, 1/100))   
x = r.rep(r.seq(1,10), each=10)
y = r.rep(r.seq(1,10), 10)
z = r.abs(r.rnorm(100))

df = {'x': x, 'y' :y, 'z':z}
df = ro.DataFrame(foo)

formula = ro.Formula('z ~ x * y')
formula.getenvironment()['z'] = df.rx2('z')
formula.getenvironment()['y'] = df.rx2('y')
formula.getenvironment()['z'] = df.rx2('z')

foo = lattice.levelplot(formula, data=df, col_regions = grayvector)
print foo

Does anyone know how to use lattice function arguments with. in them in rpy2?

+3
source share
1 answer

You need to specify the argument mapping manually:

from rpy2.robjects.functions import SignatureTranslatedFunction
lattice = importr("lattice")
lattice.levelplot = SignatureTranslatedFunction(lattice.levelplot,
                                                init_prm_translate={'col_regions': 'col.regions'})
foo = lattice.levelplot(formula, data=df, col_regions=grayvector)

And also check this out: http://rpy.sourceforge.net/rpy2/doc-2.2/html/robjects_functions.html

It is important to understand that the translation is carried out by checking the signature of the function R and not much can be guessed from R ellipsis "... if any.

+3
source

Source: https://habr.com/ru/post/1786700/


All Articles