【问题标题】:How to set background color of ggplot and facet_grid in R?如何在 R 中设置 ggplot 和 facet_grid 的背景颜色?
【发布时间】:2013-10-25 20:07:02
【问题描述】:

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

【问题讨论】:

  • geom_rect 层应该先行
  • 我在导致此错误的 mtcars 数据上进行了尝试:Discrete value supplied to continuous scale,但是它适用于我实际绘制的数据,但是当我将它用作颜色时仍然给出奇怪的结果(两个图例,并填充箱线图 / facets_grids 混合)
  • 类似,但我认为让我很难过的是箱线图的填充和侧面背景的填充不知何故相互干扰,也许目前根本不可能跨度>
  • 好吧,经过更多的摆弄,这可以解决问题:p &lt;- p + scale_x_discrete()(在 ggplot 之后,然后是 geom_rect 之后),但知道我正在尝试手动设置颜色,但没有成功。有什么提示吗?

标签: r ggplot2


【解决方案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)

【讨论】:

  • 如果您使用的是颜色的命名向量,那么顺序应该不重要,至少在新版本的 ggplot2 中是这样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-11
  • 2021-11-09
  • 2018-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多