如何将任何(不相关的)图例映射到现有的ggplot?
免责声明:请不要恨我 . 我知道使用'ggplot2'创建图例的最佳方法是正确地映射您的数据,我99%的时间都这样做 . 然而,我要求的东西一般可以给我任何我想要的传奇 .
作为一个例子,我有一个看起来像这样的情节:
从这段代码创建:
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
我想添加一个包含以下内容的图例:
-
一条红色的,垂直的垂直线,叫做"l1"
-
一条黑色,实心的水平线,叫做"l2"
-
一个名为"l3"的绿色填充块
理想情况下,我会产生这样的(前面的伪代码):
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"))
我最好的猜测如何处理这个将是创建一些辅助伪数据 temp
绘制/映射在图上看不见的地方,然后用于创建图例,但我没有成功得到这样的东西给我一个传奇 .
再一次,我的想法是如何将任何不相关的图例添加到现有的图中,即没有将原始数据巧妙地映射到绘图变量?
1 回答
可以从头开始构建图例:使用
grid
构建图例元素;然后使用gtable
定位图例中的元素和图中的图例 . 这有点粗糙,但给出了一般的想法 .