2016-08-12 42 views
1

我試圖在地圖上使用名稱有條件地爲城市標記點。如何使用ggmap有條件地在城市地圖中添加標籤

數據

name |s Latitude |s Longitude |s Frequency 

Pelham Bay Park | 40.865556 | -73.808333 | 32 

Greenbelt  | 40.58846 | -74.139073 | 10 

Van Cortlandt Park | 40.8978 | -73.8839 | 3 

Flushing Meadows–Corona Park | 40.745833 | -73.844722 | 5 

Central Park | 40.783333 | -73.966667 |22 

代碼

library(ggmap) 
town <- get_map(location = "New York", zoom = 10) 

mapPoints <- ggmap(town) + 
    geom_point(aes(x = work_count$Longitude, y = work_count$Latitude, size = work_count$Frequency), data = work_count, alpha = .5) + 
geom_text(aes(label=ifelse(work_count$Frequency>quart(work_count$Frequency)[2],as.character(work_count$name),'')),hjust=0,vjust=0) 

quart <- function(x) { 
    x <- sort(x) 
    n <- length(x) 
    m <- (n+1)/2 
    if (floor(m) != m) { 
    l <- m-1/2; u <- m+1/2 
    } else { 
    l <- m-1; u <- m+1 
    } 
    c(Q1=median(x[1:l]), Q3=median(x[u:n])) 
} 
mapPoints 

我得到以下錯誤: 錯誤:美學必須是長度爲1或相同的數據(5) :標籤,x,y 任何幫助表示讚賞

+0

它更容易幫助您繪製的問題,如果你提供一個[重複的例子(http://stackoverflow.com/questions/5963269/how-to-make-a-great- r-reproducible-example)與樣本輸入數據,因此我們可以運行您的代碼來查看錯誤並測試可能的解決方案。 – MrFlick

+0

您可能希望預處理標籤,而不是在'geom_text'中即時計算它們,即'work_count $ labels < - ifelse(work_count $ Frequency> quart(work_count $ Frequency)[2],as.character(work_count $ name),''))',然後將其傳遞給'geom_text'。 –

+0

@黃偉煌我已經完成了一個專欄,只有符合我的標準的條目才存在,剩下的都是空的。然後我將work_count $標籤傳遞給geom_text中的標籤字段,但無法獲得輸出結果 –

回答

2

這似乎工作。

work_count$lab <- ifelse(work_count$Frequency>quart(work_count$Frequency)[2], 
    as.character(work_count$name), '') 

mapPoints <- ggmap(town, 
        base_layer = ggplot(work_count, 
        aes(x = Longitude, y = Latitude))) + 
    geom_point(aes(size = Frequency), 
      alpha = .5) + 
    geom_text(aes(label = labels), 
      vjust = 0, 
      hjust = 0) 
mapPoints 

enter image description here

+0

謝謝。 「ggmap(鎮, base_layer = ggplot(數據= work_count,AES(X =經度, Y =緯度, 標籤=標籤)))+ geom_point(填充= 「黑」,α-= 0.8,AES(X = work_count $ Longitude,y = work_count $ Latitude,size = work_count $ Frequency),shape = 21)+ geom_text()'也爲我解答。如果我們一次同時處理多個城市和一個輸入,您是否知道如何動態縮放城鎮變量? –

+0

事實上,在'ggmap(...)中指定'data'和'aes()'是很方便的。,base_layer = ggplot(...))'。我編輯了我的答案以反映這一點。 (另外,正如其他人上面提到的,一旦你在'ggplot(data = ...)'或者'geom_中指定了數據,你就不需要在你的geoms中包含所有'work_count $ ...' *(data = ...)'。)關於動態縮放的問題本身就是一個單獨的問題! –

+0

在這種情況下,我們如何只標註滿足其他顏色條件的點。在這種情況下,佩勒姆灣公園。 –

相關問題