我试图在地图上绘制一些关于加拿大的省级数据。但是,我的一些数据汇总到了区域中,所以我需要在地图上组合一些省份。我知道我的数据中的省份与一些地区重叠(艾伯塔省是大草原的一部分),但这就是我所拥有的。
我要绘制的示例数据:
data_to_plot <- data.frame(province = c("Alberta", "Atlantic Canada", "British Columbia",
"Ontario", "Prairies", "Quebec"),
data = runif(6, 1E6, 1E8))
有省份的加拿大shapefile可以下载here。
到目前为止我尝试了什么:
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知之甚少,所以如果我想做什么是不可能的,请告诉我。
对于由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)
我知道这个问题很老,但为了完整起见......我第二次提出使用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))