Peter Peter - 1 year ago 81
R Question

How to plot regression line with ggplot?

I am trying to put two regression lines into the same plot. I can do it by using the code below but with the same color of line:

model1 <- glm(species~logarea, family=poisson, data=fish)
model2 <- glm.nb(species~logarea, data=fish)


I am thinking to use ggplot to replicate above plot so I can display different line with different color. But I could not figure out how to do it.

I only finished the first step which is drawing the scatter plot, but don't know how to add lines on it.


I did some search and I understand that I can use geom_smooth(method = "glm") to generate regression line. But it seems it is not based on the model I built.

Could anyone shed some light on this?

Many thanks.

Answer Source

Just add geom_line(aes(y=fitted_datas)), for instance like this :

model <- glm(mpg~hp, family=poisson, data=mtcars)

Results :

enter image description here