Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Unearth the Buried Regression Line in GGPLOT

Tags:

plot

r

ggplot2

Currently my regression plot looks like this. Notice that the regression line is deeply buried.

Is there any way I can modify my code here, to show it on top of the dots? I know I can increase the size but it's still underneath the dots.

p <- ggplot(data=my_df, aes(x=x,y=y),) +
     xlab("x") +
     ylab("y")+
     geom_smooth(method="lm",se=FALSE,color="red",formula=y~x,size=1.5) +
     geom_point()
p

enter image description here

like image 849
neversaint Avatar asked Mar 05 '13 01:03

neversaint


2 Answers

Just change the order:

p <- ggplot(data=my_df, aes(x=x,y=y),) +
     xlab("x") +
     ylab("y")+
     geom_point() +
     geom_smooth(method="lm",se=FALSE,color="red",formula=y~x,size=1.5)
p
like image 51
alexwhan Avatar answered Nov 06 '22 22:11

alexwhan


The issue is not the color, but the order of the geoms. If you first call geom_point() and then geom_smooth() the latter will be on top of the former.

Plot the following for comparison:

Before <- 
  ggplot(data=my_df, aes(x=x,y=y),) +
     xlab("x") +
     ylab("y")+
     geom_smooth(method="lm",se=FALSE,color="red",formula=y~x,size=1.5) +
     geom_point()

After <- 
  ggplot(data=my_df, aes(x=x,y=y),) +
     xlab("x") +
     ylab("y")+
     geom_point() + 
     geom_smooth(method="lm",se=FALSE,color="red",formula=y~x,size=1.5)

Line Plotted AFTER Points

Line Plotted BEFORE Points

like image 44
Ricardo Saporta Avatar answered Nov 06 '22 21:11

Ricardo Saporta