Home > Software engineering >  Generating a custom legend with ggplot
Generating a custom legend with ggplot

Time:12-04

I have a plot I'm generating with ggplot() in R, and I'd like to generate a legend which explains the vertical dotted line which I've overlaid on the data, not the data itself. Is it possible to create a custom legend with an explanation of the geom_vline component alone?

My code is something like this:

ggplot(weektotals, aes(x=week, y=total))   geom_line(color="red")   geom_point()   geom_vline(xintercept=as.Date("27/03/20", format = "%d/%m/%y"), linetype="dotted", color="darkred", size=1)

Thanks in advance!

CodePudding user response:

Without data the question is not reproducible, however using the economics built-in dataset you could adapt this code, which allows adjustment of legend text inputs, to suit...

library(ggplot2)

ggplot(head(economics, 12)) 
  geom_point(aes(date, pop)) 
  geom_vline(aes(xintercept = as.Date("1967-11-01", format = "%Y-%m-%d"), colour = "colour"), linetype = "dotted", size = 2) 
  scale_colour_manual(breaks = "colour", values = "red", label = "vline label") 
  labs(colour = "legend title")

Created on 2021-12-03 by the reprex package (v2.0.1)

  • Related