【发布时间】:2020-07-05 12:49:20
【问题描述】:
我正在尝试使用 R 生成有关 COVID-19 感染的县级数据的等值线图。我是 R 的相对新手,所以......
我已经用 ggmap 做了一些相当基本的东西来绘制空间数据,但从来没有像这样的东西。通常我只有需要在地图上叠加的兴趣点,所以我可以使用 geom_point 及其纬度/经度。在这种情况下,我需要构建底层地图,然后填充区域,而我在 ggplot 世界中正在努力做到这一点。
我已经遵循了一些我发现的在线示例:
library(ggplot2)
library(broom)
library(geojsonio)
#get a county level map geoJSON file
counties <- geojson_read("https://eric.clst.org/assets/wiki/uploads/Stuff/gz_2010_us_050_00_500k.json", what = "sp")
#filter our alaska and Hawaii
lower48 <- counties[(counties@data$STATE != "02" & counties@data$STATE != "15") ,]
#turn it into a dataframe for ggmap
new_counties <- tidy(lower48)
# Plot it
print(ggplot() +
geom_polygon(data = new_counties, aes( x = long, y = lat, group = group), fill="#69b3a2", color="white") +
theme_void() +
coord_map())
这会产生这个情节:
到目前为止一切顺利。但我的 new_counties 数据框现在看起来像这样:
head(new_counties)
# A tibble: 6 x 7
long lat order hole piece group id
<dbl> <dbl> <int> <lgl> <chr> <chr> <chr>
1 -85.4 33.9 1 FALSE 1 0.1 0
2 -85.4 33.9 2 FALSE 1 0.1 0
3 -85.4 33.9 3 FALSE 1 0.1 0
4 -85.4 33.9 4 FALSE 1 0.1 0
5 -85.4 33.9 5 FALSE 1 0.1 0
6 -85.4 33.8 6 FALSE 1 0.1 0
因此,我丢失了任何可以与我县级感染数据相关联的信息。
我的数据中每个县都有一个 5 位数的 FIPS 代码。前两位数字是州,后三位是县。我的 geoJSON 文件有更详细的 FIPS 代码。我尝试只抓取前 5 个并创建我自己的数据元素,我可以映射回
library(ggplot2)
library(broom)
library(geojsonio)
#get a county level map geoJSON file
counties <- geojson_read("https://eric.clst.org/assets/wiki/uploads/Stuff/gz_2010_us_050_00_500k.json", what = "sp")
#filter our alaska and Hawaii
lower48 <- counties[(counties@data$STATE != "02" & counties@data$STATE != "15") ,]
#add my own FIPS code
lower48@data$myFIPS <- substr(as.character(lower48@data$GEO_ID),1,5)
#turn it into a dataframe for ggmap
new_counties <- tidy(lower48, region = "myFIPS")
# Plot it
print(ggplot() +
geom_polygon(data = new_counties, aes( x = long, y = lat, group = group), fill="#69b3a2", color="white") +
theme_void() +
coord_map())
但这会产生这个情节
我不得不说我对 broom::tidy 不够熟悉,无法确切知道原因。 我还注意到,当我键入此内容时,我需要过滤掉波多黎各!
如果有人能指出我有用的方向....我不拘泥于当前的方法,但我想坚持使用 ggplot2 或 ggmap。我的老板最终希望我覆盖某些功能。最终的目标是效仿here 的示例,并生成一个显示随时间变化的数据的动画地图,但我显然还有很长的路要走。
【问题讨论】:
-
使用
sf::st_read()读取geojson,因此您将其作为sf对象获取。然后使用ggplot2::geom_sf()绘制它。 -sf是sp的继承者,所以我建议任何人离开sp。 -
其中
sf对象是已经是一个data.frame。因此,所有标准过滤和子集操作都“正常工作”。
标签: r ggplot2 geospatial ggmap choropleth