Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include map scale and north arrow to only one ggplot facet

Tags:

r

ggplot2

sf

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

enter image description here

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

enter image description here

like image 423
rafa.pereira Avatar asked Oct 16 '22 17:10

rafa.pereira


1 Answers

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)

enter image description here

like image 102
sebdalgarno Avatar answered Nov 14 '22 21:11

sebdalgarno