如何使用ggplot自定义多面图中的背景颜色

问题描述

我想分别控制多面图中面板和图的背景颜色。使用提示 this answer,我能够创建几乎可行的东西,但仍然存在两个问题:

  1. 颜色没有像我定义的那样出现-颜色在每个单元格中看起来都不同,但是颜色看起来很“奇怪”-因为它们有些重叠
  2. 我无法分别控制面板并绘制背景色

到目前为止,这是我的代码

ann_text <- data.frame(mpg = c(22,15,30),wt = c(4,5,2),cyl = factor(c(4,6,8),levels = c("4","6","8")),lab = c("Text 1","Text 2","Text 3"),hue = c("pink","yellow","lightblue"))
 
ggplot(mtcars,aes(mpg,wt)) +
  geom_rect(data = ann_text,aes(fill = hue),xmin = -Inf,xmax = Inf,ymin = -Inf,ymax = Inf,alpha = 0.3) +
  geom_text(data = ann_text,mapping = aes(x = mpg,y = wt,label = lab)) +
  theme(panel.background = element_blank(),panel.grid.major.y = element_line(color = "grey")) +
  facet_grid(. ~ cyl) +
  geom_point()

result of my code with 'Strange' colors

我本来想在theme()内使用下面的代码,但是当然不能使用(?!):

plot.background = element_rect(data = ann_text,mapping = aes(fill = hue))

有什么想法能让我有机会指定面板和绘图的背景颜色吗?

解决方法

使用scale_fill_identity

ggplot(mtcars,aes(mpg,wt)) +
  geom_rect(data = ann_text,aes(fill = hue),xmin = -Inf,xmax = Inf,ymin = -Inf,ymax = Inf,alpha = 0.3) +
  geom_text(data = ann_text,mapping = aes(x = mpg,y = wt,label = lab)) +
  theme(panel.background = element_blank(),panel.grid.major.y = element_line(color = "grey")) +
  facet_grid(. ~ cyl) +
  geom_point() +
  scale_fill_identity()

enter image description here

或者,您也可以将美学包装在I

ggplot(mtcars,aes(fill = I(hue)),panel.grid.major.y = element_line(color = "grey")) +
  facet_grid(. ~ cyl) +
  geom_point()