ggplot2:如何合并来自两个不同地理数据集的shapefile?

6

我正在尝试在ggplot中绘制一些与英国和爱尔兰有关的地理位置数据。运行以下代码,我可以成功地将此制表符分隔文件中的某些值映射到这里找到的GBR shapefile数据(国家=大不列颠):

library(rgdal)
library(ggplot2)
library(rgeos)
library(plyr)

#this data comes from http://www.gadm.org/country (download the Great Britain data set, and set path to the downloaded data's topmost directory)
shape.dir <- "C:\\Users\\Douglas\\Desktop\\estc_clean_analysis\\geoanalysis\\GBR_adm" 

#the first parameter we pass to readOGR species the location of the shapefile we want to read in; layer indicates which shapefile in that dir we want to read in. Data via UK shapefile from http://www.gadm.org/country
uk.shp <- readOGR(shape.dir, layer = "GBR_adm2")

#read in csv with values by county
small_geo_data <- read.csv(file = "small_geo_sample.txt", header=TRUE, sep="\t", na.string=0, strip.white=TRUE)

#fortify prepares the data for ggplot
uk.df <- fortify(uk.shp, region = "ID_2") # convert to data frame for ggplot

#now combine the values by id values in both dataframes
combined.df <- join(small_geo_data, uk.df, by="id")

#now build plot up layer by layer
ggp <- ggplot(data=combined.df, aes(x=long, y=lat, group=group)) 
ggp <- ggp + geom_polygon(aes(fill=value))         # draw polygons
ggp <- ggp + geom_path(color="grey", linestyle=2)  # draw boundaries
ggp <- ggp + coord_equal() 
ggp <- ggp + scale_fill_gradient(low = "#ffffcc", high = "#ff4444", 
                                 space = "Lab", na.value = "grey50",
                                 guide = "colourbar")
ggp <- ggp + labs(title="Plotting Values in Great Britain")
# render the map
print(ggp)

运行该代码会产生以下结果:enter image description here

现在我想要做的是将有关爱尔兰的数据添加到我的图表中。我从同一网站下载了“IRL”形状文件,该网站提供了GBR形状文件,但接下来我遇到了一系列障碍。我尝试结合IRL_adm1.csvGBR_adm2.csv(将前者中的id值重命名以避免冲突),但什么都没成功。在继续寻找笨拙的解决方案之前,我想在SO上发表以下问题:是否有一个相对简单的方法来将GBR和IRL文件组合在一个图表中?如果其他人能够提供任何想法或建议,我将非常感激。


我的观点可能有偏见,但我会先尝试将两个shape文件合并成一个,然后再使用像这样的工具进行可视化 http://gis-programming.com/?p=194 或者 http://gis.stackexchange.com/questions/25061/how-to-merge-multiple-layers-to-one-layer-using-qgis。你可能会遇到的问题是,你想要使用adm2来表示gbr,而irl只有adm1,如果它也有adm2,事情可能会更容易... 我会尝试以某种方式保护irl的id_1和gbr的id_2,并提出统一的id,然后在r/ggplot中与你的数据连接起来。 - yosukesabai
我刚刚尝试了使用ogr2ogr的方法。我可以得到合并的形状文件,其中id_2对于英国具有有效值,而对于爱尔兰部分的多边形,id_2为null。因此,我将想出id_duhaime,根据它是爱尔兰还是英国选择id_1和id_2,同时避免冲突,然后使用您的ID准备您的txt文件。 - yosukesabai
非常感谢您的想法,yosukesabai!请查看下面的简单解决方案——它像魔法一样有效。 - duhaime
1个回答

6
如果你的英国和爱尔兰的shapefile使用相同的投影/坐标系,你可以像这样将两个图层添加到一个绘图中,而不需要像这样加入它们:
ggplot() +
  geom_polygon(data = gbrshapefortified, aes(long, lat, group = group)) +
  geom_polygon(data = irlshapefortified, aes(long, lat, group = group)) +
  coord_equal()

也就是说,如果你只是绘制图层并且你要绘制的主题值彼此之间没有依赖关系,那么你不需要将它们组合起来。


太棒了!非常感谢! - duhaime
很高兴能够帮到你。 - Phil
是的,这看起来比我建议的要容易得多。 - yosukesabai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接