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)