Search code examples
rggplot2confidence-intervalloess

How to detect where the width of loess 95% CI reach a certain amount?


I've fitted a loess curve with 95% CI, and now I'd like to be able to determine where the CI get to a certain width.

For example, using the "cars" dataset:

plot <- ggplot (cars, aes (x=speed, y=dist)) +
geom_point() +
stat_smooth (method= "loess", se=TRUE) +
xlab("Speed")+
ylab("Distance")+
theme_bw()
plot

plot

I'd like to be able to find out at what values of "Speed" the CIs are equal to 20 units of distance. Looking at the plot, it might be approximately 7 and 24.

Thanks!


Solution

  • You can use ggplot_build(plot) to extract relevant data about the layers built in ggplot2 and other misc information.

    In this case, the limits for the confidence intervals are in the ymin and ymax columns and can be reached with:

    foo <- ggplot_build(plot)
    foo[["data"]][[2]]
    

    You can then do a simple mutate to examine the differences between ymax and ymin and at what "Speed" the CI gap reaches 20 through the x column.

    mutate_info <- foo[["data"]][[2]] %>% dplyr::mutate(ci_gap = ymax-ymin)