How to Unearth the Buried Regression Line in GGPLO

2019-06-23 16:43发布

问题:

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

回答1:

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


回答2:

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)



回答3:

How about transparent points?

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 



标签: r plot ggplot2