问题描述
我正在尝试将带有标签和点的省份和城市的标签合并到南非地图中。我可以从网站 https://gadm.org/download_country_v3.html
的 spdf 文件中获取带有省级细分的地图SA1spdf <- readRDS("gadm36_ZAF_1_sp.rds")
我正在尝试使用插槽中的信息:
SA1spdf@data@ADM1_EN
包含9个省的标签 如果可能的话,我想将标签放在多边形的中心,所以我得到了 9 个省的质心:
centroids_SAdf <- as.data.frame(coordinates(SA1spdf))
并将名称 V1 和 V2 更改为经度和纬度
names(centroids_SAdf) <- c("Longitude","Latitude")
我还想在图中添加一些城市:
coordinates_cities <- data.frame(city = c("Cape Town","Durban","Johannesburg","Port Elizabeth"),lat = c(-33.930,-29.870,-26.190,-33.960 ),lon = c(18.460,30.990,28.040,25.590 )
但我无法将所有这些链接在一起。
我可以通过以下方式获取地图:
qtm(SA1spdf,fill = "white")
qtm(SA1spdf,fill = "white") + tm_text("SA1spdf$data#ADMN1_EN")
tm_shape(SA1spdf) + tm_polygons() + tm_fill(col = "white")
我没有得到一张白色填充的地图,它是灰色的
tm_shape(SA1spdf) + tm_polygons() + tm_text(c("Eastern Cape","Free State","Gauteng","KwaZulu-Natal","Limpopo","mpumalanga","north West","Nothern Cape","Western Cape"))
ggplot(SA1spdf,aes(x = lon,y = lat),group = group) + geom_polygon(fill = "white") + geom_point(data = coordinates_cities,aes(x = lat,y = lon)) + geom_text(data= coordinate_cities,aes(label = city))
解决方法
library(sp)
library(ggplot2)
library(tmap)
library(rgeos)
我将使用您使用 ZAF 中的数据创建的同一对象 SA1spdf
作为 GADM 中的 sp 对象
coordinate_cities <- data.frame(
city = c("Cape Town","Durban","Johannesburg","Port Elizabeth"),lat = c(-33.930,-29.870,-26.190,-33.960),long = c(18.460,30.990,28.040,25.590))
基础图
plot(SA1spdf)
points(coordinate_cities$lon,coordinate_cities$lat,pch = 16,col = "red",cex = 1)
text(coordinate_cities$lon,coordinate_cities$city,adj = c(0,0),cex = 0.7)
title(main = "South Africa",sub = "Main cities")
ggplot2
sa_df <- fortify(SA1spdf)
#> Regions defined for each Polygons
ggplot(sa_df,aes(long,lat)) +
geom_polygon(aes(group = group),fill = "white",colour = "black") +
geom_point(data = coordinate_cities,aes(x = long,y = lat),colour = "red") +
geom_text(data = coordinate_cities,aes(label = city),vjust = -1) +
coord_equal()
tmap
# convert coordinate_cities to sp object
sa_cities_spdf <- SpatialPointsDataFrame(coords = coordinate_cities[,c("long","lat")],data = coordinate_cities[,"city",drop = FALSE],proj4string = CRS("+proj=longlat +datum=WGS84"))
tm_shape(SA1spdf) +
tm_borders() +
tm_layout(main.title = "South Africa regions") +
tm_text("NAME_1",size = 0.7) +
tm_shape(sa_cities_spdf) + tm_symbols(size = 0.5,col = "red")
由 reprex package (v0.3.0) 于 2021 年 6 月 17 日创建