# 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))