ggplot, vline, date x-axis: Need vline Drawn from a List of Dates

I looked at some posts on this forum, but they did not provide the answer for my situation, as well other websites, for example: https://statisticsglobe.com/draw-vertical-line-to-x-axis-of-class-date-in-ggplot2-plot-in-r

Generally, after looking at some posts in this forum, this code would work if I provide one specific date explicitly, but if I bring in a list of dates for x-intercept of vertical lines, it would not work.

library(tidyverse)
library(ggplot2)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union

# Sample time series data
df = data.frame(yearr = sample(2015:2021, 2000, replace = TRUE),
                monthh = sample(1:12, 2000, replace = TRUE),
                dayy = sample(1:29, 2000, replace = TRUE)) |>
  mutate(datee = ymd(paste(yearr, monthh, dayy)),
         yy = sample(0:100, 2000, replace = TRUE) + (130 * yearr) + (2 * monthh)) |>
  filter(!is.na(datee)) |>
  arrange(-desc(datee)) |>
  mutate(ii = row_number())
#> Warning: 2 failed to parse.

df_dates_of_interest = df |>
  filter(yearr == 2013)
l_dates_of_interest = df_dates_of_interest$datee

gg = df |>
  ggplot() +
  geom_line(aes(y = yy,
                x = datee)) +
  geom_vline(aes(xintercept = l_dates_of_interest))

#gg # NOT WORKING

Created on 2022-01-21 by the reprex package (v2.0.1)

Might it be because there is no 2013 in your sample?

Oops, typo making reprex

The problem still stands. Even if changed to 2018, it won't work

Error: Aesthetics must be either length 1 or the same as the data

gg = df |>
  ggplot() +
  geom_line(aes(y = yy, x = datee)) +
  geom_vline(data = as.data.frame(l_dates_of_interest), aes(xintercept = as.Date(l_dates_of_interest)))
gg
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.