Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 in R: fill underneath a geom_smooth line

Tags:

r

ggplot2

I am trying to fill in a portion of a plot underneath a geom_smooth() line.

Example:

An example of a fill under a curve.

In the example the data fits on that curve. My data is not as smooth. I want to use geom_point() and a mix of geom_smooth() and geom_area() to fill in the area under the smoothed line while leaving the points above.

A picture of my data with a geom_smooth():

Male points are blue, female points are red.

In other words, I want everything underneath that line to be filled in, like in Image 1.

like image 710
Prayag Gordy Avatar asked Sep 18 '25 23:09

Prayag Gordy


1 Answers

Use predict with the type of smoothing being used. geom_smooth uses loess for n < 1000 and gam for n > 1000.

library(ggplot2)

ggplot(mpg, aes(displ, hwy)) +
    geom_point() +
    geom_smooth() +
    geom_ribbon(aes(ymin = 0,ymax = predict(loess(hwy ~ displ))),
                alpha = 0.3,fill = 'green')

Which gives:

enter image description here

like image 168
shreyasgm Avatar answered Sep 20 '25 14:09

shreyasgm