简体   繁体   中英

How to plot regression line with rpy2

In R, one can use the following command for plotting regression line:

res=lm(height~age)
abline(res)

As suggested by http://msenux.redwoods.edu/math/R/regression.php

How can I do the same thing with rpy2? I tried

from rpy2 import robjects
r = robjects.r
r.png('test.png')
x = range(10)
y = range(10)
r.plot(x, y)
r.abline(r.lm(x, y))

but got complained by rpy2:

Error in formula.default(object, env = baseenv()) : invalid formula
Traceback (most recent call last):
  File "plot_ratio_price.py", line 34, in <module>
    r.abline(r.lm(x, y))
  File "/Library/Python/2.7/site-packages/rpy2/robjects/functions.py", line 82, in __call__
    return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/rpy2/robjects/functions.py", line 34, in __call__
    res = super(Function, self).__call__(*new_args, **new_kwargs)
rpy2.rinterface.RRuntimeError: Error in formula.default(object, env = baseenv()) : invalid formula

Any hints? Thanks!

Following on to @joran's comment, Rpy2 requires you provide a special object for the formula. The documentation says that the class robjects.Formula represents an R formula . So prior to your last line (the call to r.abline ) you need to create a Formula object and pass that in to your lm() call.

By the way, your problem code looks close enough to the rpy2 example that you might consider using it as a template:

import array
from rpy2.robjects import IntVector, Formula
from rpy2.robjects.packages import importr
stats = importr('stats')

x = IntVector(range(1, 10))
y = IntVector(range(1, 10))

fmla = Formula('y ~ x')
env = fmla.environment
env['x'] = x
env['y'] = y

fit = stats.lm(fmla)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM