使用annotate时ggmap和错误(geom =“text”)

时间:2015-03-17 14:01:52

标签: r ggplot2 ggmap annotate

我在普林斯顿不同地点的流量数据框架。

# dput(count)
structure(list(intersection = structure(c(11L, 9L, 10L, 12L, 
6L, 3L, 7L, 2L, 4L, 1L, 5L, 8L), .Label = c("CherryHillat206", 
"ElmatRidgeRd", "FacultyatHarrison", "HarrisonatLake", "HarrisonbetwHamilton", 
"MerceratLoversLane", "ProvinceLineatMercer", "RiverRdat27", 
"Rt 27 Bank", "Rt. 27 River Rd", "US206 Cambelton", "US206Princeton Ave."
), class = "factor"), traffic = c(19352, 18697, 12493, 21554, 
10871, 13310, 7283, 11408, 12055, 6415, 14100, 5739), lat = c(40.3475418, 
40.3487282, 40.3711205, 40.3909988, 40.3403702, 40.3434601, 40.343689, 
40.3440514, 40.3454819, 40.3627014, 40.3658734, 40.3738098), 
lon = c(-74.6711197, -74.6630707, -74.62323, -74.6541214, 
-74.6720123, -74.647049, -74.7051392, -74.7334671, -74.6390533, 
-74.6648483, -74.6596518, -74.6207962), class = structure(c(1L, 
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("primary", 
"secondary"), class = "factor")), .Names = c("intersection", 
"traffic", "lat", "lon", "class"), row.names = c(NA, -12L), class = "data.frame")

library(ggplot2)
library(ggmap)

map <- get_map(location = 'princeton', zoom = 13, maptype = "road")

ggmap(map) +
geom_point(data = count, aes(x = lon, y = lat)) + 
annotate("text", x = -74.7, y = 40.4, label = "TEST anno")

早期的问题1 conflict with annotate in other package没有用2 solution to create another data frame

每条评论编辑 - 我收到的错误消息:

Error: 'x' and 'units' must have length > 0

这是绘图,显示轴上的边界。

enter image description here

1 个答案:

答案 0 :(得分:3)

在研究这个案例后,我认为Error: 'x' and 'units' must have length > 0表示地图中不存在注释点。

str(map)
# chr [1:1280, 1:1280] "#F0EDE4" "#F0EDE4" "#F0EDE4" "#F0EDE4" ...
# - attr(*, "class")= chr [1:2] "ggmap" "raster"
# - attr(*, "bb")='data.frame': 1 obs. of  4 variables:
#  ..$ ll.lat: num 40.3
#  ..$ ll.lon: num -74.7
#  ..$ ur.lat: num 40.4
#  ..$ ur.lon: num -74.6

如果你看上面的lon和lat值,-74.7和40.4是bbox的值。但是,看到错误消息,可能不包括bbox值。如果是这样,如果你想让你的注释点在x = -74.7,y = 40.4,你需要另一种方法。我的方法是获得具有小缩放值的​​地图(例如,缩放= 12)并使用scale_x_continuousscale_y_continuous修剪地图。通过这种方式,我确保注释点保留在地图中。顺便说一下,下面的地图缺少一个数据点。如果你想在地图中使用它,你需要使用lon / lat值。

map2 <- get_map(location = 'princeton', zoom = 12, maptype = "road")

ggmap(map2) +
geom_point(data = mydf, aes(x = lon, y = lat)) + 
annotate("text", x = -74.7, y = 40.4, label = "TEST anno") +
scale_x_continuous(limits = c(-74.71, -74.6)) +
scale_y_continuous(limits = c(40.3, 40.4))

enter image description here