tidyverse / ggplot2

An implementation of the Grammar of Graphics in R
https://ggplot2.tidyverse.org
Other
6.47k stars 2.02k forks source link

geom_smooth and stat_smooth need to truncate lines when standard error exceeded #5688

Closed kramerrs closed 6 months ago

kramerrs commented 7 months ago

Tips for a helpful feature request:

I would like to request that the trend lines drawn by geom_smooth or stat_smooth have an option to truncate the line when a standard error threshold is exceeded. For most plots when there is a strong trend a few outliers lead to aweful looking plots. Even if we put a standard error on the plot, it doesn't make it look better:

For example in this plot, everyone knows I can't predict those outliers at the beginning and end, I don't need to tell everyone. Hey, there is a bogus crooked line here with massive standard error.

image

teunbrand commented 7 months ago

I'm not sure that this is considered good practise. You can always fit the model outside of ggplot2 and plot it however you see fit.

teunbrand commented 6 months ago

Also using delayed evaluation, you can clip the fill region by setting either ymin or ymax to NA.

library(ggplot2)

ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  geom_smooth(
    aes(ymin = after_stat(ifelse(ymax - ymin > 3, NA, ymin)))
  )
#> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'

Created on 2024-03-11 with reprex v2.1.0

As this functionality is already available, I'll close this issue.