4

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.

Prayag Gordy
  • 667
  • 7
  • 18
  • Can you provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610) for your graph? That would make it much easier for others to assist you. – shrgm May 21 '16 at 04:07
  • I will next time. Thanks for the suggestion. @shreyasgm – Prayag Gordy May 21 '16 at 16:26

1 Answers1

6

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

shrgm
  • 1,315
  • 1
  • 10
  • 20
  • But let's say that I wanted to fill based on gender. Here is [my data](https://www.dropbox.com/sh/5poh0gpoq0wa4du/AABMmRpObK9fv7Xy7HzaC-QYa?dl=0). I want to create two different `geom_smooth`s, and fill under each with blue or red, like my points in the new graph in the question. I want points only under the blue line or only under the red line to have those colors, and everything under both lines to be purple. Thanks! – Prayag Gordy May 21 '16 at 16:37
  • That's an interesting question! Please post it as a separate question with a [minimal reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) instead of editing your original question - the answer is involved. You'll find some pointers [here](http://stackoverflow.com/questions/9789871/method-to-extract-stat-smooth-line-fit) though. – shrgm May 21 '16 at 17:50
  • I'm newish to Stack Overflow, so thanks for the formatting suggestions. Here is the [new question](http://stackoverflow.com/questions/37368778/use-geom-ribbon-for-shading-under-two-different-geom-smooth-lines). Thank you! – Prayag Gordy May 21 '16 at 22:54