【问题标题】:ggplot2: Combine shapefiles from two different geodatasetsggplot2:组合来自两个不同地理数据集的 shapefile
【发布时间】:2015-01-27 16:42:42
【问题描述】:

我正在尝试在 ggplot 中绘制一些与英国和爱尔兰有关的地理位置数据。运行以下代码,我可以成功地将this tab-separated file 中的一些值映射到找到here 的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)

运行该代码产生:

我现在想做的是将与爱尔兰有关的数据添加到我的绘图中。我从提供 GBR shapefile 的same site 下载了“IRL”shapefile,但后来遇到了一系列障碍。我尝试将IRL_adm1.csvGBR_adm2.csv 组合在一起(重命名前者的id 值以避免冲突),但还没有任何效果。在破解其余的方法以获得一个笨拙的解决方案之前,我想我应该停下来并在 SO 上发布以下问题:是否有一种相当简单的方法可以将 GBR 和 IRL 文件组合在一个情节中?对于其他人可以就这个问题提出的任何想法或建议,我将不胜感激。

【问题讨论】:

  • 我的观点可能有偏见,但我会先尝试将两个形状文件合并为一个,然后再使用 gis-programming.com/?p=194gis.stackexchange.com/questions/25061/… 之类的工具将它们可视化。您可能会看到的问题是您想将 adm2 用于 gbr 而 irl 只能用于 adm1,如果它也有 adm2,事情可能会更容易......我会尝试以某种方式保护 irl 的 id_1 和 gbr 的 id_2 并提出统一id,然后在 r/ggplot 中加入你的数据
  • 我刚刚尝试了使用ogr2​​ogr的方法。我可以获得合并的形状文件,其中 id_2 对英国具有有效值,对于爱尔兰部分的多边形,id_2 为空。所以我会想出 id_duhaime 选择 id_1 和 id_2 取决于它是爱尔兰还是英国,同时避免冲突,然后使用你的 ID 准备你的 txt 文件。
  • 非常感谢您的想法,yosukesabai!看看下面的简单解决方案——它就像一个魅力

标签: r ggplot2 geolocation gis shapefile


【解决方案1】:

如果您的英国和爱尔兰 shapefile 使用相同的投影/CRS,您可以将两个图层添加到绘图中,而无需像这样加入它们:

ggplot() +
  geom_polygon(data = gbrshapefortified, aes(long, lat, group = group)) +
  geom_polygon(data = irlshapefortified, aes(long, lat, group = group)) +
  coord_equal()

即如果您只是绘制图层并且您绘制的主题值不相互依赖,则不需要将它们组合起来。

【讨论】:

  • 壮观!非常感谢!
  • 很高兴。很高兴它有帮助。
  • 是的,这看起来比我建议的要容易得多
猜你喜欢
  • 2013-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-06
相关资源
最近更新 更多