r - 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
加入shapefile
or 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
解决方案
我建议使用该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()
推荐阅读
- puppet - 循环中的木偶在数组中添加了空元素
- java - 如何通过 QueryDSL 访问 @Embeddable 类的属性
- android - 使用 Material ExposedDropdownMenu 时出现样式错误
- wso2 - 规则调解器与 wso2 ei 6.2.0 的集成
- unit-testing - 如何对 AWS Lambda 使用 lambda-local 和 mocha 进行单元测试?
- python - 在单独的文件中定义 Python 脚本参数
- arrays - 无法在 TypeScript 中使用 forEach 更改布尔数组值
- c# - AppDomain 的寿命应该短还是长?
- spring - 在 Spring 服务中使用 application.yaml 中的默认值的最佳方法
- php - 如何在 php 中将 Sun 10-04-19 日期转换为 10-04-2019