Search code examples
rggplot2confidence-interval

Plotting confidence intervals for each method using ggplot


I'm interested to create a plot to include confidence intervals for each method and label which one is for corresponding method. For example, I want to have a solid confidence interval bar for method A, a dashed confidence interval bar for method B and so on.

Here's a minimal example of what I have done so far:

set.seed(0)
df = 
  data.frame( Z = c("A","B","C","D","A","B","C","D","A","B","C","D"),
              x = seq(1,3.75,0.25),
              y = runif(12,0.5,0.6),
              lower = runif(12,0.4,0.5),  
              upper = runif(12,0.6,0.7)
  )

The output of head(df) is

  Z    x         y     lower     upper
1 A 1.00 0.5896697 0.4176557 0.6125555
2 B 1.25 0.5265509 0.4687023 0.6267221
3 C 1.50 0.5372124 0.4384104 0.6386114
4 D 1.75 0.5572853 0.4769841 0.6013390
5 A 2.00 0.5908208 0.4497699 0.6382388
6 B 2.25 0.5201682 0.4717619 0.6869691

Using ggplot, I plotted each method's confidence intervals.

require(ggplot2)
ggplot(df, aes(x = x, y = y)) +
  geom_point(size = 0.5) +
  geom_errorbar(aes(ymax = upper, ymin = lower)) 

enter image description here

How can i label these confidence intervals as method A,B,C,D in legend as well as making them solid, dashed etc according to method?


Solution

  • You can simply pass "linetype" as an aes argument:

    ggplot(df, aes(x = x, y = y)) +
      geom_point(size = 0.5) +
      geom_errorbar(aes(ymax = upper, ymin = lower, linetype = Z)) 
    

    enter image description here