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
319 views
in Technique[技术] by (71.8m points)

r - ggplot2 - highlighting selected points and strange behavior

I want to highlight selected points and encountered some strange behaviour. First some dummy data:

a <- 1:50
b <- rnorm(50)
mydata <- data.frame(a=a,b=b)
ggplot(mydata,aes(x=a,y=b)) + geom_point()

This works correctly. Now,to highlight some points, I add another geom_point layer:

ggplot(mydata[20:40,],aes(x=a,y=b)) + 
    geom_point() + 
    geom_point(aes(x=a[c(10,12,13)],y=b[c(10,12,13)]),colour="red")

Note that I am displaying only a limited range of the data ([20:40]). Now comes the strange behavior:

ggplot(mydata[10:40,],aes(x=a,y=b)) + 
    geom_point() + 
    geom_point(aes(x=a[c(10,12,13)],y=b[c(10,12,13)]),colour="red")

Changing the size of the selected range, I get an error, roughly translated from German: Error...: Arguments implying different number of rows. Strangely, this varies with the selected range. [23:40] will work, [22:40] won't.


The error in English is:

Error in data.frame(x = c(19L, 21L, 22L), y = c(0.28198, -0.6215,  : 
  arguments imply differing number of rows: 3, 31
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If your data is different between different layers, then you need to specify the new data for each layer.

You do this with the data=... argument for each geom that needs different data:

set.seed(1)
mydata <- data.frame(a=1:50, b=rnorm(50))
ggplot(mydata,aes(x=a,y=b)) + 
  geom_point(colour="blue") +
  geom_point(data=mydata[10:13, ], aes(x=a, y=b), colour="red", size=5)

enter image description here


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

...