如何使用ggmap在城市地图中有条件地为点添加标签

时间:2016-08-12 19:27:48

标签: r ggplot2 ggmap geom-text

我试图在地图上使用名称为城市标记点。

数据

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 任何帮助表示赞赏

1 个答案:

答案 0 :(得分: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