2016-04-04 16 views
2

Ich möchte Facetten, wo jede Facette ihre eigene Legende hat, mit Code von this answer by joran plotten. Die Farben der Punkte sollten einem Faktor zugeordnet werden, aber nicht jede Facette enthält alle Faktorstufen, daher werden die Farben/Beschriftungen inkonsistent zugewiesen. Kann ich das irgendwie beheben?Facetten mit eigener Legende aber konsistente Farbabbildung

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 

Grundstück mit nur einer Legende:

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")) 

enter image description here

Grundstück mit Legende für jede Facette aber "falsch" Farben/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) 

enter image description here

Antwort

2

Immer genannten Vektoren in scale_*_manual verwenden, wenn Sie Werte, um eine korrekte Zuordnung angeben:

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) 

resulting plot

Verwandte Themen