如何将两个地图合并为一个? [英] How to join two maps into one in r?
问题描述
我想知道是否有办法将两个sp类地图合并为一个。
例如瑞典+挪威,有一个代码(shp数据是从 http://www.gadm.org/country ):
library(maptools)
mapa_shp_swe< - readShapePoly(C:/r/SWE_adm/SWE_adm0.shp)
mapa_map_swe< - fortify(mapa_shp_swe);
swe< - ggplot(mapa_map_swe,aes(x = long,y = lat,group = group))+
geom_path(size = 1)+
theme_bw()
mapa_shp_nor< - readShapePoly(C:/r/NOR_adm/NOR_adm0.shp)
mapa_map_nor < - fortify(mapa_shp_nor)
也不<-ggplot(mapa_map_nor,aes(x = long, y = lat,group = group))+
geom_path(size = 1)+
theme_bw()
我个人倾向于在 rgdal 中使用
spRbind()
/ code>包,因为我总是在处理shapefile时加载它。
#ensure shapefil (chpa_shp_swe,polygons))
newShape < - spChFIDs(mapa_shp_nor,as.character(n))
#实际连接
newShape < - spRbind(newShape,mapa_shp_swe)
#如果您愿意,您可以编写它
writeOGR(sweNor,dsn =shapes /,layer =newShape,
driver =ESRI Shapefile)
在 shapes /
目录中合并了两个原始形状文件的shapefile,名为 sweNor
。
至于绘制城市,@cmbarbu指出这应该是一个单独的问题,但您可以尝试添加以下代码:
ggplot(newShape,aes(x = long,y = lat,group = group))+
geom_path(size = 1)+
geom_point(data = cities, aes(x = x,y = y))+
theme_bw()
没有经过测试,所以没有保证!
I am wondering if there is a way to join two maps of class "sp" into one.
For example Sweden + Norway, there is a code (shp data were downloaded from: http://www.gadm.org/country):
library(maptools)
mapa_shp_swe <- readShapePoly("C:/r/SWE_adm/SWE_adm0.shp")
mapa_map_swe <- fortify(mapa_shp_swe)
swe <- ggplot(mapa_map_swe, aes(x = long, y = lat, group=group)) +
geom_path(size=1) +
theme_bw()
mapa_shp_nor <- readShapePoly("C:/r/NOR_adm/NOR_adm0.shp")
mapa_map_nor <- fortify(mapa_shp_nor)
nor <- ggplot(mapa_map_nor, aes(x = long, y = lat, group=group)) +
geom_path(size=1) +
theme_bw()
Personally I tend to use the spRbind()
function in the rgdal
package, because I tend to have this loaded when working with shapefiles anyway.
# ensure shapefiles have unique ids
n <- length(slot(mapa_shp_swe, "polygons"))
newShape <- spChFIDs(mapa_shp_nor, as.character(n))
# the actual join
newShape <- spRbind(newShape, mapa_shp_swe)
# you can then write it if you wish
writeOGR(sweNor, dsn = "shapes/", layer = "newShape",
driver = "ESRI Shapefile")
Which should write a new shapefile called sweNor
with both original shapefiles merged in the shapes/
directory.
As for plotting the cities, as @cmbarbu points out this should really be asked as a separate question, but you could try adding the following code:
ggplot(newShape, aes(x = long, y = lat, group=group)) +
geom_path(size=1) +
geom_point(data = cities, aes(x = x, y = y)) +
theme_bw()
I haven't tested this yet so there's no guarantee!
这篇关于如何将两个地图合并为一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!