简体   繁体   English

如何在R中设置ggplot和facet_grid的背景颜色?

[英]How to set background color of ggplot and facet_grid in R?

I have a rather complicated faceted boxplot in which I would like to make two groups more distinguishable, eg by coloring the background of the facets, but grouping 2 facet_grids would be possible, too, or adding a border around the 2 areas. 我有一个相当复杂的多面箱线图,其中我想使两组更加可区分,例如,通过对小面的背景进行着色,但是也可以对2个facet_grids进行分组,或者在这2个区域周围添加边框。

I tried to modify the background color for certain grids in a facet_grid based on the factor of a variable: 我试图根据变量的因子修改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)

but I can't manage to plot a geom_rect into the background properly (fill of boxplot and fill of geom_rect are disturbing each other), and don't know about other solutions, yet. 但是我无法设法将geom_rect正确地绘制到背景中(boxplot的填充和geom_rect的填充相互干扰),并且还不知道其他解决方案。

ok I've got it, tough one, cause the order is important: 好吧,我已经做到了,艰难的,因为顺序很重要:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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