使用 ggplot facet_wrap 绘制每组的中位数

Aru*_*tri 1 r ggplot2 dplyr

有问题的数据集是钻石(以 dplyr 为单位)。我试图通过使用facet_wrap 切割来打破价格直方图。我还希望每个地块都有中线。这就是我所做的-

by_cut <- group_by(diamonds, cut)

med <- by_cut %>% 
  summarise(medn = median(price))

diam <- diamonds %>% 
  mutate(med_cut = ifelse(cut == med$cut[1], med$medn[1],
                      ifelse(cut == med$cut[2], med$medn[2],
                             ifelse(cut == med$cut[3], med$medn[3],
                                    ifelse(cut == med$cut[4], med$medn[4], med$medn[5])))))

diam %>% 
  ggplot(aes(price)) +
  geom_histogram(binwidth = 100) +
  facet_wrap(~ cut, scales = "free_y") +
  geom_vline(aes(xintercept= med_cut), colour='red') 
Run Code Online (Sandbox Code Playgroud)

并得到了所需的情节(如下所示,这就是我想要的..) - 面包裹中位数

但是我确信这不是实现结果的理想方式,因此我想知道实现结果情节的最佳方式是什么?

基于@yeedle 评论

这里比之前的尝试更好:

diam <- diamonds %>% 
  group_by(cut) %>% 
  mutate(medn = median(as.numeric(price)))

diam %>% 
  ggplot(aes(price)) +
  geom_histogram(binwidth = 100) +
  facet_wrap(~ cut, scales = "free_y") +
  geom_vline(aes(xintercept= medn, group= cut), colour='red') 
Run Code Online (Sandbox Code Playgroud)

我们可以进一步改进吗?

yee*_*dle 5

diamonds %>% 
  group_by(cut) %>%
  mutate(med_price = median(as.numeric(price))) %>%
  ggplot(aes(price)) +
     geom_histogram(binwidth = 100) +
     geom_vline(aes(xintercept= med_price), colour='red') +
     facet_wrap(~ cut, scales = "free_y")
Run Code Online (Sandbox Code Playgroud)