Adding a regression line on a ggplot

前端 未结 5 1410
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 18:54

I\'m trying hard to add a regression line on a ggplot. I first tried with abline but I didn\'t manage to make it work. Then I tried this...

data = data.frame         


        
5条回答
  •  失恋的感觉
    2020-11-29 19:14

    As I just figured, in case you have a model fitted on multiple linear regression, the above mentioned solution won't work.

    You have to create your line manually as a dataframe that contains predicted values for your original dataframe (in your case data).

    It would look like this:

    # read dataset
    df = mtcars
    
    # create multiple linear model
    lm_fit <- lm(mpg ~ cyl + hp, data=df)
    summary(lm_fit)
    
    # save predictions of the model in the new data frame 
    # together with variable you want to plot against
    predicted_df <- data.frame(mpg_pred = predict(lm_fit, df), hp=df$hp)
    
    # this is the predicted line of multiple linear regression
    ggplot(data = df, aes(x = mpg, y = hp)) + 
      geom_point(color='blue') +
      geom_line(color='red',data = predicted_df, aes(x=mpg_pred, y=hp))
    

    # this is predicted line comparing only chosen variables
    ggplot(data = df, aes(x = mpg, y = hp)) + 
      geom_point(color='blue') +
      geom_smooth(method = "lm", se = FALSE)
    

提交回复
热议问题