How to label vLines in ggplot (R)
The are multiple issues with your annotate
:
-
annotate
has no mapping argument. Hence, usingaes(...)
results in an error as it is passed (by position) to thex
argument. And asaes(...)
will not return an object of classDate
it will throw an error. -
As you want to add a label use
x
instead ofxintercept
.geom_label
. has noxintercept
aesthetic. -
There is no need to wrap the dates in
as.numeric
.
Using the ggplot2::economics
dataset as example data you could label your vertical lines like so:
library(ggplot2)
library(lubridate)
ggplot(economics, aes(x = date, y = uempmed)) +
geom_vline(aes(xintercept = ymd("1980-10-26")), color = "red") +
geom_vline(aes(xintercept = ymd("2010-02-10")), color = "blue") +
geom_line(color = 1, lwd = 0.25) +
scale_x_date(expand = c(0, 0)) +
annotate(x = ymd("1980-10-26"), y = +Inf, label = "Ignite", vjust = 2, geom = "label") +
annotate(x = ymd("2010-02-10"), y = +Inf, label = "Ignite", vjust = 2, geom = "label")