gpt4 book ai didi

r - 在带有R的传单 map 上显示SpatialPolygonsDataFrame

转载 作者:行者123 更新时间:2023-12-04 11:36:44 25 4
gpt4 key购买 nike

我想在传单 map 上显示加拿大的多边形。

# create map
library(leaflet)
m = leaflet() %>% addTiles()
m

我能够找到加拿大的多边形: http://www.gadm.org/country
我为R选择了SpatialPolygonsDataFrame格式,但还有其他可用格式(例如Shapefile)
# load object in R
load("country_polygons/CAN_adm0.RData")
pol_can <- gadm

如何在 map 上显示形状?我假设我必须利用sp软件包,但是我不知道该怎么做。
在此先感谢您的帮助!

最佳答案

您可以按照docs here的2.2节将SpatialPolygons*对象传递给addPolygons函数。

例如(请注意,以下内容包括〜11.4 MB下载):

library(sp)
download.file('http://biogeo.ucdavis.edu/data/gadm2/R/CAN_adm0.RData', f <- tempfile())
load(f)
leaflet() %>% addTiles() %>% addPolygons(data=gadm, weight=2)

请注意,GADM数据也可以使用 getData包中的 raster函数下载:
library(raster)
can <- getData('GADM', country='VAT', level=0)

编辑

作为回应,我真的很喜欢 Natural Earth提供的轻量级多边形数据集。在下面的示例中,我从自然地球下载了1:50,000,000个国家的shapefile(Admin 0),并将其子集分配给当前的英联邦成员国,然后进行绘制。压缩的shapefile小于1 MB。
library(rgdal)
library(leaflet)

download.file(file.path('http://www.naturalearthdata.com/http/',
'www.naturalearthdata.com/download/50m/cultural',
'ne_50m_admin_0_countries.zip'),
f <- tempfile())
unzip(f, exdir=tempdir())

world <- readOGR(tempdir(), 'ne_50m_admin_0_countries', encoding='UTF-8')

commonwealth <- c("Antigua and Barb.", "Australia", "Bahamas", "Bangladesh",
"Barbados", "Belize", "Botswana", "Brunei", "Cameroon", "Canada", "Cyprus",
"Dominica", "Fiji", "Ghana", "Grenada", "Guyana", "India", "Jamaica", "Kenya",
"Kiribati", "Lesotho", "Malawi", "Malaysia", "Maldives", "Malta", "Mauritius",
"Mozambique", "Namibia", "Nauru", "New Zealand", "Nigeria", "Pakistan", "Papua
New Guinea", "Rwanda", "St. Kitts and Nevis", "Saint Lucia", "St. Vin. and
Gren.", "Samoa", "Seychelles", "Sierra Leone", "Singapore", "Solomon Is.",
"South Africa", "Sri Lanka", "Swaziland", "Tanzania", "Tonga", "Trinidad and
Tobago", "Tuvalu", "Uganda", "United Kingdom", "Vanuatu", "Zamibia")

leaflet() %>% addTiles() %>%
addPolygons(data=subset(world, name %in% commonwealth), weight=2)

关于r - 在带有R的传单 map 上显示SpatialPolygonsDataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29118059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com