Geom vline on histogram with dates

Hi all

I am unsure how to make a histogram using one df and use a second date from to add geom_vlines with text saying, in this case, Event A and Event B

df <- structure(list(id = 1:30, date = structure(c(18429, 18421, 18425, 
18429, 18430, 18424, 18428, 18418, 18418, 18424, 18423, 18422, 
18424, 18426, 18425, 18423, 18422, 18421, 18422, 18424, 18423, 
18425, 18426, 18418, 18429, 18425, 18426, 18424, 18422, 18420
), class = "Date")), row.names = c(NA, -30L), class = c("tbl_df", 
"tbl", "data.frame"))


my_dates <- structure(list(date = structure(c(18418, 16967), class = "Date"), 
    event = c("Event A", "Event B")), row.names = c(NA, -2L), class = c("tbl_df", 
"tbl", "data.frame"))

Something like this:

Thanks :slight_smile:

Hi @Nilafhiosagam,

I think this should get you on the right path:

library(tidyverse)
df <- structure(
  list(id = 1:30, 
       date = structure(c(18429, 18421, 18425, 18429, 18430,
                          18424, 18428, 18418, 18418, 18424,
                          18423, 18422, 18424, 18426, 18425,
                          18423, 18422, 18421, 18422, 18424,
                          18423, 18425, 18426, 18418, 18429,
                          18425, 18426, 18424, 18422, 18420
                        ), class = "Date")), 
  row.names = c(NA, -30L), 
  class = c("tbl_df", "tbl", "data.frame")
  )

vline_date <-
  slice_sample(df, n = 2)

ggplot() +
  geom_histogram(data = df, aes(date)) +
  geom_vline(data = vline_date, aes(xintercept = date), 
             colour = "red", size = 2)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Brilliant thanks so much. My df had the dates as dttm which prevented my from adding the vline on top it seems? Adding as.Date to the aesthetic was what I needed to add, in addition to your code. Thanks!

  ggplot() +
  geom_histogram(data = df, aes(x = as.Date(date)), 
                 bins = 100) +
  geom_vline(data = key_dates, aes(xintercept = date), colour = "red")

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.