Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot regression line with ggplot?

Tags:

plot

r

regression

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)

plot(species~logarea,data=fish)
lines(fitted(model1)[order(logarea)]~sort(logarea),data=fish)
lines(fitted(model2)[order(logarea)]~sort(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.

ggplot(fish,aes(fish$logarea,fish$SPECIES))+geom_point()

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.

like image 922
Peter Avatar asked Sep 13 '16 12:09

Peter


People also ask

Can you plot a model with Ggplot?

The geom_smooth() function in ggplot2 can plot fitted lines from models with a simple structure. Supported model types include models fit with lm() , glm() , nls() , and mgcv::gam() . Fitted lines can vary by groups if a factor variable is mapped to an aesthetic like color or group .

How do you plot a regression line in ggplot2?

Adding a regression line on a ggplot You can use geom_smooth() with method = "lm" . This will automatically add a regression line for y ~ x to the plot.

How do you add a regression line in R?

A regression line will be added on the plot using the function abline(), which takes the output of lm() as an argument. You can also add a smoothing line using the function loess().


2 Answers

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

data("mtcars")
library(ggplot2)
model <- glm(mpg~hp, family=poisson, data=mtcars)
ggplot(mtcars,aes(hp,mpg))+geom_point()+geom_line(aes(y=fitted(model)))

Results :

enter image description here

like image 160
Arault Avatar answered Sep 29 '22 14:09

Arault


You can fit the models directly in geom_smooth. In this case, you'll need to give extra arguments to the fitting method using the method.args argument to define the family for the glm.

Here is an example, adding different colors per model type. I use se = FALSE to remove the confidence intervals.

ggplot(fish,aes(logarea, SPECIES)) + 
    geom_point() +
    geom_smooth(method = "glm", method.args = list(family = poisson), aes(color = "poisson"), se = FALSE) +
    geom_smooth(method = MASS::glm.nb, aes(color = "NB"), se = FALSE)
like image 28
aosmith Avatar answered Sep 29 '22 14:09

aosmith