3

I would like to control the background colors for panels and plots in a faceted plot individually. Using hints in this answer, I was able to create something that almost works, but still has two issues:

  1. Colors do NOT appear as I defined them - colors appear different by cell, but colors look 'strange' - as is they were some overlay
  2. I cannot control panel and plot bg colors separately

Here's my code so far:

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

I would have liked to use something like the line below inside theme(), but of course(?!) that didn't work:

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

Any ideas what would give me the opportunity to specify the background color for panels and plots?

Atitlan
  • 33
  • 3

1 Answers1

0

Use 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

Or, you can wrap the aesthetic in 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()
Paul
  • 8,734
  • 1
  • 26
  • 36