[英]How to plot regression line with rpy2
In R, one can use the following command for plotting regression line: 在R中,可以使用以下命令绘制回归线:
res=lm(height~age)
abline(res)
As suggested by http://msenux.redwoods.edu/math/R/regression.php 正如http://msenux.redwoods.edu/math/R/regression.php所建议的那样
How can I do the same thing with rpy2? 我怎么能用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: 但被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. 继续@joran的评论之后,Rpy2要求你为公式提供一个特殊的对象。 The documentation says that the class
robjects.Formula
represents an R formula . 文档说
robjects.Formula
类代表一个R公式 。 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. 因此,在您的最后一行(对
r.abline
的调用)之前,您需要创建一个Formula对象并将其传递给您的lm()
调用。
By the way, your problem code looks close enough to the rpy2
example that you might consider using it as a template: 顺便说一句,您的问题代码看起来足够接近您可能考虑将其用作模板的
rpy2
示例:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.