Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

r - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...