How to use cut with geom_polygon to create a map grid

I am trying to use faceting to create multiple maps filled with different values.

I created a simplified example below that reproduces what I am trying to do and the result that I do not expect from ggplot. I use the map of the United States and create two hypothetical communities for states. I can create separate communities separately, but when I try to split and generate them at the same time, I get only one card.

require(ggplot2)
require(maps)

map <- map_data("state")
states <- unique(map$region)

# generate some hypothetical communities    
runA <- data.frame(region=states, id="A",
                   community=rbinom(length(states),1,.5))
runB <- data.frame(region=states, id="B",
                   community=rbinom(length(states),1,.5))

membership <- rbind(runA, runB)

# plot an individual map of communities from run A
df <- merge(map, runA, by="region")
ggplot(df) +
  aes(long, lat, group=group) +
  coord_equal() +
  geom_polygon(aes(fill = as.factor(community)))

# likewise for B
df <- merge(map, runB, by="region")
ggplot(df) +
  aes(long, lat, group=group) +
  coord_equal() +
  geom_polygon(aes(fill = as.factor(community)))

# now instead do one plot with two maps from facetting on id
df <- merge(map, membership, by="region")
ggplot(df) +
  aes(long, lat, group=group, facets= id ~.) +
  coord_equal() +
  geom_polygon(aes(fill = as.factor(community)))

Ideally, the last plot should have two cards: one shows the community in "A", and the other shows the community in "B". Instead, only one map is displayed on the chart, and I'm not even sure what is displayed on the fill.

+5
1

. , :

ggplot(df) +
  aes(long, lat, group=group) +
  coord_equal() +
  geom_polygon(aes(fill = as.factor(community))) +
  facet_grid(facets= id ~.)

enter image description here

+8

All Articles