1

I am looking to add vertical lines and labels to draw attention to specific dates on the x axis of a ggplot2 graph. The lines and labels draw attention to multiple variables on the same date and which are built on top of each other. My problem is that I only wish to show each label once but my attempt is placing the label on 'each' y axis graph.

I have mocked up some dummy data to illustrate. For avoidance of doubt, what I am looking to achieve is a single label with the text "A", on the first vertical line, and similar for "B" and "C" on the second and third lines, where at the moment I am getting three labels for each line.

library(ggplot2)
library(reshape2)
library(dplyr)
library(scales)

set.seed(1234)
PetSightings = data.frame(DateRange = seq(as.Date("2016/1/1"), by = "day", length.out = 60),
                      cats = round(rnorm(60, 10, 3), 0), dogs = round(rnorm(60, 20, 10), 0),
                      parrots = round(rnorm(30, 5, 2)))

PetSightingsMelt = melt(PetSightings, id.vars = "DateRange")


ggplot(PetSightingsMelt, aes(x = DateRange, y = value)) +  
  ggtitle("Pet Sightings") +
  labs(x = "Date", y = "Values") +
  geom_bar(stat = "identity", aes(colour = variable)) +
  geom_vline(xintercept = as.numeric(PetSightings$DateRange[15]), linetype = "longdash", alpha = 0.5) +
  geom_vline(xintercept = as.numeric(PetSightings$DateRange[45]), linetype = "longdash", alpha = 0.5) +
  geom_vline(xintercept = as.numeric(PetSightings$DateRange[55]), linetype = "longdash", alpha = 0.5) +
  annotate("text", x = PetSightings$DateRange[15], y = 25, label = "A", size = 6) +
  annotate("text", x = PetSightings$DateRange[45], y = 25, label = "B", size = 6) +
  annotate("text", x = PetSightings$DateRange[55], y = 25, label = "C", size = 6) +
  facet_grid(variable ~ ., scales = "free_y") +
  theme(legend.position = "none",
    axis.text.x = element_text(angle = 60, vjust = 0.5, size = 6),
    plot.title = element_text(size = 20),
    axis.text.x = element_text(size = 10),
    axis.title.x = element_text(face = "bold", size = 12),
    axis.title.y = element_text(face = "bold", size = 12),
    axis.text.y = element_text(size = 8),
    strip.text.y = element_text(size = 10, angle = 0)) + 
  scale_x_date(labels = date_format("%Y-%m"), date_breaks = "1 month") +
  scale_y_continuous(labels = comma)
CallumH
  • 751
  • 1
  • 7
  • 22

1 Answers1

1

It seems that we cannot use annotate to do that. So instead, we can create a data frame for putting specific geom_text onto the plot. Let's say we create data frame ann_label as below:

ann_label <- data.frame(DateRange = PetSightings$DateRange[c(15, 45, 55)], value = 25, label = LETTERS[1:3],
                        variable = factor("cats", level = c("cats", "dogs", "parrots")))

Then, you can just add the geom_text to your ggplot object:

+ geom_text(data = ann_label, aes(label = label), size = 6)

Result:

enter image description here

zyurnaidi
  • 2,143
  • 13
  • 14