2012-07-13 61 views
7

我想突出顯示選定的點並遇到一些奇怪的行爲。首先一些虛擬數據:r - ggplot2 - 突出顯示選定的點和奇怪的行爲

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

這個工作正常。現在,要強調幾點,我再添geom_point層:

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

注意,我只顯示數據([20:40])的範圍有限。現在到了奇怪的現象:

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

更改選定範圍的大小,我得到一個錯誤,從德國大致翻譯:Error...: Arguments implying different number of rows。奇怪的是,這與選定的範圍有所不同。 [23:40]將工作,[22:40]不會。


英語中的錯誤是:

Error in data.frame(x = c(19L, 21L, 22L), y = c(0.28198, -0.6215, : 
    arguments imply differing number of rows: 3, 31 
+0

我希望你不介意,但我已在英國 – csgillespie 2012-07-13 09:54:03

回答

22

如果你的數據是不同層之間的不同,那麼你需要爲每個層指定新的數據。

你這樣做與data=...論據需要不同的數據每個geom

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

+0

好了錯誤,數據其實並沒有什麼區別,只是不同的子集。但是這個解決方案至少是穩定的。僅使用明確的命名('data = ...')。但沒有解釋爲那個奇怪的錯誤... – lambu0815 2012-07-13 12:52:02

+0

@ lambu0815事實上,這是一個不同的子集使它不同。你有這個奇怪的錯誤,因爲你試圖將一個審美(x)映射到三個不同的元素。美學必須映射到列名稱。你也不必明確指定'data = ...'參數,但是你需要按照正確的順序,即geom_point(aes(...),data,...) – Andrie 2012-07-13 14:24:53

0

另一種選擇加入的條件,這兩個屬性,顏色和大小,裏面geom_point。然後我們手動控制分別使用scale_colour_manualscale_size_manual的那些。

set.seed(1) 
mydata <- data.frame(a = 1:50, b = rnorm(50)) 
ggplot(mydata) + 
    geom_point(aes(x = a, y = b, colour = a > 9 & a < 14, size = a > 9 & a < 14)) + 
    scale_colour_manual(values = c("blue", "red")) + 
    scale_size_manual(values =c(1, 4))+ 
    theme(legend.position = "none") 

enter image description here