Prayag Gordy
Prayag Gordy

Reputation: 777

ggplot2 in R: fill underneath a geom_smooth line

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.

Upvotes: 4

Views: 7025

Answers (1)

shrgm
shrgm

Reputation: 1334

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

Upvotes: 6

Related Questions