How to open a buried regression line in GGPLOT

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

Is there a way to change my code here to show it on top of dots? I know I can increase the size, but it is still under 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

+5
source share
3 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
+12
source

The problem is not in color, but in the order of the geome. If you call first geom_point(), then the geom_smooth() last will be on top of the first.

For comparison, do the following:

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

+5
source

?

library(ggplot2)
seed=616
x1<- sort(runif(rnorm(1000)))
seed=626
x2<- rnorm(1000)*0.02+sort(runif(rnorm(1000)))
my_df<- data.frame(x= x1, y = x2)
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(size = I(2), alpha = I(0.1))
p 

Transparent plot points

+2

All Articles