【问题标题】:How to customize background colors in faceted plots with ggplot如何使用 ggplot 在多面图中自定义背景颜色
【发布时间】:2020-10-19 08:07:50
【问题描述】:

我想单独控制多面图中面板和图的背景颜色。使用提示 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))

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

【问题讨论】:

    标签: r ggplot2 facet


    【解决方案1】:

    使用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()
    

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

    ggplot(mtcars, aes(mpg, wt)) +
      geom_rect(data = ann_text, aes(fill = I(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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-14
      • 2021-11-09
      • 2011-09-12
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 2011-03-15
      相关资源
      最近更新 更多