【问题标题】:How to extract values of confidence interval from ggplot2 stat summary in R?如何从 R 中的 ggplot2 统计摘要中提取置信区间的值?
【发布时间】:2019-01-10 23:21:44
【问题描述】:

我有两种密度的计数数据(级别:1 和 3)。我已经使用 R 中的 summary_stat 函数绘制了具有引导置信区间的原始数据。我想从此图中提取置信区间的上限和下限。我怎样才能做到这一点?

data <- data.frame(set = c(1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 4, 4), 
                   density = c(1, 3, 3, 1, 3, 1, 1, 1, 3, 3, 1, 3), 
                   counts = c(100, 2, 3, 76, 33, 12, 44, 13, 54, 36, 65, 1), 
                   ratio = c(1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 90, 1))
data$density <- as.factor(data$density)

pd <- position_dodge(0.82)
library(ggplot2)
ggplot(data, aes(x=density, y=counts, fill=density)) + 
   theme_bw() +  
   stat_summary(geom="bar", fun.y=mean, position = "dodge") + 
   stat_summary(geom="errorbar", fun.data=mean_cl_boot, width = 0.1, 
                size = 1.2, col = "grey57", position = pd) + 
   ylab("Counts")

【问题讨论】:

    标签: r ggplot2 bootstrap-modal confidence-interval


    【解决方案1】:

    您可以使用ggplot_build()
    该函数为您提供两条信息:一个数据框列表(每层一个)和一个面板对象,其中包含有关轴限制、中断等的所有信息:

    p <- ggplot(data, aes(x=density, y=counts, fill=density)) + 
      theme_bw() +  
      stat_summary(geom="bar", fun.y=mean, position = "dodge") + 
      stat_summary(geom="errorbar", fun.data=mean_cl_boot, width = 0.1, 
                   size = 1.2, col = "grey57", position = pd) + 
      ylab("Counts")
    
    plot_info <- ggplot_build(p)$`data`[[2]]
    

    在您的情况下,所有相关信息都存储在$data 的第二个列表的yminymax 列中。

     # density 1 error bounds
     density1_error_min <- plot_info[1, 'ymin']
     density1_error_max <- plot_info[1, 'ymax']
    
     # density 3 error bounds
     density3_error_min <- plot_info[2, 'ymin']
     density3_error_max <- plot_info[2, 'ymax']
    

    【讨论】:

    • 如果你有四个条形图怎么办? plot_info 会是ggplot_build(p)$data[[4]] 吗?
    • 四个条形图?还是四格?在前一种情况下,它应该是相同的代码,只需在每个相应的图上调用ggplot_build()。在后者中,代码是相同的 - 只需更改行索引,例如plot_info[i, 'ymin']。如有疑问,请自行检查ggplot_build() 的结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 2016-11-04
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    • 1970-01-01
    • 2022-06-27
    相关资源
    最近更新 更多