Paul Smith
Paul Smith

Reputation: 11

How to label vLines in ggplot (R)

I've created a stream plot from a time series and need 2 vertical line labelled with text "ignite" and "extinguish" repectively.

Given that it's a time series I'm having real problems getting the labels to display.

Here's the ggplot code thus far:

ggplot(airDataClean, aes(x = Date, y = maxParticulates, fill = Location)) +
   geom_vline(aes(xintercept = as.numeric(ymd("2019-10-26"))), color='red') +
   geom_vline(aes(xintercept = as.numeric(ymd("2020-02-10"))), color='blue') + 
   geom_stream(color = 1, lwd = 0.25) +
   theme(axis.text.y = element_blank(), axis.ticks.y  = element_blank()) +
   scale_fill_manual(values = cols) +
   scale_x_date(expand=c(0,0)) +
   ylab("Particulate Pollution (index of poor air quality)") +
   xlab("Black Summer 19/20")

Results show:

Stream plot

Labelling the first line I've tried:

annotate(aes(xintercept= as.numeric(ymd("2019-10-26"))),y=+Inf,label="Ignite",vjust=2,geom="label") +

but it throws

"Error: Invalid input: date_trans works with objects of class Date only"

Any help would be greatly appreciated.

Upvotes: 1

Views: 1285

Answers (1)

stefan
stefan

Reputation: 124083

The are multiple issues with your annotate:

  1. annotate has no mapping argument. Hence, using aes(...) results in an error as it is passed (by position) to the x argument. And as aes(...) will not return an object of class Date it will throw an error.

  2. As you want to add a label use x instead of xintercept. geom_label. has no xintercept aesthetic.

  3. 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")

Upvotes: 2

Related Questions