Karl Wolfschtagg
Karl Wolfschtagg

Reputation: 567

Grouping subregions for custom mapping with ggplot

I've picked up a project that requires me to plot custom regions within the United States (including OCONUS regions and territories). Because the whole data set is huge, I've put a "small" subset here (the file name is AZExample.csv). The name of my full data frame is allgeo, and I've gotten this far:

colnames(allgeo) <- c("County", "long", "lat", "group", "order", "State", "sregion")

g <- ggplot(NULL)
# Plot state outlines
g <- g + geom_polygon(data = us_states, aes(x = long, y = lat, group = group), 
      color = "black", fill = "white", size = 0.1)
g <- g + coord_map(projection = "albers", lat0 = 39, lat1 = 45)
# Add county outlines
g <- g + geom_polygon(data = allgeo, aes(x = long, y = lat, group = group, 
      fill = sregion))
g <- g + guides(fill = "none")
g <- g + theme(axis.line = element_blank(),
      axis.text = element_blank(),
      axis.ticks = element_blank(),
      axis.title = element_blank(),
      panel.background = element_blank(),
      panel.border = element_blank(),
      panel.grid = element_blank())
g

I am trying to produce an image of the US (including territories at some point), coloring them by what I've called sregion here. The plot that I get is not what I want since the sregions are not solid colors: scribble states

Eventually I would like to add other collections of counties, but before I can do that, I need to figure this out. I'm sure this is a fundamental something when creating maps like this, but I've not done this before. Any suggestions?

Upvotes: 1

Views: 362

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173783

Your csv contains a plotting order, and the polygons are only drawn correctly if you order the data according to this order. For the subset you provided, we can do:

library(ggplot2)

url <- paste0("https://raw.githubusercontent.com/",
              "Doc-Midnight/Test_Dir/main/AZExample.csv")

allgeo <- read.csv(url)
ggplot() + 
  geom_polygon(data = allgeo[order(allgeo$order),], 
               aes(x = long, y = lat, group = group, fill = sregion), 
               color = "black") + 
  coord_map(xlim = c(-115, -108), ylim = c(30, 37.5)) +
  theme_void()

Created on 2022-04-14 by the reprex package (v2.0.1)

Upvotes: 3

Related Questions