我想要:
所需的输出将是
到目前为止,我的尝试失败。预先感谢您的任何帮助!
library(ggplot2)
set.seed(1337)
dat <- structure(list(id = structure(c(2L, 2L, 2L, 2L),
.Label = c("1.1", "1.2", "1.3", "2.1", "2.2", "2.3"),
class = "factor"),
value = c(3.1, 3.1, 3.1, 3.1),
x = c(2.2, 1.1, 1.2, 2.5),
y = c(0.5, 1, 2.1, 1.7)),
class = "data.frame",
row.names = c(NA, -4L))
line <- data.frame(
x = cumsum(runif(50, max = 0.1)),
y = cumsum(runif(50, max = 0.1))
)
ggplot(dat, aes(x = x, y = y)) +
geom_polygon(aes(color = "Border", group = id), fill = NA) +
geom_line(data = line, aes(colour = "Line"), size = 1) +
theme(legend.background = element_rect(fill = "transparent"),
legend.box.background = element_rect(fill = "transparent", colour = NA),
legend.key = element_rect(fill = "transparent"))
我看到了一些技巧,这是一个很好的问题。这很棘手,因为两个几何图形都映射到颜色,并且每种美学只能得到一个图例。这是一种方法:实际制作单独的图例,每个图例具有不同的美学效果,并将它们伪装成一个图例。
对于线条,我没有将其映射为颜色,而是将“ Line”映射为线型并对颜色进行了硬编码。然后,将线型比例设置为1,以实线表示。在中guides
,我取出了线型的标题并设置了顺序,以便颜色首先出现,然后是线型。现在有两个图例,但下一个没有标题。为使它们看起来像一个连续的图例,请在图例之间设置一个负间距。当然,如果您还有其他图例,这将无法正常工作,在这种情况下,您将需要一些不同的技巧。
library(ggplot2)
ggplot(dat, aes(x = x, y = y)) +
geom_polygon(aes(color = "Border", group = id), fill = NA) +
geom_line(aes(linetype = "Line"), data = line, color = "blue") +
scale_linetype_manual(values = 1) +
guides(linetype = guide_legend(title = NULL, order = 2), color = guide_legend(order = 1)) +
theme(legend.background = element_rect(fill = "transparent"),
legend.box.background = element_rect(fill = "transparent", colour = NA),
legend.key = element_rect(fill = "transparent"),
legend.spacing = unit(-1, "lines") )
请注意,您可以使用多种不同的美学组合,而不仅仅是颜色+线型。您可以改为映射到多边形的填充上,然后将其alpha设置为0,以便创建填充图例,但实际上并没有显示为填充。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句