【问题标题】:How to annotate the area under the curve of density plot of specific interval?如何标注特定区间的密度图曲线下面积?
【发布时间】:2021-06-01 10:07:18
【问题描述】:

密度图很有趣,但高度只是一个高度。 (https://stats.stackexchange.com/questions/147885/how-to-interpret-height-of-density-plot)

因此,在可视化这一点时,提供其他信息总是有帮助的,例如 Sepal.Length 介于 5 和 6 之间的百分比是多少?为该区域添加阴影,并在图表上标注该特定区域的百分比。

如何用 ggplot 做到这一点?

ggplot(iris, aes(x=Sepal.Length))  + 
    geom_density()

例如下面的例子,感兴趣的区域带有阴影并显示百分比(理想情况下是 12% 而不是 0.12)

【问题讨论】:

  • 相关,可能重复? stackoverflow.com/q/33244629/680068
  • @zx8754,非常接近但不是我想要的,尤其是在注释部分。不过谢谢,我也会看看这个。
  • 这不是重复的,因为其他问题只是在没有提供注释的情况下隐藏。根据我的标题,曲线下区域的注释至关重要,还提供了预期结果的图像示例。

标签: r ggplot2


【解决方案1】:

您可能会发现scales::oob_censor() 是一个方便的功能。它将越界值转换为NAs。您可以使用它来设置填充区域的边界,还可以通过计算非 NA 来获取落在边界内的观察分数(作为闭合区间)。缺点是您会收到有关缺失值的警告,这很好。不过,您必须手动为文本注释设置一个令人满意的 y 值。

library(ggplot2)
library(scales)

bounds <- c(5, 6)

ggplot(iris, aes(x=Sepal.Length))  + 
  stat_density(geom = "line") +
  stat_density(
    geom = "area",
    aes(x = stage(Sepal.Length, after_stat = oob_censor(x, bounds))),
    alpha = 0.3
  ) +
  annotate(
    "text", mean(bounds), y = 0.2, 
    label = percent(mean(!is.na(oob_censor(iris$Sepal.Length, bounds))))
  )
#> Warning: Removed 370 rows containing missing values (position_stack).

reprex package (v1.0.0) 于 2021 年 6 月 1 日创建

【讨论】:

  • 也是你 ggh4x 的忠实粉丝 :),再次感谢
猜你喜欢
  • 2015-12-19
  • 2013-12-19
  • 2021-06-18
  • 2020-03-30
  • 1970-01-01
  • 2020-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多