je2018
je2018

Reputation: 127

How to solve the conflict between fill and facet_grid in R when inserting text in a ggplot?

I can straightforwardly insert text in a faceted ggplot using the following code

mpg_plot <- ggplot(mpg, aes(x = displ, y = hwy)) +
  geom_point() +
  facet_grid(. ~ drv)

f_labels <- data.frame(drv = c("4", "f", "r"), label = c("4wd", "Front", "Rear"))
mpg_plot +
  geom_text(x = 6, y = 40, aes(label = label), data = f_labels)

However, I get an "Error in FUN(X[[i]], ...) : object 'cyl' not found" if I try to provide colors like in the following example.

mpg$cyl = as.factor(mpg$cyl)
ggplot(mpg, aes(x = displ, y = hwy, fill=cyl)) +
  geom_point(aes(col=cyl)) +
  scale_fill_manual(values = c("red","blue","green","yellow")) +
  facet_grid(. ~ drv) +
  geom_text(x = 6, y = 40, aes(label = label), data = f_labels)

mpg_plot

In that scenario, the resulting plot has neither color, nor the annotation. Is there a way to make fill compatible with facet_grid?enter image description here

Upvotes: 0

Views: 35

Answers (1)

stefan
stefan

Reputation: 123783

The issue is that your dataset f_labels has no column cyl which you specified as a global aes via fill=cyl. Simply removing it will fix your issue. Also, as the default shape for points has no fill aes you have to switch to scale_color_manual to color your points:

library(ggplot2)

f_labels <- data.frame(drv = c("4", "f", "r"), label = c("4wd", "Front", "Rear"))
mpg_plot +
  geom_text(x = 6, y = 40, aes(label = label), data = f_labels)
#> Error in eval(expr, envir, enclos): object 'mpg_plot' not found

mpg$cyl <- as.factor(mpg$cyl)
ggplot(mpg, aes(x = displ, y = hwy)) +
  geom_point(aes(col = cyl)) +
  scale_color_manual(values = c("red", "blue", "green", "yellow")) +
  facet_grid(. ~ drv) +
  geom_text(x = 6, y = 40, aes(label = label), data = f_labels)

Upvotes: 3

Related Questions