简体   繁体   中英

How to prevent scale_fill_manual + geom_boxplot + geom_rect to screw the legend?

I'm coloring the fill of a faceted boxplot with geom_rect. When I manually set the fill color color with scale_fill_manual I can't distinguish between the boxplot fill and the geom_rect fill, which screws my legend:

伊姆古尔

mtcars$type <- "Small"
mtcars$type[mtcars$cyl >= 6] <- "Medium"
mtcars$type[mtcars$cyl >= 8] <- "Big"
mtcars$type <- factor(mtcars$type)

mtcars$typeColor <- "black"
mtcars$typeColor[mtcars$cyl >= 8] <- "white"
mtcars$typeColor <- factor(mtcars$typeColor)

p <- ggplot(mtcars, aes(factor(gear), mpg, fill=factor(gear)))
p <- p + scale_x_discrete()
p <- p + geom_rect(aes(xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf, fill=(typeColor)))
p <- p + geom_boxplot()
p <- p + facet_grid(. ~ type)
p <- p + scale_fill_manual( values = c("black" = "black","white" = "white","3" = "green","4" = "red","5" = "blue"), limits=c("3","4","5"))
show(p)

Any hints how to prevent that?

Tell geom_rect to not show its guide:

ggplot(mtcars, aes(factor(gear), mpg, fill=factor(gear))) + 
        scale_x_discrete() + 
        geom_rect(aes(xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf, fill=(typeColor)),
                  show.legend = FALSE) + 
        geom_boxplot() + 
        facet_grid(. ~ type) + 
        scale_fill_manual(values = c("black" = "black","white" = "white","3" = "green","4" = "red","5" = "blue"), 
                          limits=c("3","4","5"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM