точное размещение метки geom_text на оси месяца

Как настроить geom_text так, чтобы он был виден правильно?

data <- read.table(text = "      months preMonth postMonth preOnc postOnc
1 2017-10-19      958       543    242     657
2 2017-11-19      958       177    242    1023
3 2017-12-19      958       127    242    1073
4 2018-01-19      958        41    242      NA
5 2018-02-19      958        21    242      NA
6 2018-03-19      958        21    242      NA")


dataLong <- data %>% tidyr::gather(Type, Amount, 2:5) %>% filter(!is.na(Amount))
dataLong$delim <- substr(dataLong$Type, 1, 3)
dataLong$Type <- factor(dataLong$Type, levels = c("preOnc", "postOnc", "preMonth", "postMonth"))
dataLong$delim <- factor(dataLong$delim, levels = c('pre', 'pos'))
ggplot(dataLong, aes(x=months, y=Amount, fill=Type)) + 
  geom_bar(stat = "identity") +
  geom_hline(yintercept = 1200, col='red',linetype='dashed') + 
  geom_text(aes(x=months[1], y= 1200 ,label = "Expected: 1200", vjust = -1)) +
  facet_grid(. ~ delim,  labeller=label_both) + 
  scale_fill_manual(values = c("grey", "grey", "seagreen3", "seagreen3")) +
  scale_x_date(date_breaks = "1 month", date_labels = "%b-%y")

введите здесь описание изображения


person Prradep    schedule 19.10.2017    source источник


Ответы (1)


Вы хотите, чтобы это?

Обратите внимание на hjust = -1, vjust = -0.5 в вызове geom_text().

library(tidyverse)

data <- read.table(text = "      months preMonth postMonth preOnc postOnc
1 2017-10-19      958       543    242     657
2 2017-11-19      958       177    242    1023
3 2017-12-19      958       127    242    1073
4 2018-01-19      958        41    242      NA
5 2018-02-19      958        21    242      NA
6 2018-03-19      958        21    242      NA")

# the tidyverse (in this case dplyr) case of preparing the data 
dataLong <- data %>% 
  gather(Type, Amount, 2:5) %>% 
  filter(!is.na(Amount)) %>% 
  mutate(
    delim =  substr(Type, 1, 3),
    Type = factor(Type, levels = c("preOnc", "postOnc", "preMonth", "postMonth")),
    delim = factor(delim, levels = c("pre", "pos")),
    months = as.Date(months)
    )

ggplot(dataLong, aes(x = months, y = Amount, fill = Type)) + 
  geom_bar(stat = "identity") +
  geom_hline(yintercept = 1200, col = "red",linetype = "dashed") + 
  geom_text(aes(x = months[1], y = 1200, label = "Expected: 1200"), 
            vjust = -0.5, hjust = -1) +
  facet_grid(. ~ delim, labeller = label_both) + 
  scale_fill_manual(values = c("grey", "grey", "seagreen3", "seagreen3")) +
  scale_x_date(date_breaks = "1 month", date_labels = "%b-%y")

Альтернатива с центрированным geom_label

# first compute the middle of the range of months
mid_month <- range(dataLong$months) %>% {(.[2] - .[1]) / 2 + .[1]}

ggplot(dataLong, aes(x = months, y = Amount, fill = Type)) + 
  geom_bar(stat = "identity") +
  geom_hline(yintercept = 1200, col = "red",linetype = "dashed") +

  # use geom_label and hardcode the parameters
  geom_label(x = mid_month, y = 1200, label = "Expected: 1200", 
             vjust = 0.5, hjust = 0.5, color = "red", inherit.aes = F) +
  facet_grid(. ~ delim, labeller = label_both) + 
  scale_fill_manual(values = c("grey", "grey", "seagreen3", "seagreen3")) +
  scale_x_date(date_breaks = "1 month", date_labels = "%b-%y")

Здесь без inherit.aes = F мы бы также присвоили цвет легенде (чего мы не делаем)...

person David    schedule 19.10.2017
comment
Или вы хотите центрировать текст? - person David; 19.10.2017
comment
Спасибо за оба подхода. У меня нет предпочтений центрировать метку, но я буду использовать второй подход, так как он мне больше понравился. - person Prradep; 19.10.2017
comment
@David, спасибо, что показал geom_label. До сих пор не знал о его существовании. - person Adam Quek; 19.10.2017