bad interaction between stat_smooth and geom_ribbon

Viewed 308

I was answering this question, which required plotting smooth areas, but removing 'useless' area. To do that on a simple geom_area (not smooth), i'd just use geom_ribbon with aes(ymax=y, ymin=min(y)). But turning a stat_smooth(geom="area") into a stat_smooth(geom="ribbon", aes(ymax=y, ymin=min(y))) does not yield the expected result.

geom_area to geom_ribbon (dummy data at the end):

ggplot(df, aes(x=x, y=y)) + geom_area() to ggplot(df, aes(x=x, y=y)) + geom_ribbon(aes(ymax=y, ymin=min(y)))

enter image description here

Now the smooth version:

ggplot(df, aes(x=x, y=y)) + stat_smooth(geom="area") to ggplot(df, aes(x=x, y=y)) + stat_smooth(geom="ribbon", aes(ymax=y, ymin=min(y)))

enter image description here

The output that i wanted is something like this:

enter image description here

I found some solutions that involved making a new data frame with "smoothed data", and then plotting that normally with a geom_ribbon, but that applied only when you had a known function and could easily generate more observations. Another try was to set the y limits to ylim(min(y), max(y)), but ggplot doesn't plot any geom that is "caught" in a limit, so maybe if there's a way to change that feature it'd be a way to solve my problem.

Dummy data:

df <- data.frame(
  x = 1:7,
  y = c(12.44, 11.98, 11.40, 12.15, 13.14, 11.99, 12.17))
1 Answers

Do you mean something like this? If you want to use a calculated variable in your mapping, you need to wrap it with after_stat(). after_stat(y) means "use the y value calculated by the stat, not the y value in the original data frame."

library(ggplot2)

df <- data.frame(
  x = 1:7,
  y = c(12.44, 11.98, 11.40, 12.15, 13.14, 11.99, 12.17)
)

ggplot(df, aes(x=x, y=y)) + 
  geom_point() +
  stat_smooth(
    geom="ribbon", 
    aes(ymax = after_stat(y), ymin = after_stat(min(y))),
    fill = "skyblue"
  )
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

Created on 2020-10-28 by the reprex package (v0.3.0)

Related