【问题标题】:How to use faceting with geom_polygon to generate a grid of maps如何使用带有 geom_polygon 的 faceting 来生成地图网格
【发布时间】:2012-01-19 16:39:17
【问题描述】:

我正在尝试使用 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”中的社区。相反,该图只显示了一张地图,我什至不确定将什么映射到填充。

【问题讨论】:

    标签: r ggplot2 facets


    【解决方案1】:

    您只是以错误的方式指定了方面。改为这样做,它会正常工作:

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

    【讨论】:

    • 谢谢!为什么可以在aes() 中指定facets 美学?
    • 我认为它是这样工作的,因为刻面系统本身实际上并不是一种美学,而是一个单独的情节组​​件,如比例和坐标。所以它可能是facet_gridfacet_wrap,或者将来可能是其他人,这不能仅通过标准的美学映射来完全指定。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 2016-03-02
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 2011-03-29
    • 2013-05-09
    相关资源
    最近更新 更多