How to add shaded confidence intervals to line plot with specified values

前端 未结 2 1264
暗喜
暗喜 2020-12-05 08:07

I have a small table of summary data with the odds ratio, upper and lower confidence limits for four categories, with six levels within each category. I\'d like to produce

相关标签:
2条回答
  • 2020-12-05 08:33

    You need the following lines:

    p<-ggplot(data=data, aes(x=interval, y=OR, colour=Drug)) + geom_point() + geom_line()
    p<-p+geom_ribbon(aes(ymin=data$lower, ymax=data$upper), linetype=2, alpha=0.1)
    

    enter image description here

    0 讨论(0)
  • 2020-12-05 08:48

    Here is a base R approach using polygon() since @jmb requested a solution in the comments. Note that I have to define two sets of x-values and associated y values for the polygon to plot. It works by plotting the outer parameter of the polygon. I define plot type = 'n' and use points() separately to get the points on top of the polygon. My personal preference is the ggplot solutions above when possible since polygon() is pretty clunky.

    library(tidyverse)
    
    data('mtcars')  #built in dataset
    
    mean.mpg = mtcars %>% 
      group_by(cyl) %>% 
      summarise(N = n(),
            avg.mpg = mean(mpg),
            SE.low = avg.mpg - (sd(mpg)/sqrt(N)),
            SE.high =avg.mpg + (sd(mpg)/sqrt(N)))
    
    
    plot(avg.mpg ~ cyl, data = mean.mpg, ylim = c(10,30), type = 'n')
    
    #note I have defined c(x1, x2) and c(y1, y2)
    polygon(c(mean.mpg$cyl, rev(mean.mpg$cyl)), 
    c(mean.mpg$SE.low,rev(mean.mpg$SE.high)), density = 200, col ='grey90')
    
    points(avg.mpg ~ cyl, data = mean.mpg, pch = 19, col = 'firebrick')
    
    0 讨论(0)
提交回复
热议问题