【问题标题】:ggplot: Faceted map with multiple layersggplot:具有多层的多面地图
【发布时间】:2017-12-19 16:12:44
【问题描述】:

我正在尝试使用 ggplot 创建具有两层的多面地图。一个来自包含纬度/经度坐标的数据框,由 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))

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

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

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

但是,如果我想将街道作为底图添加到每个方面,我就遇到了困难。这个:

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 个街道),但我仍然不明白我做错了什么。任何指针表示赞赏!

【问题讨论】:

  • 看我的回答。我很确定你的问题在~ poijoin$level1

标签: r ggplot2


【解决方案1】:

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

library(hrbrthemes)
library(tidyverse)

获取地图:

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

ggplot2 将跨构面应用底图,然后将构面应用到具有level 类别的任何其他图层。

【讨论】:

  • 非常感谢!它确实是完全限定的列名。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-07
  • 2016-08-29
  • 2017-11-08
  • 1970-01-01
相关资源
最近更新 更多