首页 > 解决方案 > ggplot 填充 SpatialPolygonsDataFrame

问题描述

我正在尝试绘制美国县 SPDF 并对出现在另一个向量中的县进行着色(通过 GEOID 匹配)。这是我目前拥有的代码,但没有一个县是阴影的。

我已经从这个链接下载了美国县界的 ShapeFile 。

library(ggplot2)
library(raster)
US_counties <- shapefile("~/us_county_shp_files/tl_2017_us_county.shp")
counties_in_radius <- c("12011", "12015", "12021", "12027", "12043", "12049", "12051", "12055", "12061")
base_plot <- ggplot(data = US_counties) +
  coord_fixed(ratio = 1.3) +
  geom_polygon(data=US_counties, aes(x = long, y = lat, group = group), size = 0.1, colour = "gray", 
               fill= (if(US_counties$GEOID %in% counties_in_radius) "blue" else NA))
base_plot

如果我只做 GEOID,我会得到错误对象 'GEOID' not found,而当我做 US_counties$GEOID 时,我会得到“条件长度 > 1,并且只会使用第一个元素”。

如何正确填写counties_in_radius 中的县?

标签: rggplot2

解决方案


推荐阅读