当reference_map=FALSE 时,Choroplethr 邮政编码地图不显示

问题描述 投票:0回答:1

我正在使用 choroplethrzip 包创建密歇根州东南部邮政编码的 choropleth 地图,并使用 geom_polygon 函数添加县线覆盖。我当前的代码如下:

zip_choropleth(df,
zip_zoom = plot_zips,
reference_map=TRUE) +   
geom_polygon(data = countyref,
aes(x = long, y = lat, group = group),
alpha = 0,
color = "black",
linewidth = 0.2) +   
geom_text(data = mi_county_midpoints,
aes(x = long, y = lat, label = county),
size = 2,
color = "black",
fontface = "bold") 

当reference_map设置为TRUE时,代码按照我想要的方式运行,但是如果我将其更改为FALSE或完全删除参数,则会出现以下错误:

Error in `geom_text()`: Problem while computing aesthetics. Error occurred in the 3rd layer. Caused by error: object 'group' not found

如果我删除 geom_text 函数,错误就会消失,但地图看起来像这样:

在此输入图片描述

然后,如果我删除 geom_polygon 函数,只留下 zip_choropleth 部分,它又可以正常工作了。如何在没有背景参考地图的情况下绘制带有县边界和标签的地图?预先感谢!

r ggplot2 choroplethr
1个回答
0
投票
zip_choropleth()

函数,但下面概述的方法有效。在绘制地理点、线或多边形数据时,我强烈建议使用

geom_sf()
。使用其他几何图形可能会导致问题。另外,
ggplot2
可以很好地处理 SF 对象。
由于您没有提供您感兴趣的县和邮政编码列表,因此我使用 

coord_sf()

来放大您感兴趣的区域。如果您首先对数据进行子集化,

ggplot2
将自动缩放到数据范围。此外,由于没有任何有关您的组变量或您希望如何填充邮政编码功能的信息,我已为它们分配了单一颜色。
默认情况下,此代表中的数据都将 NAD83:EPSG4269 作为其 CRS。如果您的数据具有不同的 CRS,您将需要 

st_transform()

其中之一以使您的任务更轻松。

library(zipcodeR)
library(tigris)
library(sf)
library(ggplot2)

# # Find zipcodes for Michigan (skip if you already know)
mi_zip <- search_state("MI")

# Load zip boundary sf using first two digits of zipcodes from mi_zip
mi_zip_sf <- zctas(cb = TRUE, 
                   year = 2020, # Most recent available data
                   starts_with = c("48", "49"),
                   class = "sf")

# Load county data
countyref <- counties("Michigan", cb = TRUE)

# Plot
ggplot() +
  geom_sf(data = mi_zip_sf,
          fill = "lightblue",
          colour = "grey50",
          linewidth = 0.1) +
  geom_sf(data = countyref,
          fill = NA,
          color = "black",
          linewidth = 0.2) +
  geom_sf_text(data = countyref,
               aes(label = NAME),
               size = 3,
               fun.geometry = st_centroid,
               colour = "black") +
  coord_sf(xlim = c(-85, -82.75),
           ylim = c(41.6, 43))

result

© www.soinside.com 2019 - 2024. All rights reserved.