簡體   English   中英

如何在R中設置ggplot和facet_grid的背景顏色?

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

我有一個相當復雜的多面箱線圖,其中我想使兩組更加可區分,例如,通過對小面的背景進行着色,但是也可以對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的填充相互干擾),並且還不知道其他解決方案。

好吧,我已經做到了,艱難的,因為順序很重要:

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