user3022875 user3022875 - 1 month ago 15
R Question

ggplot object not found error when adding layer with different data

I have a plot with some points and I'd like to use segment to connect them

dummy = data.frame(GROUP=c("A","B","C","D"),
X = c(80,75,68,78),
Y=c(30, 32,36,33)

)
df= data.frame(x1 = c(80), x2 =c(78) , y1=c(30), y2 =c(33))
df
library(ggplot2)
ggplot(dummy,aes(x=X,y=Y,color=GROUP)) +
geom_point() +
geom_segment(aes(x=x1,y=y1,xend= x2, yend =y2), data = df)


but I get this error

Error in eval(expr, envir, enclos) : object 'GROUP' not found


What am I doing wrong here?

Answer

Aesthetic mapping defined in the initial ggplot call will be inherited by all layers. Since you initialized your plot with color = GROUP, ggplot will look for a GROUP column in subsequent layers and throw an error if it's not present. There are 3 good options to straighten this out:

Option 1: Set inherit.aes = F in the layer the you do not want to inherit aesthetics. Most of the time this is the best choice.

ggplot(dummy,aes(x = X, y = Y, color = GROUP)) + 
  geom_point() +
  geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2),
               data = df,
               inherit.aes = FALSE) 

Option 2: Only specify aesthetics that you want to be inherited (or that you will overwrite) in the top call - set other aesthetics at the layer level:

ggplot(dummy,aes(x = X, y = Y)) + 
  geom_point(aes(color = GROUP)) +
  geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2),
               data = df) 

Option 3: Specifically NULL aesthetics on layers when they don't apply.

ggplot(dummy,aes(x = X, y = Y, color = GROUP)) + 
  geom_point() +
  geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2, color = NULL),
               data = df) 

Which to use?

Most of the time option 1 is just fine. It can be annoying, however, if you want some aesthetics to be inherited by a layer and you only want to modify one or two. Maybe you are adding some errorbars to a plot and using the same x and color column names in your main data and your errorbar data, but your errorbar data doesn't have a y column. This is a good time to use Option 2 or Option 3 to avoid repeating the x and color mappings.)