Keith Keith - 4 months ago 40
R Question

Making regression line visible with ggplot2

My question is really simple:

I have a data set and I made a scatter plot of points (y on x) and I added a regression line using ggplot2. However, because the points are so densely populated, I cannot see my regression line through the points:

ggplot(wthrmelt, aes(x =value, y = avg_target)) +facet_wrap(~variable, scales = "free") + geom_smooth(method='lm',color="red",formula=y~x)+geom_point()

Is there an option I can set in the geo_smooth() function to overlay the line on top of the points?


  • Keith


@Roland is correct, you simply need to reorder your plot. You currently have

ggplot(wthrmelt, aes(x =value, y = avg_target)) +
    facet_wrap(~variable, scales = "free") +
    geom_smooth(method='lm',color="red",formula=y~x) + 

which is plotting all the points on top of the line. Rearrange it:

ggplot(wthrmelt, aes(x =value, y = avg_target)) +
    facet_wrap(~variable, scales = "free") +
    geom_point() +

and that should solve the problem, because the regression line will be plotted over the points.