ggmap: 使用 ggplot2 进行空间可视化绘图(下篇)

浏览: 3300

作者:戴维 · 卡尔 & 哈德利 · 威克姆,翻译:李博。

原文:ggmap: Spatial Visualization with ggplot2

原文发布于作者知乎、简书,欢迎大家关注支持。本文已获作者授权原创形式发布,欢迎点击【阅读原文】查看!    

知乎:https://www.zhihu.com/people/li-bo-90-94/pins/posts     

简书:http://www.jianshu.com/u/43365c904dba

PS:由于原文较长,故翻译分为三次进行(会进行多次修正)。

9ggmap 的实用函数   

ggmap 有几个实用函数,可以帮助探索空间数据分析。

image.png

从地址转换到经度 / 纬度坐标的方式,实际上是对空间数据进行可视化的必要条件。但问题是,这一过程几乎总是要通过使用必要的地理信息系统(GIS)、同时需要保存结果并将其导入到 R 中,最后在 R 外部完成。

而 geocode(地理编码)函数将该过程简化为 R 中一行命令。

geocode 是一个向量化函数, 它接受字符串并返回地理信息的数据集。在 output =“simple” 的默认情况下,只返回经纬度。

这些实际上是 Mercator 对 1984 年世界大地测量系统(WGS84)的普遍预测,这是 Google Maps 使用球形地球模型的来源。当 output=“more” 时,会返回一个较大的数据集,该数据集提供了更多的 Google 地理编码信息:

> geocode("baylor university", output = "more")
lon lat type loctype address north south east
1 -97.11441 31.54872 university approximate [long address] 31.55823 31.53921 -97.0984
west postal_code country administrative_area_level_2
1 -97.13042 76706 united states mclennan
administrative_area_level_1 locality street streetNo point_of_interest
1 texas waco s 5th st 1311 <NA>

#在个人电脑上运行后情况

> library(ggmap)

#谷歌地图API服务条款。Google Maps API Terms of Service: http://developers.google.com/maps/terms.
> geocode("baylor university", output = "more")
Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=baylor%20university&sensor=false
        lon      lat          type     loctype
1 -97.11431 31.54984 establishment approximate
                                          address    north    south      east      west
1 1301 s university parks dr, waco, tx 76798, usa 31.55119 31.54849 -97.11297 -97.11566
  street_number                        route locality administrative_area_level_2
1          1301 South University Parks Drive     Waco             McLennan County
  administrative_area_level_1       country postal_code
1                       Texas United States       76798

特别是,各级政府机构的报告。若设定 output=“all" 时,则返回整个 JSON 对象,该对象由谷歌地理编码 API 解析。参考下面的代码。

## output = "all"的时,返回详细信息情况(节选一部分)。

> library(ggmap)
> geocode("baylor university", output = "all")
Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=baylor%20university&sensor=false
$results
$results[[1]]
$results[[1]]$address_components
$results[[1]]$address_components[[1]]
$results[[1]]$address_components[[1]]$long_name
[1] "1301"
$results[[1]]$address_components[[1]]$short_name
[1] "1301"
$results[[1]]$address_components[[1]]$types
[1] "street_number"

地理编码 API 有一些防止滥用的要求限制。

一个未指明的短期 rate(见图文) 以及 24 小时 2500 个请求的限制,通过隐藏的全局变量可以在一定程度上进行检测。

GooglegGocodeQueryCount 和输出函数 geocodequerycheck,geocode 使用它们监控自己的进度,要么(1)根据使用情况调整运行速度或(2)如果查询超出限制则弹出一个错误提示,值得注意是,revgeocode 共享相同的请求响应,同时是由相同的变量和函数监测。

要了解更多关于谷歌地理编码、距离矩阵,和 API 方向的使用规则,请参考文献中列出的网站。

002.revgeocode 函数     

在某些情况下,将经度 / 纬度坐标转换为物理地址是很有用的,使用 revgeocode 函数这样做是可能的,不过这将依赖于 Google 地理编码 API。

> gc <- geocode("baylor university")
> (gc <- as.numeric(gc))
[1] -97.11441 31.54872
> revgeocode(gc)
[1] "S 1st St, Baylor University, Waco, TX 76706, USA"
Like geocode , more output can be provided as well –
> revgeocode(gc, output = "more")
address route establishment neighborhood locality
1 [long address] S 1st St Baylor University Baylor Waco
administrative_area_level_2 administrative_area_level_1 country postal_code
1 McLennan Texas United States 76706

因此,除了反向地理编码的物理位置 (即: 地址),revgeocode 可以报告在不同尺寸级别上的情况。最后,output="all" 选项可以返回 Google 报告的整个 JSON 对象。

003.mapdist 函数    

在空间环境中,计算人们常说的 “距离” 的能力,是很了不起的事,因此这也为 GIS 输送了大量的分析人员。使用 Google Distance Matrix AI,ggmap 能够为 Google 提供驾驶,骑自行车或步行路线的距离。除了距离之外,Google 还会报告预计的剩余时间。输出结果存放在易于使用的数据集中。

例如:

> from <- c("houston", "houston", "dallas")
> to <- c("waco, texas", "san antonio", "houston")
> mapdist(from, to)
from to m km miles seconds minutes hours
1 houston waco, texas 298004 298.004 185.1797 11907 198.45 3.307500
2 houston san antonio 320764 320.764 199.3227 11997 199.95 3.332500
3 dallas houston 387389 387.389 240.7235 14592 243.20 4.053333

自己运行后情况

> library(ggmap)

载入需要的程辑包:ggplot2

Google Maps API Terms of Service: http://developers.google.com/maps/terms.
Please cite ggmap if you use it: see citation('ggmap') for details.
> from <- c("houston", "houston", "dallas")
> to <- c("waco, texas", "san antonio", "houston")
> mapdist(from, to)
by using this function you are agreeing to the terms at :
http://code.google.com/apis/maps/documentation/distancematrix/
Information from URL : http://maps.googleapis.com/maps/api/distancematrix/json?origins=dallas&destinations=houston&mode=driving&sensor=false
Information from URL : http://maps.googleapis.com/maps/api/distancematrix/json?origins=houston&destinations=waco+texas%7Csan+antonio&mode=driving&sensor=false
     from          to      m      km    miles seconds  minutes    hours
1 houston waco, texas 298587 298.587 185.5420   10332 172.2000 2.870000
2 houston san antonio 317170 317.170 197.0894   10474 174.5667 2.909444
3  dallas     houston 385035 385.035 239.2607   12476 207.9333 3.465556

上面默认的运输工具是汽车。然而,其它模式也是可用的。输入的形式,可以是物理地址(理想),或(“白宫”),或地理坐标(即反向地理编码)。当输出默认为上面所看到的数据集格式时,设置 output=“all”,则从谷歌获取完整的 JSON 对象。

Distance Matrix API 将用户限制为每个查询 100 个请求,每 10 秒 100 个请求,每 24 小时 2500 个请求。在能够轻松监控这些限制的情况下,导出函数 distQueryCheck 可帮助用户跟踪其剩余的查询次数。它依赖于隐藏的全局变量 ".GoogleDistQueryCount(谷歌距离查询数量)"

> distQueryCheck()
2495 distance queries remaining.
> .GoogleDistQueryCount
time url elements
1 2012-03-16 00:12:11 [url used] 1
2 2012-03-16 00:16:10 [url used] 2

如果用户超过了查询上限,mapdist 要么(1)暂停,直到到短期的请求限制已经失效或(2)报错,如果没有查询的话。因此,它几乎与用于地理编码的原理相同。如果用户认为这不正确,则 mapdist 参数规范 “override_limit = TRUE” 可以覆盖。

mapdist 输出的数据集非常便于用 ggplot2 绘图。图 11 提供一个例子。从一个位置到附近好几个位置的距离,(1)可以使用 mapdist 进行测定。(2)使用 cut 可以进行分类,(3)使用一个 qmap 组合进行绘图。比如:geom_text 和 geom_rect。可以用布景对行程时间分类。完整的代码在 ggmap 文档的示例部分中。

image.png

图 11

image.png

route 函数提供构成两个位置之间路线序列的地图距离。每条路线都具有开始和结束经度 / 纬度坐标,以及与 mapdist 报告的相同单位的距离和持续时间。按照序列组成的路线集,构成了一个单独的,并可使用 geom_leg 绘制的路线。

图 12 中可以看到,使用 geom_leg 绘制路线,就是一个很好例证,其中在相同的两个位置之间绘制了三条路线。这些可以使用 route 函数中的 “alternatives = TRUE” 参数获得。备选方案要求是,从起点到目的地的多条路线;返回值添加到一个附加变量数据集中,用于路由标识符(A,B,C 等)。

legs_df <- route(

’marrs mclean science, baylor university’,

’220 south 3rd street, waco, tx 76701’,

alternatives = TRUE

)

qmap(’424 clay avenue, waco, tx’, zoom = 15, maptype = ’hybrid’,

base_layer = ggplot(aes(x = startLon, y = startLat), data = legs_df)) +

geom_leg(

aes(x = startLon, y = startLat, xend = endLon, yend = endLat,

colour = route),

alpha = 3/4, size = 2, data = legs_df

) +

labs(x = ’Longitude’, y = ’Latitude’, colour = ’Route’) +

facet_wrap(~ route, ncol = 3) + theme(legend.position = ’top’)

image.png

与地图距离一样,在给定时间内可以请求的路线同样受到限制。留下的查询数由 “.GoogleRouteQueryCount” 变量与 “routeQueryCheck” 函数进行监控。

绘制形状文件

作为最后一个例子,这可能太常见了以至于被忽略,用 ggmap 绘制形状文件是一件轻而易举的工作,可以通过几种方式完成。最简单的方法是使用 fortify(ggplot2),并通过点 / 路径 / 多边形图层添加到地图方法,将形状文件转换为数据框。可以通过简单的更多的 Geom 层来添加附加层。

图 13 显示绘制美国 2000 年人口普查,以及完整代码的基本示例。

# get an example shape file#获取一个示例形状文件
download.file(’http://www.census.gov/geo/cob/bdy/tr/tr00shp/tr48_d00_shp.zip’,
destfile = ’census.zip’)
# unzip, and load tools#解压缩和载入工具
unzip(’census.zip’); library(maptools); library(gpclib); library(sp);
gpclibPermit()
# read data into R#读取数据到R中
shapefile <- readShapeSpatial(’tr48_d00.shp’,
proj4string = CRS("+proj=longlat +datum=WGS84"))
# convert to a data.frame for use with ggplot2/ggmap and plot#转换数据框,使用 ggplot2/ggmap 进行绘图
data <- fortify(shapefile)
qmap(’texas’, zoom = 6, maptype = ’satellite’) +
geom_polygon(aes(x = long, y = lat, group = group), data = data,
colour = ’white’, fill = ’black’, alpha = .4, size = .3)

image.png

建立在 ggplot2 之上,ggmap 为可视化空间数据提供了几个新的有用工具。从理论上说,分层图形的语法尝试强制绘图的兼容性,从而实现良好的绘图实践。但实际上,在 ggplot2 上构建 ggmap 可以使结果更好,因为 ggplot2 的全部功能都接受了考验。

未来的一些发展方向,应该在 ggmap 存储包中。新的 osmar 包集成了 R 和 OpenStreetMap 数据结构,Stamen Maps 和 CloudMade Maps 被渲染,从而打开了使用 ggmap(Eugster 和 Rug)在 R 上绘制地图或卫星图像的可能性。或者,与 R 中的其它空间包集成的,可以为空间数据分析提供几个非常实用的工具。最后,Google Elevation API 和 Places API 提供了更多有趣的探索,可以像其它 Google API 一样融入 ggmap 框架,为用户提供额外的功能,而且可以免费提供地理数据。

感谢和参考资料略,详见原文。

ggmap: Spatial Visualization with ggplot2

http://vita.had.co.nz/papers/ggmap.pdf

推荐 1
本文由 EasyCharts 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册