首页 > 解决方案 > R:带有 ggplot2 的 Choropleth 地图(连接属性)

问题描述

我试图使用 ggplot2 和瑞士的公共形状文件创建一个等值线图(它包含在这个 zip 文件中:PLZO_PLZ.shp)

library(rgdal)    
library(ggplot2)   
library(ggmap)   
library(broom)

# Load Shapefile
shapefile <- readOGR(file.choose())

# Next the shapefile has to be converted to a dataframe for use in ggplot2
shapefile_df <- fortify(shapefile)

ggplot(data = shapefile_df) +
  geom_path(aes(x = long, y = lat, group = group),  color="black") +
  theme_void() 

结果如下所示:

在此处输入图像描述

但是,我不想只绘制地图,我还想根据某些属性为不同的城市着色。每个自治市都有一个四位数的邮政编码(称为“PLZ”)。这些值可以在 中看到shapefile$PLZ

但是我怎样才能将属性分配给某些城市呢?一个例子:

fakeData <- data.frame(PLZ = c(8001, 8002, 8048), values = c(20, 40, 99))

我想为市镇 8001、8002 和 8048 着色。但是如何将变量values加入shapefileor shapefile_df?这样我就可以像这样绘制它:

ggplot(data = shapefile_df) +
  geom_path(aes(x = long, y = lat, group = group, fill = values),  color="black") +
  theme_void() 

如果我在错误消息上尝试“left_join”,shapefile则该方法不适用于“c('SpatialPolygonsDataFrame','SpatialPolygons','Spatial')”类的对象。然而shapefile_df,不再有变量PLZ了。我也试过

shapefile@data$id <- rownames(shapefile@data)
shapefile_df <- fortify(shapefile, region = "PLZ")

这导致以下错误:Error in maptools::unionSpatialPolygons(cp, attr[, region]) : isTRUE(gpclibPermitStatus()) is not TRUE

标签: rggplot2tidyverseshapefile

解决方案


我建议使用该sf包来读取 shapefile。然后你可以left_join毫无问题地做。最后,您可以使用绘图geom_sf并将 NA 的填充默认值从灰色更改为透明使用scale_fill_distiller(您也可以为非 NA 值选择填充调色板)。

library(sf)

# Read shapefile as sf
shapefile_df <- st_read(file.choose())

# Left_join by PLZ
shapefile_df <- shapefile_df %>%
  left_join(fakeData, by = "PLZ")

# Do plot
ggplot(shapefile_df, 
       aes(fill = values)) + 
  # Plot sf 
  geom_sf(show.legend = F) +
  # Indicate fill palette and set NA values to transparent
  scale_fill_distiller(type = "seq",
                       palette = "Blues",
                       na.value = "transparent") +
  # Add void theme
  theme_void()

推荐阅读