1

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.

Peter
  • 11,500
  • 5
  • 21
  • 31
Paul Smith
  • 11
  • 2
  • 1
    Hard to tell without having your data to play with (maybe give us a minimal data set as described here: https://stackoverflow.com/q/5963269), but if your x-axis is a Date field, I don't understand why you have the `as.numeric()` in your `xintercept`s – Hobo Jan 16 '22 at 06:24

1 Answers1

2

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

stefan
  • 90,330
  • 6
  • 25
  • 51