1

我有一个相当复杂的多面箱线图,我想让两个组更容易区分,例如通过为小平面的背景着色,但也可以将 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 的填充相互干扰),并且还不知道其他解决方案。

4

1 回答 1

1

好的,我知道了,很难,因为顺序很重要:

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)
于 2013-10-17T13:52:48.953 回答