【问题标题】:Fitting a quadratic curve in ggplot在ggplot中拟合二次曲线
【发布时间】:2017-08-03 11:49:11
【问题描述】:

这是我的示例数据。我想在一个情节中同时绘制y1y2x1。这就是我所做的:

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 命令只会放置一条二次线,而我需要两条二次线 对于y1y2

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

谢谢

【问题讨论】:

    标签: r ggplot2 quadratic


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-02-02
      • 1970-01-01
      • 2020-10-10
      • 2020-12-13
      • 2019-05-11
      • 2014-03-05
      • 1970-01-01
      • 2019-07-31
      • 2021-02-23
      相关资源
      最近更新 更多