首页 > 解决方案 > 将县名标签添加到州地图

问题描述

我正在尝试从 ARCOS 数据更新地图以包含县名标签,但遇到了麻烦。 https://cran.r-project.org/web/packages/arcos/arcos.pdf

# Uncomment and run the lines below to see if you have the packages required already installed
# packages <- c("tidyverse", "jsonlite", "knitr", "geofacet", "scales", "forcats")
# if (length(setdiff(packages, rownames(installed.packages()))) > 0) {
#   install.packages(setdiff(packages, rownames(installed.packages())), repos = "http://cran.us.r-project.org") # }


# These are all the packages you'll need to run everything below 

library(arcos)
library(knitr)
library(tigris)
library(viridis)
library(dplyr)
library(ggplot2)
library(scales)
library(forcats)

wv <- summarized_county_annual(state="WV", key="WaPo")
## Set the option for shapefiles to load with sf
options(tigris_class = "sf")

## Function to download county shapefiles in West Virginia
wv_shape <- counties(state="WV", cb=T)

## Join the county dosage data we pulled
wv <- left_join(wv, wv_shape, by=c("countyfips"="GEOID"))

wv %>%
  ggplot(aes(geometry=geometry, fill = DOSAGE_UNIT, color = DOSAGE_UNIT)) +
  facet_wrap(~year, ncol=2) +
  geom_sf() +
  coord_sf(crs = 26915) + 
  scale_fill_viridis(direction=-1, label = comma) +
  scale_color_viridis(direction=-1, label = comma) +
  theme_void() +
  theme(panel.grid.major = element_line(colour = 'transparent')) +
  labs(title="Oxycodone and hydrocodone pills in West Virginia", caption="Source: The Washington Post, ARCOS")

我想使用 BUYER_COUNTY 列为各个县的地图添加标签。我想出了如何创建标签的地图,理想情况下只想将这两张地图分层,但我一直收到错误消息。想知道是否有人对地图分层有任何建议,或者是否有更简单的方法可以将县名标签添加到地图中。谢谢!

wv$centroid <-st_centroid(wv$geometry)
wv <- wv %>% extract(centroid, c('lat', 'lon'), '\\((.*), (.*)\\)', convert = TRUE) 
cnames <- aggregate(cbind(lon, lat) ~ BUYER_COUNTY, data=wv, FUN=function(x)mean(range(x)))

labels <- ggplot(cnames, aes(lon, lat))+
  coord_sf(crs = 26915) + 
  theme_void() +
  theme(panel.grid.major = element_line(colour = 'transparent')) +
  geom_text(aes(label = BUYER_COUNTY), size =1)
labels

标签: rggplot2maps

解决方案


推荐阅读