Search code examples
rggplot2confidence-interval

Plotting confidence or prediction intervals on point plots ggplot2


I want to plot prediction interval of some data I have that come from a certain distribution where I have calculated the 95% prediction interval. So let's say I have this code

require(ggplot2)
require(reshape2)


dummy_data <- data.frame(x=rnorm(100, 15,2), y=rnorm(100, 17,2), z=rnorm(100,13, 2))
melted_dd <- melt(dummy_data)

pi_limits <- data.frame(start=c(10.2, 14.3, 9.2), end=c(17.2, 20.4, 18.9))
row.names(pi_limits) <- c("x", "y", "z")


ggplot() + geom_point(data=melted_dd, aes(x=value, y=variable)) + theme_minimal()

Now I want to plot prediction interval limits on my discrete y-axis for all variables which covers the distance given in the pi_limits with a certain colored bar that goes from the start to end. I have looked at solutions on this site when it comes to this problem, the closest I got was using geom_ribbon but that seems to be suited for line graphs or maybe I havn't undertsood how to use it correctly. Can somebody help me please?


Solution

  • Try geom_linerange():

    library(ggplot2)
    set.seed(13)
    
    pi_limits$variable <- rownames(pi_limits)
    
    ggplot() + 
      geom_linerange(
        data = pi_limits, 
        aes(xmin = start, xmax = end, y = variable, color = variable), 
        linewidth = 5,
        alpha = 0.5,
        show.legend = FALSE
      ) +
      geom_point(data = melted_dd, aes(x = value, y = variable)) +
      theme_minimal()