How to create an area under a stat_smooth curve on scatter plot?

Viewed 65

I'm making a scatter plot of a metabolic rate according to the time with 2 qualities conditions and I'm using the stat_smooth function with a lm model to have the curves of my scatter plot. I would like to create an area under these curves (with a different color for each quality) but when I try with geom_ribbon, it creates the areas according to the dots, not the curves.

Here is my script :

metabo_temps_quantity = ggplot(data_metabo, aes(x = time, y = metabolic_rate, col=quality)) +
  geom_point(aes(color = quality), size = 3)+
  geom_ribbon(data=data_metabo,aes(x=time,ymax=metabolic_rate),ymin=0, alpha=0.3) +
  theme_classic()+
  stat_smooth(method='lm')+
  facet_wrap(~quantity)+
  theme_minimal()+
  theme_grey(base_size = 22)
metabo_temps_quantity 

How could I do that ?

Thanks in advance !

1 Answers

You could achieve your desired result with a second stat_smooth where you set geom="area" (which is a ribbon which starts at 0). To get rid of the outline I set size=0. To set the fill color map the column you mapped on color also on fill for this layer.

Using mtcars as example data:

library(ggplot2)

ggplot(mtcars, aes(hp, mpg, color = factor(cyl))) +
  geom_point() +
  stat_smooth(method='lm') +
  stat_smooth(aes(fill = factor(cyl)), method='lm', geom = "area", alpha = .3, size = 0)
#> `geom_smooth()` using formula 'y ~ x'
#> `geom_smooth()` using formula 'y ~ x'

Related