r

ggplot for linear-log regression model?


How do I plot a log linear model in R? Currently, I am doing this but am not sure if it's the right/efficient way:

data(food)
model1 <- lm(food_exp~log(income), data = food)
temp_var <- predict(model1, interval="confidence")
new_df <- cbind(food, temp_var)
head(new_df)
ggplot(new_df, aes(x = income, y = food_exp))+
  geom_point() +
  geom_smooth(aes(y=lwr), color = "red", linetype = "dashed")+
  geom_smooth(aes(y=upr), color = "red", linetype = "dashed")+
  geom_smooth(aes(y = fit), color = "blue")+
  theme_economist()

Solution

  • you can use geom_smooth and putting your formula directly in. It should yield the same as your fit (which you can check by also plotting that)

    ggplot(new_df, aes(x = Sepal.Width, y = Sepal.Length))+
      geom_point() +
      geom_point(aes(y=fit), color="red") + #your original fit
      geom_smooth(method=lm, formula=y~log(x)) #ggplot fit