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.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…