我想:
所需的输出是
到目前为止我的失败尝试。提前感谢您的帮助!
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"))
答案 0 :(得分:5)
这是一个很好的问题,我看过几个黑客。这很棘手,因为两个geoms都映射到颜色,每个美学只能得到一个传奇。这是一种方式:实际上制作单独的传说,每个传说具有不同的美学,并将它们伪装成一个传奇。
对于该行,我将“Line”映射到linetype并对颜色进行硬编码,而不是映射到颜色。然后我将线型比例设置为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,以便创建填充图例,但实际上并不显示填充。
答案 1 :(得分:2)
他们必须成为同一个传奇的一部分吗?如果没有,那么你可以使用&#39; fill&#39;多边形的审美和“颜色”。线条审美:
ggplot(dat, aes(x = x, y = y)) +
geom_polygon(aes(fill = "Border", group = id), colour="black") +
geom_line(data = line, aes(colour = "Line"), size = 1) +
scale_fill_manual(values=c(NA))