Reputation: 1303
I have map below.from here. how can I add state borders and abbreviated names to this county US map?
vec1 <- c(4013, 6037, 17031, 26163, 36059)
vec2 <- c(48045, 1009)
vec3 <- c(48289,48291)
library(ggplot2)
library(usmap)
library(dplyr)
library(stringr)
dt <- countypop %>%
mutate(fill = case_when(
fips %in% str_pad(vec1, 5, pad = "0") ~ "Blue",
fips %in% str_pad(vec2, 5, pad = "0") ~ "Red",
fips %in% str_pad(vec3, 5, pad = "0") ~ "Green",
TRUE ~ "Other"
))
plot_usmap(regions = "counties", data = dt, values = "fill", color = "grey") +
scale_fill_manual(
values = c(Blue = "blue", Green = "green", Red = "red", Other = "light gray")
)
Upvotes: 0
Views: 855
Reputation: 1492
To plot the state borders you need to obtain the x, y coordinates for each state and draw them on the map. Since this is plotted with plot_usmap()
, you will need to transform lat, long coordinates to the current plot coordinate system.
states <- map_data("state") %>%
usmap_transform()
Then add this to the plot with geom_polygon()
.
geom_polygon(data = states, aes(x = long.1,
y = lat.1,
group = group),
color = "black",
alpha = 0)
To add the state abbreviations you will need to first convert the lat, long data in the state.center
data set to the coordinate system on the chart.
state_centers <- data.frame(long = state.center$x,
lat = state.center$y) %>%
usmap_transform()
Then merge this with data containing the names/abbreviations of each state. Since the data you have is missing Hawaii/Alaska, you need to remove those states.
centroids <- data.frame(name = state.name,
abb = state.abb) %>%
mutate(center_long = state_centers$long.1,
center_lat = state_centers$lat.1) %>%
filter(abb != c("HI", "AK")) %>%
mutate(name = tolower(name)) %>%
rename("region" = name)
Then add the abbreviations to the plot with geom_text()
.
geom_text(data = state_names,
aes(x = center_long,
y = center_lat,
label = abb))
Result:
Things look pretty compact in the North East. You may want to do something with that region of the country to make it more readable.
If you don't want to worry about the coordinate transformations you can remake the plot as follows (not very pretty as-is, but could be styled easily):
counties <- map_data("county")
states <- map_data("state")
state_centers <- data.frame(long = state.center$x,
lat = state.center$y)
centroids <- data.frame(name = state.name,
abb = state.abb) %>%
mutate(center_long = state_centers$long,
center_lat = state_centers$lat) %>%
filter(abb != c("HI", "AK")) %>%
mutate(name = tolower(name)) %>%
rename("region" = name)
ggplot() +
geom_polygon(data = counties,
aes(x = long,
y = lat,
group = group),
color = "grey",
fill = "white") +
geom_polygon(data = states,
aes(x = long,
y = lat,
group = group),
color = "black",
alpha = 0) +
geom_text(data = centroids,
aes(x = center_long,
y = center_lat,
label = abb)) +
coord_fixed(1.3)
Upvotes: 1