R 在ggplot中拟合二次曲线

R 在ggplot中拟合二次曲线,r,ggplot2,quadratic,R,Ggplot2,Quadratic,这是我的样本数据。我想在一个绘图中,根据x1绘制y1和y2。这就是我所做的: library(ISLR) library(ggplot2) y1<-scale(Auto$horsepower,scale = T,center=T) y2<-scale(Auto$weight,scale = T,center=T) x1<-Auto$mpg df<-data.frame(y1,y2,x1) p<-ggplot(df,aes(x=x1)) + geom_po

这是我的样本数据。我想在一个绘图中,根据
x1
绘制
y1
y2
。这就是我所做的:

library(ISLR)
library(ggplot2)

y1<-scale(Auto$horsepower,scale = T,center=T)
y2<-scale(Auto$weight,scale = T,center=T)
x1<-Auto$mpg
df<-data.frame(y1,y2,x1)

p<-ggplot(df,aes(x=x1)) + 
   geom_point(aes(y = y1), shape = 16) +
   geom_point(aes(y = y2), shape = 2) 
它抛出了一个错误:

Warning message:
Computation failed in `stat_smooth()`:
variable lengths differ (found for 'x')  
除此之外,stat_smooth命令将只放置一条二次线,而我需要两条二次线 对于
y1
y2

我是如何在R中实现这一点的


谢谢

您应该添加两个
stat\u smooth()
调用,并添加
aes()
以显示要使用的
y

ggplot(df,aes(x=x1)) + 
      geom_point(aes(y = y1), shape = 16) +
      geom_point(aes(y = y2), shape = 2) +
      stat_smooth(aes(y = y1),method = "lm", formula = y ~ x + I(x^2), size = 1) +
      stat_smooth(aes(y = y2),method = "lm", formula = y ~ x + I(x^2), size = 1, color = "red")
或者制作长格式表格,然后只需调用一次
stat\u smooth()
geom\u point()

library(tidyr)
df_长%聚集(变量,值,y1:y2)
ggplot(df_long,aes(x1,值,颜色=变量))+
几何点()+
统计平滑(method=“lm”,公式=y~x+I(x^2),大小=1)

ggplot(df,aes(x=x1)) + 
      geom_point(aes(y = y1), shape = 16) +
      geom_point(aes(y = y2), shape = 2) +
      stat_smooth(aes(y = y1),method = "lm", formula = y ~ x + I(x^2), size = 1) +
      stat_smooth(aes(y = y2),method = "lm", formula = y ~ x + I(x^2), size = 1, color = "red")
library(tidyr)
df_long <- df %>% gather(variable, value, y1:y2)

ggplot(df_long, aes(x1, value, color = variable)) +
      geom_point() +
      stat_smooth(method = "lm", formula = y ~ x + I(x^2), size = 1)