Setup from last lesson

library(ggplot2)
library(sf)
library(terra)
library(tidyterra)

harv_soils <- read_sf("data/harv/harv_soils.shp")
harv_dtm <- rast("data/harv/harv_dtmfull.tif")

Plotting with expected units

  • We’ve talked about how different spatial data have different projections which have different units
  • Let’s look at the coordinate reference systems for these two data sets
st_crs(harv_soils)
st_crs(harv_dtm)
  • So both data sets in are UTM Zone 18 North
  • But when we plot them they show up as lat/longs
ggplot() +
  geom_spatraster(data = harv_dtm) +
  geom_sf(data = harv_soils, fill = "transparent", color = "white")
  • Show plot from previous lesson
  • This happens because by default tidyterra changes the units to latitude and longitude values
  • To change the units to another projection, like the projection of the data, we use coord_sf
  • Which takes a CRS and shows the axes in those units
  • So if we want this graph in the units of the projection of our data we can look up the CRS and use that
ggplot() +
  geom_spatraster(data = harv_dtm) +
  geom_sf(data = harv_soils, alpha = 0) +
  coord_sf(datum = st_crs(harv_dtm))
  • We could also use the numeric code for the CRS instead if we want to

Rotating axis labels

  • Our x-axis labels are overlapping, which makes the map difficult to read
  • Can fix this by rotating the axis labels
  • Do this using the theme() function, which lets us control many details of how our plots display
  • We want to set an element of the x-axis text so we set axis.text.x
  • We can set the element we want using the element_text() function
  • And then the name of the element and it’s value
  • In this case the element is angle and we’ll set it to 45 degrees
ggplot() +
  geom_spatraster(data = harv_dtm) +
  geom_sf(data = harv_soils, alpha = 0) +
  coord_sf(datum = st_crs(harv_dtm)) +
  theme(axis.text.x = element_text(angle = 45))
  • This is better, but now our label is starting to overlap our plot
  • We can adjust the position using two functions that control the “justificiation”
  • vjust to control vertical and hjust to control horizontal
  • Possible values are 0 (left justified), 1 (right justified), and 0.5 (center justified)
ggplot() +
  geom_spatraster(data = harv_dtm) +
  geom_sf(data = harv_soils, alpha = 0) +
  coord_sf(datum = st_crs(harv_dtm)) +
  theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))
  • Setting both to 1, for right justified, will align the right edge with the tick

Do Task 6 of Harvard Forest Soils Analysis.