在ggplot中拟合二次曲线

24

这是我的示例数据。我想在一个图中绘制y1y2相对于x1的关系。我做了以下操作:

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) 

我希望为y1和y2针对x插入一个二次线。我已经这样做了:
p + stat_smooth(method = "lm", formula = y ~ x + I(x^2), size = 1)

它抛出了一个错误:

Warning message:
Computation failed in `stat_smooth()`:
variable lengths differ (found for 'x')  

除此之外,stat_smooth命令只会生成一条二次线,而我需要分别为y1和y2生成两条二次线。
我该如何在R中实现这个目标?
谢谢。
1个回答

43

你应该添加两个stat_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_smooth()geom_point()

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)

输入图片描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接