给出如下数据框:
df1= data.frame(x = c(1:50))
df1$val=df1$x*(-0.35)
我使用了ggplot2并使用命令
添加了回归线t=ggplot(df1, aes(x=val, y=x))+geom_smooth(method=lm) + geom_point()
为了添加等式和r值,我尝试了这个问题的代码Adding Regression Line Equation and R2 on graph
但我收到了错误
Error in terms.formula(formula, data = data) :
'data' argument is of the wrong type
有关如何解决此问题的任何想法?
修改
我使用的代码
my_sts <- function(df1){
m <- lm(df1$x ~ df1$val, df1);
eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
list(a = format(coef(m)[1], digits = 2),
b = format(coef(m)[2], digits = 2),
r2 = format(summary(m)$r.squared, digits = 3)))
as.character(as.expression(eq));
}
tgen = t + geom_text(x = -10, y = 50, label = eq(df1), parse = TRUE)
答案 0 :(得分:1)
这是从控制台会话中复制的。我纠正了两件我认为错误的事情:1)正如我在评论中提到的那样,当你有数据参数时,你不应该在公式中使用df1 $,2)我认为你的意思是使用my_sts(df1)
> df1= data.frame(x = c(1:50))
> df1$val=df1$x*(-0.35)
> my_sts <- function(df1){
+ m <- lm(x ~ val, df1);
+ eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
+ list(a = format(coef(m)[1], digits = 2),
+ b = format(coef(m)[2], digits = 2),
+ r2 = format(summary(m)$r.squared, digits = 3)))
+ as.character(as.expression(eq));
+ }
> t=ggplot(df1, aes(x=val, y=x))+geom_smooth(method=lm) + geom_point()
> tgen = t + geom_text(x = -10, y = 50, label = eq(df1), parse = TRUE)
Error in layer(data = data, mapping = mapping, stat = stat, geom = GeomText, :
could not find function "eq"
> tgen = t + geom_text(x = -10, y = 50, label = my_sts(df1), parse = TRUE)
Warning message:
In summary.lm(m) : essentially perfect fit: summary may be unreliable
> print(tgen)
似乎打印得很好:注意x和y角色是相反的,因此系数是建模因子的倒数。