我有一个多面板密度图,每个面板有两条密度曲线.我想在每个面板中添加每个密度曲线的平均值,作为一条垂直线(即,2条线/面板).我该怎么做stat_summary

set.seed(42)
data_frame(site = rep(LETTERS[1:4], each = 25),
                 sex = rep(c("f", "m"), 50),
                 mass = rnorm(100, 50, 5)) %>% 
  ggplot(aes(x = mass, col = sex)) +
  geom_density() +
  stat_summary(fun = mean, geom = "vline") +
  facet_wrap(~site)
Error in `stat_summary()`:
! Problem while computing stat.
ℹ Error occurred in the 2nd layer.
Caused by error in `compute_layer()`:
! `stat_summary()` requires the following missing aesthetics: y
Run `rlang::last_trace()` to see where the error occurred.

当我为y添加一个术语时,我会收到另一个错误消息:

data_frame(site = rep(LETTERS[1:4], each = 25),
                 sex = rep(c("f", "m"), 50),
                 mass = rnorm(100, 50, 5)) %>% 
  ggplot(aes(x = mass, col = sex)) +
  geom_density() +
  stat_summary(fun = mean, geom = "vline", aes(y = 0)) +
  facet_wrap(~site)
Error in `stat_summary()`:
data_frame(site = rep(LETTERS[1:4], each = 25),
                 sex = rep(c("f", "m"), 50),
                 mass = rnorm(100, 50, 5)) %>% 
  ggplot(aes(x = mass, col = sex)) +
  geom_density() +
  stat_summary(fun = mean, geom = "vline", aes(y = 0)) +
  facet_wrap(~site)
! Problem while setting up geom.
ℹ Error occurred in the 2nd layer.
Caused by error in `compute_geom_1()`:
! `geom_vline()` requires the following missing aesthetics: xintercept
Run `rlang::last_trace()` to see where the error occurred.

当我为xintercept添加一个项时,我得到了每个个体的值,而不是平均值:

data_frame(site = rep(LETTERS[1:4], each = 25),
                 sex = rep(c("f", "m"), 50),
                 mass = rnorm(100, 50, 5)) %>% 
  ggplot(aes(x = mass, col = sex)) +
  geom_density() +
  stat_summary(fun = mean, geom = "vline", aes(xintercept = mass, y = 0)) +
  facet_wrap(~site)

enter image description here

推荐答案

问题是默认情况下,stat_summary将为映射到x上的变量的每个值计算映射到y上的变量的平均值.相反,为了达到你想要的结果,你必须设置orientation="y"来计算x的平均值,在y上映射一个常数,例如y = 0,并使用after_stat()来将计算的平均值映射到xintercept上:

library(ggplot2)

set.seed(42)

dat <- data.frame(
  site = rep(LETTERS[1:4], each = 25),
  sex = rep(c("f", "m"), 50),
  mass = rnorm(100, 50, 5)
)

dat |>
  ggplot(aes(x = mass, col = sex)) +
  geom_density() +
  stat_summary(
    aes(xintercept = after_stat(x), y = 0),
    fun = mean, geom = "vline", orientation = "y"
  ) +
  facet_wrap(~site)

R相关问答推荐

多个ggpredicate对象的平均值

提取R中值和列名的所有可能组合

基于shiny 应用程序中的日期范围子集xts索引

使用R中的Shapetime裁剪格栅文件

当月份额减go 当月份额

将数字转换为分钟和秒

传递ggplot2的变量作为函数参数—没有映射级别以正确填充美学

如何提取所有完美匹配的10个核苷酸在一个成对的匹配与生物字符串在R?>

如何在R中描绘#符号?

更改STAT_VALLES/STAT_PEAKS中的箭头线宽/大小

R如何计算现有行的总和以添加新的数据行

将具有坐标列表列的三角形转换为多个多边形

使用shiny 中的所选要素行下拉菜单

我已经运行了几个月的代码的`Palette()`中出现了新的gglot错误

如何在shiny 的应用程序 map 视图宣传单中可视化单点

分隔日期格式为2020年7月1日

网络抓取NBA.com

如何创建一个由一个连续变量和一个因素变量组成的复杂方框图?

在R中,有没有什么方法可以根据一列中的多个值来过滤行?

使用卡环从R中的列中删除单位(&C)