在使用 facet_wrap 创建的直方图上绘制均值

Plotting means on histograms created with facet_wrap

我正在使用 ggplot2facet_wrap 制作几个直方图,并想在每个面板上绘制平均值。下面,我创建了一个虚拟数据框,找到每个方面的平均值,然后使用 geom_point.

创建添加平均值的图
# Load libraries 
library(tidyverse)

# Toy data frame
df <- data.frame(ID = sample(letters[1:3], 100, replace = TRUE), n = runif(100))

# Mean value of each group
df_mean <- df %>% group_by(ID) %>% summarise(mean = mean(n))

# Plot histograms
ggplot(df) + 
  geom_histogram(aes(n)) + 
  facet_wrap(~ID) +
  geom_point(data = df_mean, aes(x = mean, y = Inf))

我使用 y = Inf 将点放在每个面的顶部,但是 - 如您所见 - 它被裁剪了一些。我想将它向下推,以便它完全可见。据我所知,geom_point 没有 nudge_yvadj 参数,0.7 * Inf 显然是荒谬的。我还尝试添加 position = position_nudge(y = -5) 作为 geom_point 的参数,但这似乎没有任何效果。作为一种解决方法,我什至尝试使用 geom_text 并指定 nudge_y,但是——就像 position_nudge 解决方案一样——它没有任何明显的效果。在绘图时是否有一种简单的方法可以做到这一点,或者我只需要在绘图之前计算 y 值?

# Load libraries 
library(tidyverse)

# Toy data frame
df <- data.frame(ID = sample(letters[1:3], 100, replace = TRUE), n = runif(100))

# Mean value of each group
df_mean <- df %>% group_by(ID) %>% summarise(mean = mean(n))

# Get max count using the dataframe that stores ggplot info
ggplot(df) + 
  geom_histogram(aes(n)) + 
  facet_wrap(~ID) -> p

# Plot histograms and plot mean in the right place
p + geom_point(data = df_mean, aes(x = mean, y = max(ggplot_build(p)$data[[1]]$count)))

这里的关键是要知道最大计数值,因为这将是直方图的最高 y 轴值。您可以使用 ggplot_build 函数获取该信息,并使用它在正确的位置绘制您的点。

当然,如果点落在其中一根柱上,您可以比最大计数高一点,就像这样y = 0.2 + max(ggplot_build(p)$data[[1]]$count))

如果您可以使用 geom_text/label(),您可以使用 vjust 参数来执行此操作:

ggplot(df) + 
    geom_histogram(aes(n)) + 
    facet_wrap(~ID) +
    geom_text(data = df_mean, aes(x = mean, y = Inf),
              label = "Mean", vjust = 1)

我一直用它来计算面板顶部的浮动百分比变化或 p 值,您不需要计算任何东西,ggplot 已经帮您解决了。