我正在使用ggplot2和sf包绘制地图,我想使用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')
Run Code Online (Sandbox Code Playgroud)
如果我们尝试使用两个变量,问题会变得复杂一些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')
Run Code Online (Sandbox Code Playgroud)
使用scalebar中的facet.var和facet.lev参数添加到单个facet。使用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)
Run Code Online (Sandbox Code Playgroud)