r - 仅将 map 比例尺和指北针包含在一个 ggplot 方面

标签 r ggplot2 sf

我正在使用 ggplot2 绘制 map 和 sf包,我想使用 ggsn 在图中包含 map 比例尺和指北针包裹。这是问题所在。我想显示一个有两个或更多的图 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')

enter image description here

如果我们尝试在 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')

enter image description here

最佳答案

使用比例尺中的 facet.var 和 facet.lev 参数添加到单个方面。使用north2() 函数添加一个指北针。您可以调整定位/比例等以满足您的需要。
如果您使用带有两个变量的 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)

enter image description here

关于r - 仅将 map 比例尺和指北针包含在一个 ggplot 方面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50711547/

相关文章:

R SF : Find polygons outside of multiple overlapping polygons

r - 无法让 alpha 与 ggplot2::geom_sf 在 sf linestring 对象上一起使用

r - R 中数字和字符列的 dcast - 默认返回长度

r - Geom_line 和 fill 在 ggplot 中不能一起使用

r - 在 R 中为每个客户绘制不同颜色的折线图

r - st_join 几何和分组列在一起

r - 寓言中的预测功能是否提供一步预测?

r - 是否可以使用 R 中的 data.table 的 SET 来分配多个列/值?

r - 子集数据表而不是 for 循环 R 的更快方法

r - 添加笔画点的图例ggplot2