Exploring the package {climateR}

Exploring the various datasets available publicly and freely to use and analyze with R, {terra} and {sf} with the {climateR} package

Maps
Geocomputation
{geodata}
Author

Aditya Dahiya

Published

January 30, 2025

Exploring the {climateR} package

Exploring {climateR} (by Mike Johnson) with {sf} (Pebesma and Bivand 2023) and {terra} (Hijmans 2024)

Code
# Install {cliamteR} package
# remotes::install_github("mikejohnson51/AOI") # suggested!
# remotes::install_github("mikejohnson51/climateR")

# Data Import and Wrangling Tools
library(sf)                   # Handling simple features in R
library(terra)                # Handling rasters in R
library(tidyterra)            # Rasters with ggplot2
library(tidyverse)            # All things tidy

# Final plot tools
library(scales)               # Nice Scales for ggplot2
library(fontawesome)          # Icons display in ggplot2
library(ggtext)               # Markdown text in ggplot2
library(showtext)             # Display fonts in ggplot2
library(colorspace)           # Lighten and Darken colours

# Package to explore
library(climateR)             # Climate Data
library(AOI)                  # Get area of interest

# Making tables in R
library(gt)                   # Beautiful Tables

bts = 12 # Base Text Size
sysfonts::font_add_google("Asap Condensed", "body_font")
showtext::showtext_auto()
theme_set(
  theme_minimal(
    base_size = bts,
    base_family = "body_font"
  ) +
    theme(
      text = element_text(
        colour = "grey20",
        lineheight = 0.3,
        margin = margin(0,0,0,0, "pt")
      )
    )
)

# Some basic caption stuff
# A base Colour
bg_col <- "white"
seecolor::print_color(bg_col)

# Colour for highlighted text
text_hil <- "grey30"
seecolor::print_color(text_hil)

# Colour for the text
text_col <- "grey20"
seecolor::print_color(text_col)


# Caption stuff for the plot
sysfonts::font_add(
  family = "Font Awesome 6 Brands",
  regular = here::here("docs", "Font Awesome 6 Brands-Regular-400.otf")
)
github <- "&#xf09b"
github_username <- "aditya-dahiya"
xtwitter <- "&#xe61b"
xtwitter_username <- "@adityadahiyaias"
social_caption_1 <- glue::glue("<span style='font-family:\"Font Awesome 6 Brands\";'>{github};</span> <span style='color: {text_hil}'>{github_username}  </span>")
social_caption_2 <- glue::glue("<span style='font-family:\"Font Awesome 6 Brands\";'>{xtwitter};</span> <span style='color: {text_hil}'>{xtwitter_username}</span>")
plot_caption <- paste0(
  "**Data**: {geodata} package  ",
  "  |  **Code:** ", 
  social_caption_1, 
  " |  **Graphics:** ", 
  social_caption_2
  )
rm(github, github_username, xtwitter, 
   xtwitter_username, social_caption_1, 
   social_caption_2)

getTerraClim()

The getTerraClim() function in the {climateR} package provides access to TerraClimate data, a high-resolution dataset that offers monthly climate and water balance variables from 1958 onward. These variables include key climate indicators such as precipitation, temperature, soil moisture, wind speed, and evaporation metrics.

Code
terraClim_vars <- tibble::tibble(
  Variable = c("aet", "def", "PDSI", "pet", "ppt", "q", "soil", "srad", 
               "swe", "tmax", "tmin", "vap", "vpd", "ws"),
  Units = c("mm", "mm", "unitless", "mm", "mm", "mm", "mm", "W/m^2", 
            "mm", "degC", "degC", "kPa", "kPa", "m/s"),
  Description = c("Water evaporation amount", 
                  "Potential evaporation minus actual evaporation",
                  "Palmer Drought Severity Index",
                  "Potential evaporation amount",
                  "Precipitation amount",
                  "Runoff amount",
                  "Soil moisture content",
                  "Downwelling shortwave flux in air",
                  "Liquid water content of surface snow",
                  "Maximum air temperature",
                  "Minimum air temperature",
                  "Water vapor partial pressure in air",
                  "Vapor pressure deficit",
                  "Wind speed")
)

terraClim_vars |> 
  gt::gt() |> 
  gtExtras::gt_theme_538()
Table 1: Summary of Climate and Hydrological Variables in getTerraClim()
Variable Units Description
aet mm Water evaporation amount
def mm Potential evaporation minus actual evaporation
PDSI unitless Palmer Drought Severity Index
pet mm Potential evaporation amount
ppt mm Precipitation amount
q mm Runoff amount
soil mm Soil moisture content
srad W/m^2 Downwelling shortwave flux in air
swe mm Liquid water content of surface snow
tmax degC Maximum air temperature
tmin degC Minimum air temperature
vap kPa Water vapor partial pressure in air
vpd kPa Vapor pressure deficit
ws m/s Wind speed
Code
# Get a nice map of India from Survey of India (simplified to
# save on computing time)
india_vec <- read_sf(
  here::here(
    "data", "india_map",
    "India_Country_Boundary.shp"
  )
) |> 
  # Simplify to save computing time
  st_simplify(dTolerance = 3000) |> 
  # Keep on bigger szed polygons and multiploygons
  filter(!st_is_empty(geometry)) |> 
  arrange(desc(Area)) |> 
  slice(1:2) |> 
  select(-Area) |> 
  st_transform("EPSG:4326")

india_vec |> 
  ggplot() +
  geom_sf()

india_vec2 <- aoi_get(country = "India") |> 
  st_cast("POLYGON")

climate_raw <- getTerraClim(
  india_vec2,
  varname = "ppt",
  startDate = "2021-01-01"
)

ggplot() +
  geom_spatraster(
    data = climate_raw$ppt
  )

object.size(climate_raw)

British Isles: Monthly Rainfall Data

This code generates a faceted map of monthly rainfall in the British Isles from January 2018 to December 2022. It begins by defining the area of interest using aoi_get() and then retrieves precipitation data via getTerraClim(). The region is refined using ne_countries() and processed with st_union(), st_as_sf(), and st_crop() to match the raster data’s extent. The precipitation raster is cropped and masked using terra::crop() and terra::mask(). Monthly labels are extracted with str_remove() and format(). The plot is created using ggplot() with geom_spatraster() for the raster data and geom_sf() for country borders. Color scaling is handled by paletteer::scale_fill_paletteer_c(), and faceting is applied with facet_wrap(). The final visualization is styled using theme_map(), and the plot is saved with ggsave().

Code
# Try for a smaller area

uk_vec <- aoi_get(country = c("United Kingdom", "Ireland"))

uk_climate_raw <- getTerraClim(
  uk_vec,
  varname = "ppt",
  startDate = "2018-01-01",
  endDate = "2022-12-31"
)

uk_vec_detail <- rnaturalearth::ne_countries(
  country = c("United Kingdom", "Ireland"),
  scale = "medium",
  returnclass = "sf"
) |> 
  select(geometry) |> 
  st_union() |> 
  st_as_sf() |> 
  st_crop(
    st_bbox(
      c(
        ymin = 49.8,
        ymax = 59.5,
        xmin = -10.3,
        xmax = 2
      ),
      crs = st_crs("EPSG:4326")
    )
  ) |> 
  st_transform(st_crs(uk_climate_raw$ppt))

ggplot(uk_vec_detail) +
  geom_sf()

uk_rast <- uk_climate_raw$ppt |> 
  terra::crop(uk_vec_detail) |> 
  terra::mask(uk_vec_detail)


strip_labels <- uk_rast |> 
  names() |> 
  str_remove("ppt_") |> 
  str_remove("_total") |> 
  as_date() |> 
  format("%B %Y")

names(strip_labels) <- uk_rast |> 
  names()


g <- ggplot() +
  geom_spatraster(
    data = uk_rast[[c(1:60)]]
  ) +
  geom_sf(
    data = uk_vec_detail,
    fill = "transparent",
    linewidth = 0.25,
    colour = "grey20"
  ) +
  paletteer::scale_fill_paletteer_c(
    "grDevices::Blues 3",
    direction = -1,
    na.value = "transparent",
    limits = c(0, 450),
    oob = scales::squish
  ) +
  facet_wrap(
    ~lyr,
    labeller = labeller(lyr = strip_labels),
    nrow = 5,
    ncol = 12
  ) +
  coord_sf(clip = "off") +
  labs(
    title = "British Isles: Rainfall Pattern",
    fill = "Monthly Precipitation (mm)"
  ) +
  ggthemes::theme_map(
    base_size = 40,
    base_family = "body_font"
  ) +
  theme(
    legend.position = "bottom",
    legend.title.position = "top",
    strip.text = element_text(
      hjust = 0,
      margin = margin(4,0,-2,0,"pt"),
      size = 48
    ),
    strip.background = element_blank(),
    plot.title = element_text(
      margin = margin(0,0,10,0, "pt"),
      hjust = 0.5,
      size = 120
    ),
    panel.background = element_rect(
      fill = "transparent",
      colour = "transparent"
    ),
    legend.key.height = unit(10, "pt"),
    legend.key.width = unit(100, "pt"),
    legend.title = element_text(
      margin = margin(0,0,2,0, "mm"),
      size = 80,
      hjust = 0.5
    ),
    legend.text = element_text(
      margin = margin(2,0,0,0, "mm")
    ),
    plot.margin = margin(10,0,10,0, "pt"),
    legend.margin = margin(0,0,0,0, "pt"),
    legend.box.margin = margin(0,0,0,0, "pt"),
    legend.justification = c(0.5, 0)
  )

ggsave(
  filename = here::here(
    "geocomputation", "images",
    "climateR_package_1.png"
  ),
  plot = g,
  height = 4500,
  width = 6000,
  units = "px",
  bg = "white"
)
Figure 1: This faceted visualization illustrates monthly precipitation trends across the British Isles from January 2018 to December 2022. Each panel represents a different month, showcasing variations in rainfall intensity using a gradient color scale. Data is sourced from TerraClimate and spatially refined for accuracy.

References

Hijmans, Robert J. 2024. “Terra: Spatial Data Analysis.” https://CRAN.R-project.org/package=terra.
Pebesma, Edzer, and Roger Bivand. 2023. Spatial Data Science: With Applications in r.” https://doi.org/10.1201/9780429459016.