How can I map any (unrelated) legend to an existing ggplot?
Disclaimer: please don't hate me. I know the best way to create a legend with 'ggplot2' is to map your data right and I do it 99% of the time. Here however I am asking for something that in general can give me any legend I want.
As an example I have a plot that looks somewhat like this:
created from this code:
set.seed(42)
temp1 = cbind.data.frame(begin = rnorm(10, 0, 1), end = rnorm(10, 2, 1), y1 = 1:10, y2 = 1:10, id = as.character(1:10))
temp2 = cbind.data.frame(x = 0:2, y = 1:3*2)
temp3 = cbind.data.frame(x = seq(0.5, 1.5, 0.33))
temp = c()
plot1 = ggplot(data = temp, aes(x = x)) +
geom_vline(data = temp3, aes(xintercept = x), color = "red", linetype = "longdash") +
geom_segment(data = temp1, aes(y = y1, yend = y2, x = begin, xend = end, color = id)) +
geom_point(data = temp2, aes(x = x, y = y), shape = 4, size = 4) +
scale_color_discrete(guide = F)
plot1
and I want to add a legend that contains:
- a red, longdashed vertical line called "l1"
- a black, solid horizontal line called "l2"
- a green filled block called "l3"
ideally I would produce that somewhat like this (pseudo-code ahead):
plot2 = plot1 + guide(elements = list(list(type = "line", color = "red", linetype = "longdash", direction = "vertical", label = "l1"), list(type = "line", label = "l2"), list(type = "rect", fill = "green", label = "l3"))
my best guess how to approach this would be to create some auxiliary pseudo-data temp
that is plotted/mapped somewhere invisible on the plot and then used to create the legend, but I was not successful in getting anything like this to plot me a legend.
Once more, the idea is how can I add any unrelated legend to an existing plot, i.e. without clever mapping of the original data to the plot variables?
geom_text
andgeom_line
. – Roman Luštrikgrid
and grobs. Or try and write an extension to ggplot2 to do this. I imagine someone will eventually do the latter as similar questions pop up a lot. – Mike Wise