Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use faceting with geom_polygon to generate a grid of maps

I am attempting to use faceting to generate multiple maps filled with different values.

I've created the simplified example below that reproduces both what I am trying to do and the result that I don't expect from ggplot. I use the map of the United States and generate two hypothetical communities for the states. I can plot each community separately, but where I try to facet and generate them at the same time, I only get one map.

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 maps, one showing the community in "A" and the other showing the community in "B". Instead, the plot only shows one map and I am not even sure what is being mapped to the fill.

like image 396
mindless.panda Avatar asked Dec 13 '11 20:12

mindless.panda


1 Answers

You just specified the facets the wrong way. Do it like this instead and it'll work fine:

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

enter image description here

like image 70
John Colby Avatar answered Oct 15 '22 23:10

John Colby