I am ploting a map using the ggplot2
and sf
packages and I would like to include a map scale and north arrow to the figure using the ggsn
package. Here is the problem. I want to show a figure with two or more facets
but I would like to add the scale and north arrow to only one of the figure facets.
Any idea on how to do this?
Reproducible example:
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')
The problem gets a bit more complicated if we try to use two variables in 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')
Use the facet.var and facet.lev arguments in scalebar to add to a single facet. Use the north2() function to add a single north arrow. You can adjust the positioning/scale etc. to suit your needs. If you are using facet_grid with two variables you can pass a vector to facet.var and 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With