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.
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 ~.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With