如何添加图例以显示观测总数?

时间:2019-03-15 14:07:36

标签: r ggplot2 legend

在ggplot2中,如何添加图例以显示箱线图正在查看的观测总数?

我当前的代码:

ggplot(data, aes(x = paymentType, y = numberOfUses)) + 
  geom_boxplot() + 
  facet_wrap(~city) + 
  theme(axis.text.x = element_text(size = rel(2),angle = 60, hjust = 1)) + 
  theme(axis.text.y = element_text(size = rel(1.5), hjust = 1)) + 
  theme(axis.title.y = element_text(size = rel(2.5), angle = 90), 
        axis.title.x = element_text(size = rel(2.5))) + 
  scale_y_continuous(breaks=seq(0,100,20)) + coord_cartesian(ylim = c(0, 100))

输出:

enter image description here

我想在每个单独的城市地块的左上角显示两种付款类型正在观察的观察次数。

由于敏感,我无法提供实际数据。

1 个答案:

答案 0 :(得分:0)

从您问题的描述中听起来,您实际上不需要要包含在构面标签中的值。如果是这样,请查看以下方法是否适合您:

library(ggplot2)
library(dplyr)

# create a sample dataset
sample.data <- diamonds %>%
  filter(cut %in% c("Fair", "Good") & clarity %in% c("SI2", "SI1", "VS2", "VS1")) %>%
  select(cut, price, clarity) %>%
  rename(x = cut, y = price, f = clarity)

> head(sample.data)
# A tibble: 6 x 3
  x         y f    
  <ord> <int> <ord>
1 Good    327 VS1  
2 Good    335 SI2  
3 Fair    337 VS2  
4 Good    339 SI1  
5 Good    351 SI1  
6 Good    351 SI1 

sample.data %>%

  # count number of observations for each facet
  group_by(f) %>%
  mutate(n = n()) %>%
  ungroup() %>%

  ggplot(aes(x, y)) + 
  geom_boxplot() + 

  # add this information as a geom_text layer to each facet, positioned at the top-left
  # corner, with check_overlap so that each label is only plotted once
  geom_text(aes(x = 0.5, y = max(y), 
                label = paste0("Total obs:\n", n)), # or however you wish to label this
            hjust = 0, vjust = 1, check_overlap = TRUE) +
  facet_wrap(~f)

plot