在ggplot中拟合二次曲线

时间:2017-03-13 12:48:07

标签: r ggplot2 quadratic

这是我的样本数据。我想在单个图中对y1y2进行绘制。这就是我所做的:

x1

我想为y1和y2插入一条二次线对x。我这样做了:

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) 

它引发了一个错误:

p + stat_smooth(method = "lm", formula = y ~ x + I(x^2), size = 1)

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

我是如何在R中实现这一目标的?

由于

1 个答案:

答案 0 :(得分:17)

您应该添加两个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)

enter image description here