rggplot2geom-vline

How to put geom_vline manually in ggplot legend (r)


I want to make a plot with a vertical line to represent the beggining of a policy. How can I add this vertical line to the legend of the plot?

example:

df <- tibble(year = 2010:2014, value = c(1,2,3,3,4))

df %>% 
    ggplot(aes(x = year, y = value)) + 
    geom_line() + 
    geom_vline(xintercept = 2012, linetype = 4)

I've tried show_legend = T but nothing happens. This is the plot enter image description here


Solution

  • You have to take xintercept = 2012, linetype = "dotdash" part inside aes() like the following code to show the legend

    df %>% 
      ggplot(aes(x = year, y = value)) + 
      geom_line() + 
      geom_vline(aes(xintercept = 2012, linetype = "dotdash"))+
      scale_linetype_manual(values=c("dotdash"), name = "vline") +
      theme_bw()
    

    enter image description here