如何使用geom_polygon构面生成地图网格

时间:2011-12-13 20:05:52

标签: r ggplot2 facets

我正在尝试使用faceting生成多个填充了不同值的地图。

我创建了下面的简化示例,它再现了我要做的事情以及我不希望从ggplot得到的结果。我使用美国地图并为州创建两个假设社区。我可以单独绘制每个社区的情节,但是在我尝试同时生成它们的地方,我只得到一张地图。

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)))

理想情况下,最后一个地块应该有两张地图,一张显示“A”中的社区,另一张显示“B”中的社区。相反,该图只显示一个地图,我甚至不确定是什么映射到填充。

1 个答案:

答案 0 :(得分:8)

您刚刚以错误的方式指定了facet。这样做,它会工作正常:

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

enter image description here