合并shapefile中的国家/省以使用ggplot2进行绘图

时间:2019-03-15 15:08:03

标签: r ggplot2 gis

我正在尝试在地图上绘制有关加拿大的一些省级数据。但是,我的一些数据汇总到了区域中,因此我需要在地图上合并一些省份。我知道数据中的省份与某些地区(阿尔伯塔省是大草原的一部分)重叠,但这就是我所拥有的。

我要绘制的示例数据:

data_to_plot <- data.frame(province = c("Alberta", "Atlantic Canada", "British Columbia", 
                                        "Ontario", "Prairies", "Quebec"),
                           data = runif(6, 1E6, 1E8))

可以下载here用于加拿大的省份shapefile。

到目前为止我尝试过的事情:

library(tidyverse)
library(rgdal)

# Import the shape file
shapefile <- readOGR("[path to shape file]", "Canada")
shapefile_df <- fortify(shapefile, region = "NAME")
shapefile_df$id[shapefile_df$id == "Yukon Territory"] <- "Yukon"

# Replace `id` with new region name, where applicable
shapefile_df <- shapefile_df %>%
  mutate(id = case_when(id %in% c("New Brunswick", "Nova Scotia", "Prince Edward Island") ~ "Atlantic Canada",
                        id %in% c("Saskatchewan", "Manitoba") ~ "Prairies",
                        TRUE ~ id))

# Merge map data with data to plot
map.data <- full_join(shapefile_df, data_to_plot, by = c("id" = "province"))

# Plot the map
ggplot(map.data) +
  geom_polygon(aes(x = long, y = lat, group = id, fill = data),
               size = 0, alpha = 0.9) +
  geom_path(aes(x = long, y = lat, group = group),
            color = "grey", size = 0.5, alpha = 0.5)

如下所示,这会造成混乱。最好我还要删除同一地区内各省之间的所有边界。我承认我对形状文件或GIS不太了解,所以请告诉我我想做的事是否不可能。

example_plot

2 个答案:

答案 0 :(得分:0)

要使fortify制作的数据框正常工作,行必须按制作时的原始顺序排列,否则,您会得到在加拿大北部看到的怪异效果。如果要进行任何合并和联接,我想向强化对象添加行ID。所以:

shapefile <- readOGR("[path to shape file]", "Canada")
shapefile_df <- fortify(shapefile, region = "NAME")
shapefile_df$row_id <- 1:nrow(shapefile_df)

然后重命名变量并执行联接等操作,并在绘制之前执行以下操作:

shapfile_df <- shapefile_df %>% arrange(row_id)

答案 1 :(得分:0)

我知道这个问题很旧,但是出于完整性考虑,我第二次建议卡米尔使用sf。这是你要的吗?

library(sf)
library(dplyr)
library(ggplot2)

data_to_plot <- data.frame(
    province=c("Alberta", "Atlantic Canada", "British Columbia", "Ontario", "Prairies", "Quebec"),
    data=runif(6, 1E6, 1E8)
)
shapefile <- st_read('/temp/r/Canada/Canada.shp')
shapefile$NAME <- as.character(shapefile$NAME)
shapefile$NAME[shapefile$NAME == "Yukon Territory"] <- "Yukon"

# Replace `id` with new region name, where applicable
shapefile <- shapefile %>%
  mutate(NAME = case_when(NAME %in% c("New Brunswick", "Nova Scotia", "Prince Edward Island") ~ "Atlantic Canada",
                        NAME %in% c("Saskatchewan", "Manitoba") ~ "Prairies",
                        TRUE ~ NAME))

# Merge map data with data to plot
map.data <- full_join(shapefile, data_to_plot, by = c("NAME"="province"))

ggplot() +
    geom_sf(data=map.data, aes(fill=data))

enter image description here