将地图比例和北向箭头仅包含在一个 ggplot 方面

Include map scale and north arrow to only one ggplot facet

我正在使用 ggplot2sf 包绘制地图,我想使用 ggsn 包在图中添加地图比例尺和指北针。这就是问题所在。我想显示一个包含两个或更多 facets 的图形,但我只想将比例尺和指北针添加到图形的一个方面。

知道怎么做吗?

可重现的例子:

library(UScensus2000tract)
library(ggplot2)
library(spdep)
library(sf)
library(ggsn)

# load data
  data("oregon.tract")

# convert spatial object to sf class
  oregon_sf_A <- st_as_sf(oregon.tract)
  oregon_sf_B <- st_as_sf(oregon.tract)

# organize data for facetting
  oregon_sf_A$cat <- "A"
  oregon_sf_B$cat <- "B"
  oregon_sf <- rbind(oregon_sf_A, oregon_sf_B)

# create a second variable for facetting
  oregon_sf$var2 <- sample(c("C","D"), nrow(oregon_sf), replace=T)

# Map
  ggplot() +
    geom_sf(data=oregon_sf, aes(fill=hispanic.t), color=NA) +
    scale_fill_viridis(option = "inferno", direction=-1) +
    facet_grid(~cat) +
    north(data=oregon_sf, symbol=4, location="bottomleft", scale=.2) +
    scalebar(data=oregon_sf, dist = 200, st.size=3, height=0.02, dd2km = TRUE, location="bottomright" , model = 'WGS84')

如果我们尝试在 facet_grid 中使用两个变量,问题会变得有点复杂:

# Map 2
  ggplot() +
    geom_sf(data=oregon_sf, aes(fill=hispanic.t), color=NA) +
    scale_fill_viridis(option = "inferno", direction=-1) +
    facet_grid(cat~var2) +
    north(data=oregon_sf, symbol=4, location="bottomleft", scale=.2) +
    scalebar(data=oregon_sf, dist = 200, st.size=3, height=0.02, dd2km = TRUE, location="bottomright" , model = 'WGS84')

使用比例尺中的 facet.var 和 facet.lev 参数添加到单个方面。使用 north2() 函数添加单个指北针。您可以调整 positioning/scale 等以满足您的需要。 如果您将 facet_grid 与两个变量一起使用,您可以将向量传递给 facet.var 和 facet.lev.

 ggp <- ggplot(data = oregon_sf) +
  geom_sf(aes(fill=hispanic.t), color=NA) +
  scale_fill_viridis(option = "inferno", direction=-1) +
  facet_grid(cat~var2) +
  scalebar(data=oregon_sf, dist = 200, st.size=3, height=0.02, dd2km = TRUE, location="bottomright" , model = 'WGS84',
           facet.var = c('cat', 'var2'), facet.lev = c('B', "C"))
north2(ggp = ggp, scale = 0.1, x = 0.05, y = 0.3, symbol = 4)

如果您还没有发现它,ggspatial 包在这里有一个解决方案。 https://github.com/paleolimbot/ggspatial/issues/25