Как добавить легенду, чтобы показать общее количество наблюдений? - PullRequest
0 голосов
/ 15 марта 2019

В 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 голосов
/ 16 марта 2019

Из описания в вашем вопросе не похоже, что вы на самом деле нуждаетесь в значении, указанном в метке фасета.Если это так, посмотрите, работает ли для вас следующий подход:

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

...