ggplot2:组合来自两个不同地理数据集的shapefile

时间:2014-11-29 03:24:48

标签: r ggplot2 geolocation gis shapefile

我试图在ggplot中绘制一些与英国和爱尔兰有关的地理数据。运行以下代码,我可以成功地将this tab-separated file中的一些值映射到找到here的GBR shapefile数据(country = Great Britain):

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

我现在要做的是将有关爱尔兰的数据添加到我的情节中。我从提供GBR shapefile的same site下载了“IRL”shapefile,但后来遇到了一系列障碍。我尝试过组合IRL_adm1.csvGBR_adm2.csv(在前者中重命名id值以避免冲突),但还没有任何工作。在将剩下的工作分解为kludgy解决方案之前,我认为我应该停止并在SO上发布以下问题:是否有一种相当直接的方法将GBR和IRL文件合并到一个图中?我非常感谢其他人可以就这个问题提出的任何想法或建议。

1 个答案:

答案 0 :(得分:5)

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

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

即。如果您只是绘制图层并且您正在密谋的主题值并不相互依赖,那么您就不需要将它们组合在一起。