首页 文章

ggplot:具有多个图层的分面 Map

提问于
浏览
1

我正在尝试使用ggplot创建一个带有两个图层的分面图 . 一个来自包含lat / lon坐标的数据框,从CSV创建:

head(poijoin)

NAME                           LAT       LNG      level1
ATM  Bank Of America ATM @ WHC 38.92825 -77.01517 ShopService                        
ATM  Bank Of America ATM       38.90577 -77.03654 ShopService
ATM  Bank of America           38.91512 -77.02184 ShopService    
ATM  USAA ATM @CVS             38.91343 -77.03590 ShopService
ATM  Bank of America ATM       38.95511 -77.02473 ShopService

另一个来自街道网络形状文件,使用 fortify 变成数据帧:

head(streets_df)

        LNG      LAT order piece id group
1 -77.02704 38.90253     1     1  0   0.1
2 -77.02704 38.90303     2     1  0   0.1
3 -77.02704 38.90303     3     1  0   0.1
4 -77.02704 38.90304     4     1  0   0.1
5 -77.02704 38.90326     5     1  0   0.1

单独绘制它们的工作正常,覆盖它们也是如此:

ggplot() +
  geom_point(data = poijoin, aes(x = poijoin$LNG, y = poijoin$LAT)) +
  geom_path(data = streets_df, aes(x = LNG, y = LAT, group = group))

Overlay

(不是很漂亮,我知道,但我想在这里坚持代码的基本部分 . )

我也可以毫无问题地面对点层:

ggplot() +
  geom_point(data = poijoin, aes(x = poijoin$LNG, y = poijoin$LAT)) +
  facet_wrap(~ poijoin$level1, nrow=3)

facet

但是,如果我想将街道添加为每个方面的基本 Map ,我就会陷入困境 . 这个:

ggplot() +
  geom_point(data = poijoin, aes(x = poijoin$LNG, y = poijoin$LAT, color = poijoin$level1)) +
  geom_path(data = streets_df, aes(x = LNG, y = LAT, group = group)) +
  facet_wrap(~ poijoin$level1, nrow=3)

给我:

Error in `$<-.data.frame`(`*tmp*`, "PANEL", value = c(8L, 8L, 8L, 8L,  : 
  replacement has 20983 rows, data has 200205

我确定错误出现是因为两个数据帧具有不同数量的元素(20983点和200205街道),但我仍然不知道我做错了什么 . 任何指针赞赏!

1 回答

  • 2

    让我们做一个可重复的例子:

    library(hrbrthemes)
    library(tidyverse)
    

    获取 Map :

    st_map <- map_data("state")
    

    与3组分数:

    set.seed(2017-12-19)
    data_frame(
      lat = sample(st_map$lat, 30),
      lng = sample(st_map$long, 30),
      level = rep(c("A", "B", "C"), 10)
    ) -> points_df
    
    ggplot() +
      geom_path(data=st_map, aes(long, lat, group=group), size=0.25) + # basemap
      geom_point(data=points_df, aes(lng, lat, color=level)) +         # add our points layer
      coord_map("polyconic") +                                         # for funsies
      facet_wrap(~level) +                                             # NEVER use a fully qualified column unless you know what you're doing
      labs(x=NULL, y=NULL) +
      theme_ipsum(grid="") +
      theme(axis.text=element_blank()) +
      theme(legend.position="none")
    

    enter image description here

    ggplot2将在构面之间应用底图,然后将构面应用于具有 level 类别的任何其他图层 .

相关问题