我有一个相当复杂的多面箱图,我想让两组更加明显,例如:通过为facet的背景着色,但也可以对2个facet_grids进行分组,或者在2个区域周围添加边框。
我尝试根据变量的因子修改facet_grid中某些网格的背景颜色:
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 + geom_boxplot()
p <- p + facet_grid(. ~ type)
p <- p + geom_rect(aes(xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf, fill=factor(typeColor)))
show(p)
但是我无法正确地将geom_rect绘制到背景中(填充boxplot和填充geom_rect会互相干扰),并且还不知道其他解决方案。
答案 0 :(得分:0)
好的我已经得到它,很难,因为订单很重要:
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"))
show(p)