将python对象传递给rpy2中的R函数

时间:2018-01-31 09:08:00

标签: python r rpy2

我在使用Python 2的Jupyter笔记本中工作,并希望使用rpy2绘制热图。

$.ajax({
   type: 'POST',
   url: c.cls.server,
   data: {
     mode: 'Perspective',
     id: c.uid,
     points: points,
     width: c.cls.canvasMaxWidth,
     caseid: caseid,
     imgtype: imgtype
   },
   async: false,
   timeout: 5000,
   contentType: "application/x-www-form-urlencoded",
   success: function(e) {
     result = e;
   },
   error: function(r, s, e) {
     c.onError(status + e);
   }
 });

给我错误

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)

如何将参数正确传递到此函数中?规格:rpy2 2.5.6,R3.3.3和Python 2.7

1 个答案:

答案 0 :(得分:2)

这不起作用,因为image.plot显然来自包fields。使用基础R的image库中的graphics,例如这样:

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

给出enter image description here

要使用image.plot,您必须运行

fields = importr('fields')

并将grf.image(a, b, c)替换为fields.image.plot(a, b, c)