我想使用this answer by joran中的代码绘制每个方面都有自己图例的方面。点的颜色应该映射到一个因子,但不是每个面都包含每个因子级别,因此颜色/标签的分配不一致。我能以某种方式解决这个问题吗?
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"))
绘制每个方面的图例但是&#34;错误&#34;颜色/标签
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)
答案 0 :(得分:3)
如果指定值以确保正确映射,则始终在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)