每个方面都有自己的图例,但颜色映射一致

Facets with own legend each but consistent colour mapping

我想使用 this answer by joran 中的代码绘制各个方面,其中每个方面都有自己的图例。点的颜色应该映射到一个因子,但不是每个面都包含每个因子水平,因此 colours/labels 分配不一致。我能以某种方式解决这个问题吗?

dat <- structure(list(group1 = structure(c(1L, 1L, 2L, 2L), .Label = c("A", "B"), class = "factor"), group2 = structure(c(1L, 2L, 1L, 3L), .Label = c("a", "b", "c"), class = "factor"), x = 1:4, y = 1:4), .Names = c("group1", "group2", "x", "y"), row.names = c(NA, -4L), class = "data.frame")

  group1 group2 x y
1      A      a 1 1
2      A      b 2 2
3      B      a 3 3
4      B      c 4 4

只有一个图例的情节:

library(ggplot2)
ggplot(dat) +
  geom_point(aes(x=x, y=y, colour=group2)) +
  facet_wrap(~group1) +
  scale_colour_manual(values=c("green", "red", "blue"), labels=c("green", "red", "blue"))

为每个方面绘制图例,但 "wrong" colours/labels:

library(gridExtra)
dat <- split(dat, f = dat$group1)

p1 <- ggplot(dat$A) +
  geom_point(aes(x=x, y=y, colour=group2)) +
  facet_wrap(~group1) +
  scale_colour_manual(values=c("green", "red", "blue"), labels=c("green", "red", "blue"))

p2 <- p1 %+% dat$B

grid.arrange(p1, p2, ncol=2)

如果您指定值以确保正确映射,请始终在 scale_*_manual 中使用命名向量:

p1 <- ggplot(dat$A) +
  geom_point(aes(x=x, y=y, colour=group2)) +
  facet_wrap(~group1) +
  scale_colour_manual(values=c(a = "green", b = "red", c = "blue"), 
                      labels=c(a = "green", b = "red", c = "blue"),
                      drop = FALSE)

p2 <- p1 %+% dat$B

grid.arrange(p1, p2, ncol=2)