how to add a vertical line on a factor?

Consider this simple example


tibble(crazyfactor = c(ymd('2019-01-01'),
                       ymd('2019-01-02'),
                       ymd('2019-01-04')),
       value = c(1,3,2)) %>% 
  mutate(crazyfactor = as.factor(crazyfactor)) 
# A tibble: 3 x 2
  crazyfactor value
  <fct>       <dbl>
1 2019-01-01      1
2 2019-01-02      3
3 2019-01-04      2

I would like to create a simple barchart with a vertical line on a few selected dates. The tricky thing is that my dates are factors (no, I cant change that! :slight_smile: ). Simply running the following does not work

tibble(crazyfactor = c(ymd('2019-01-01'),
                       ymd('2019-01-02'),
                       ymd('2019-01-04')),
       value = c(1,3,2)) %>% 
  mutate(crazyfactor = as.factor(crazyfactor)) %>% 
  ggplot(aes(x = crazyfactor, y = value)) + geom_bar(stat = 'identity')+
  geom_vline(aes(xintercept = '2019-01-02'))
Error in UseMethod("rescale") : 
  no applicable method for 'rescale' applied to an object of class "character"

What is wrong here? What should I do?
Thanks!

You can do it like this

library(tidyverse)
library(lubridate)

tibble(crazyfactor = ymd(c('2019-01-01', '2019-01-02', '2019-01-04')),
       value = c(1,3,2)) %>%
    mutate(crazyfactor = as.factor(crazyfactor)) %>% 
    ggplot(aes(x = crazyfactor, y = value)) +
    geom_bar(stat = 'identity') +
    geom_vline(aes(xintercept = which(levels(crazyfactor) == '2019-01-02')))

Created on 2019-08-26 by the reprex package (v0.3.0.9000)

Note: Please remember to include library calls in your reprex next time

2 Likes

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