r - 将三阶多项式及其方程添加到 r 中的 ggplot 中

标签 r ggplot2

我绘制了以下数据并添加了黄土平滑器。我想在图中添加一个三阶多项式及其方程(包括残差)。有什么建议吗?

set.seed(1410)
dsmall<-diamonds[sample(nrow(diamonds), 100), ]
df<-data.frame("x"=dsmall$carat, "y"=dsmall$price)

p <-ggplot(df, aes(x, y)) 
p <- p + geom_point(alpha=2/10, shape=21, fill="blue", colour="black", size=5)

#Add a loess smoother
p<- p + geom_smooth(method="loess",se=TRUE)

enter image description here

如何添加三阶多项式?我尝试过:

p<- p + geom_smooth(method="lm", se=TRUE, fill=NA,formula=lm(y ~ poly(x, 3, raw=TRUE)),colour="red")

最后如何将三阶多项式方程和残差添加到图中? 我尝试过:

 lm_eqn = function(df){
    m=lm(y ~ poly(x, 3, df))#3rd degree polynomial
    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))
}


data.label <- data.frame(x = 1.5,y = 10000,label = c(lm_eqn(df)))


p<- p + geom_text(data=data.label,aes(x = x, y = y,label =label), size=8,family="Times",face="italic",parse = TRUE)

最佳答案

第 1 部分:要拟合多项式,请使用参数:

  • method=lm - 您的操作正确
  • formula=y ~ poly(x, 3, raw=TRUE) - 即不要将其包含在对 lm 的调用中

代码:

p + stat_smooth(method="lm", se=TRUE, fill=NA,
                formula=y ~ poly(x, 3, raw=TRUE),colour="red")

enter image description here

<小时/>

第 2 部分:添加方程:

  • 修改您的函数lm_eqn()以正确指定lm的数据源 - 您的右括号位于错误的位置
  • 使用 annotate() 来定位标签,而不是 geom_text

代码:

lm_eqn = function(df){
  m=lm(y ~ poly(x, 3), df)#3rd degree polynomial
  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))
}


p + annotate("text", x=0.5, y=15000, label=lm_eqn(df), hjust=0, size=8, 
             family="Times", face="italic", parse=TRUE)

enter image description here

关于r - 将三阶多项式及其方程添加到 r 中的 ggplot 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11949331/

相关文章:

r - 使用 cron 安排 R 脚本

r - 按元素的总和/平均值过滤行

r - 如何过滤R中具有特定值的参与者?

r - 如何在 ggplot 函数中使用以数字开头的列名

递归地更改R中嵌套列表中的名称

r - 一个更通用的函数,用于列表的n个元素中的匹配元素数

r - 如何反转折线图ggplot2 R上的坐标

r - ggplot2线图顺序

R hist 与 geom_hist 断点

r - 更改 ggplot2 中 x Axis 刻度之间的距离