Home > Net >  How can I portray my lm() model across different ggplot scatterplot differently?
How can I portray my lm() model across different ggplot scatterplot differently?

Time:12-07

I am currently regressing GDP on multiple factors (7 different variables to be exact), My x variable is quarterly Dates (2006-Q1 to 2020-Q4). I need need to plot my scatter plot for the GDP with Date and plot my lm() linear line on top of it. I can not use geom_smooth() as it wont include all the regression coefficients and i can't do it any other way and am stuck. I attempted to use predict but when plotted its a non linear line. To sum it up, I need to take my lm() model and put it on my scatterplot.

CodePudding user response:

# Load the required packages
library(ggplot2)
library(dplyr)

# Define the data frame
Data <- data.frame(
  Date = seq(as.Date("2006-01-01"), as.Date("2020-12-31"), by = "3 months"),
  GDP = rnorm(106)
)

# Fit a linear regression model
model <- lm(GDP ~ Date, data = Data)

# Create a scatter plot of the data
ggplot(Data, aes(x = Date, y = GDP))  
  geom_point()

# Add the linear regression line to the plot
abline(model, col = "red")

CodePudding user response:

That is correct. In general, it is not recommended to mix ggplot2 and base plot functions in the same plot. This is because ggplot2 and base plot functions use different plotting systems and the plots created by these two systems can be incompatible with each other.

If you want to add a linear regression line to a ggplot2 scatter plot, you should use the geom_smooth() function instead of the abline() function. The geom_smooth() function is part of the ggplot2 package and is used to add a smoothed conditional mean to a ggplot2 plot.

Here is an example of how you can use the geom_smooth() function to add a linear regression line to a ggplot2 scatter plot:

# Load the required packages
library(ggplot2)
library(dplyr)

# Define the data frame
Data <- data.frame(
  Date = seq(as.Date("2006-01-01"), as.Date("2020-12-31"), by = "3 months"),
  GDP = rnorm(106)
)

# Create a scatter plot of the data
ggplot(Data, aes(x = Date, y = GDP))  
  geom_point()  
  geom_smooth(method = "lm", col = "red")
  • Related