ggplot2直方图在“填充”参数上显示平均值

时间:2018-07-29 19:59:54

标签: r ggplot2

我遇到以下问题,我希望根据另一列的值计算fill参数。下面的可复制示例:

library(tidyverse)

df <- tibble(a = rbeta(1000, 10, 2),
             b = rbinom(1000, 1, .8))

df %>%
  ggplot() +
  geom_histogram(aes(x = a, fill = "average of df$b by bin"), color = "black", binwidth = 0.05, boundary = -0.05) +
  scale_x_continuous(labels = scales::percent, breaks = seq(0, 1, .05))

1 个答案:

答案 0 :(得分:1)

尝试预先计算统计信息

df %>%
  group_by(a_group = cut(a, breaks = seq(0, 1.05, .05), labels = scales::percent(seq(0, 1, .05)))) %>% 
  summarise(b_count = n(), b_mean = mean(b)) %>% 
  ggplot(aes(x = a_group, y = b_count, fill = b_mean)) +
  geom_col(position = position_nudge(x = .5))

enter image description here