【问题标题】:Getting the values calculated by stat_summary with mean_cl_boot使用 mean_cl_boot 获取 stat_summary 计算的值
【发布时间】:2020-05-28 10:34:20
【问题描述】:

我正在用 mean_cl_boot 绘制一些 X 值,置信区间很大

如何导出每个组中fun.y = meanfun.data = mean_cl_boot 的值的文本?

我在mean_cl_boot 中有一个值区间,我想绘制它们并导出它们。

ggplot(iris, aes(x = Species, y = Petal.Length)) + 
geom_jitter(width = 0.5) + stat_summary(fun.y = mean, geom = "point", color = "red") + 
stat_summary(fun.data = mean_cl_boot, fun.args=(conf.int=0.9999), geom = "errorbar", width = 0.4)

我必须绘制平均 (fun.y = mean) 值,其中:

stat_summary(fun.y=mean, geom="text", aes(label=sprintf("%1.1f", ..y..)),size=3, show.legend=FALSE

但我不能和mean_cl_boot 一样。

【问题讨论】:

    标签: r ggplot2 tidyverse mean confidence-interval


    【解决方案1】:

    您可以通过ggplot_build访问stat_summary的数据。

    首先,将您的 ggplot 调用存储在一个对象中:

    g <- ggplot(iris, aes(x = Species, y = Petal.Length)) + 
      geom_jitter(width = 0.5) + 
      stat_summary(fun.y = mean, geom = "point", color = "red") + 
      stat_summary(fun.data = mean_cl_boot, fun.args=(conf.int=0.9999), geom = "errorbar", width = 0.4)
    

    然后,用:

    ggplot_build(g)$data[[3]]
    

    你得到用mean_cl_boot计算的值:

      x group     y     ymin     ymax PANEL xmin xmax colour size linetype width alpha
    1 1     1 1.462 1.386000 1.543501     1  0.8  1.2  black  0.5        1   0.4    NA
    2 2     2 4.260 4.024899 4.462202     1  1.8  2.2  black  0.5        1   0.4    NA
    3 3     3 5.552 5.337199 5.798202     1  2.8  3.2  black  0.5        1   0.4    NA
    

    为了获得正确的标签,您可以这样做:

    # extract the data
    mcb <- ggplot_build(g)$data[[3]]
    
    # add the labels to the plot
    g + geom_text(data = mcb,
                  aes(x = group, y = ymin, label = round(ymin,2)),
                  color = "blue",
                  vjust = 1)
    

    结果:

    但可能更好的选择是使用 包:

    library(ggrepel)
    
    g + geom_label_repel(data = mcb,
                         aes(x = group, y = ymin, label = round(ymin,2)),
                         color = "blue",
                         nudge_x = 0.2,
                         nudge_y = -0.2)
    

    结果:

    【讨论】:

    • 我通过使用观察到:stat_summary(fun.data = mean_cl_boot, fun.args=(conf.int=0.9999), geom = "text", aes(label=sprintf("%1.1f ", ..ymin..)), width = 0.4) 或 ymax 我可以绘制 ymax 和 ymin,但在图表上没有定义位置。你有什么想法吗?
    • @GabrielG。 定义的位置是什么意思?
    • 例如,误差条正下方的最小值和误差条上方的最大值。如果我在上面的代码中使用 vjust,我不会在对齐上得到完美匹配!
    • 对图表的触感非常好。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多