How to put geom_vline manually in ggplot legend (r)

239 views Asked by At

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

1

There are 1 answers

0
UseR10085 On BEST ANSWER

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