Fitting a quadratic curve in ggplot

后端 未结 1 1931
失恋的感觉
失恋的感觉 2021-01-04 01:31

This is my sample data. I want to plot both y1 and y2 against x1 in a single plot. This is what I did:

library(ISLR)
l         


        
相关标签:
1条回答
  • 2021-01-04 01:59

    You should add two stat_smooth() calls and add aes() to show which y to use.

    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")
    

    Or make long format table and then you will need just one call of stat_smooth() and 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)
    

    0 讨论(0)
提交回复
热议问题