Search code examples
rggplot2geom-bar

How to create shaded effects to display confidence interval / error bar on a ggplot2 bar chart?


I would like to reproduce the visual effect from this chart in order to display the confidence interval for an indicator.

enter image description here

This looks a lot more intuitive than the regular error_bar / whisker.

I checked a bit some reference - like https://www.datanovia.com/en/lessons/ggplot-error-bars/ - and tried to play with errorbar and line range..

my_df <- 
tibble::tribble(~response, ~estimate, ~lower_ci, ~upper_ci,
                "little_bit", 0.353477, 0.255625, 0.451747,
                "no", 0.307639, 0.250436, 0.375393,
                "very", 0.338883, 0.301007, 0.37572310)


ggplot(my_df, aes(x = reorder(response, -estimate), y = estimate)) +


geom_linerange(aes( ymin = lower_ci, ymax = upper_ci),
             width = 0.9, 
              size = 45, 
             color = "red",
             alpha  = 0.7
            ) +
  geom_errorbar(aes(ymin = estimate, ymax = estimate),
            width = 0.9, 
            size = 2 ,
            color = "#6EB3FF") 

Still not the nice shaded / gradient effects...

Thanks for help!


Solution

  • You'd probably need to do this "manually"

    ggplot(my_df, aes(x = reorder(response, -estimate))) +
      geom_linerange(data = my_df %>%
                       group_by(response) %>%
                       summarize(ymin = lead(seq(lower_ci, upper_ci, length = 100)),
                                 ymax = lag(seq(lower_ci, upper_ci, length = 100)),
                                 alpha = c(seq(0, 0.5, length = 50), 
                                           seq(0.5, 0, length = 50)),
                                 estimate = estimate),
                     aes(ymin = ymin, ymax = ymax, alpha = alpha, 
                         color = response),
                     size = 45) +
      geom_errorbar(aes(ymin = estimate, ymax = estimate),
                    width = 0.9, 
                    size = 2 ,
                    color = "#3453A2") +
      scale_alpha_identity() +
      guides(color = guide_none()) +
      xlab("Response") +
      theme_minimal(base_size = 20) +
      theme(plot.background = element_rect(fill = "#fff2e6", color = NA),
            panel.background = element_rect(fill = "#fff9f4", color = NA))
    
    

    enter image description here