R/texture.R

Defines functions texture_triangle add_texture .usda_class classify_texture

Documented in add_texture classify_texture texture_triangle

#' @title USDA soil texture classification
#' @name texture
#' @description Classify soil samples into USDA texture classes from sand,
#'   silt, and clay percentages, and create texture triangle plots.
NULL

#' Classify soil texture according to the USDA system
#'
#' Returns the USDA texture class name for each row based on the sand, silt,
#' and clay fractions.  Inputs are expected in per-cent (0–100) and must sum
#' to approximately 100.
#'
#' @param sand Numeric vector: sand content (%).
#' @param silt Numeric vector: silt content (%).
#' @param clay Numeric vector: clay content (%).
#' @param tol  Tolerance for the 100 % sum check (default `1.0`).
#'
#' @return Character vector of USDA texture class names.  Returns `NA`
#'   for rows where values are missing or do not sum to approximately 100.
#'
#' @examples
#' classify_texture(sand = c(70, 20, 10, 40),
#'                 silt = c(15, 50, 30, 40),
#'                 clay = c(15, 30, 60, 20))
#'
#' @export
classify_texture <- function(sand, silt, clay, tol = 1.0) {
  n    <- max(length(sand), length(silt), length(clay))
  sand <- rep_len(as.numeric(sand), n)
  silt <- rep_len(as.numeric(silt), n)
  clay <- rep_len(as.numeric(clay), n)

  result <- character(n)
  for (i in seq_len(n)) {
    sa <- sand[i]; si <- silt[i]; cl <- clay[i]
    if (any(is.na(c(sa, si, cl)))) { result[i] <- NA_character_; next }
    if (abs(sa + si + cl - 100) > tol) { result[i] <- NA_character_; next }
    result[i] <- .usda_class(sa, si, cl)
  }
  result
}

#' @keywords internal
.usda_class <- function(sa, si, cl) {
  # Reference: USDA Soil Survey Manual (2017)
  if (cl >= 60)                                   return("Clay")
  if (cl >= 40 && si >= 40)                        return("Silty Clay")
  if (cl >= 35 && sa >= 45)                        return("Sandy Clay")
  if (cl >= 40)                                    return("Clay")
  if (cl >= 27 && cl < 40 && si >= 20 && si < 40) return("Clay Loam")
  if (cl >= 27 && cl < 40 && si >= 40)             return("Silty Clay Loam")
  if (cl >= 20 && cl < 35 && sa >= 45 && si < 15) return("Sandy Clay Loam")
  if (cl >= 7  && cl < 27 && si >= 28 && si < 50 && sa <= 52) return("Loam")
  if ((cl < 12  && si >= 80) || (cl >= 12 && si >= 50))       return("Silt Loam")
  if (cl < 12  && si >= 50 && si < 80)            return("Silt Loam")
  if (si >= 80 && cl < 12)                         return("Silt")
  if (sa >= 85 && cl < 10 && si < 15)              return("Sand")
  if (sa >= 70 && sa < 85 && cl < 15 && si < 30)  return("Loamy Sand")
  if (sa >= 70 && cl < 20 && si < 30)              return("Sandy Loam")
  if (sa >= 52 && si < 28 && cl >= 7 && cl < 20)  return("Sandy Loam")
  if (sa < 52  && cl < 27 && si < 28)              return("Loam")
  "Loam"    # fallback
}

#' Add texture classification column to a data frame
#'
#' @param df       A data frame.
#' @param sand_col Column name for sand (default `"sand_total"`).
#' @param silt_col Column name for silt (default `"silt"`).
#' @param clay_col Column name for clay (default `"clay"`).
#' @param out_col  Name of the output column (default `"Texture"`).
#'
#' @return The input data frame with an additional `out_col` column.
#'
#' @examples
#' df <- data.frame(sand_total = c(70, 20), silt = c(15, 50), clay = c(15, 30))
#' add_texture(df)
#'
#' @export
add_texture <- function(df,
                        sand_col = "sand_total",
                        silt_col = "silt",
                        clay_col = "clay",
                        out_col  = "Texture") {
  stopifnot(is.data.frame(df))
  for (col in c(sand_col, silt_col, clay_col)) {
    if (!(col %in% names(df)))
      rlang::abort(paste("Column not found:", col))
  }
  df[[out_col]] <- classify_texture(
    sand = df[[sand_col]],
    silt = df[[silt_col]],
    clay = df[[clay_col]]
  )
  df
}

#' Plot a USDA soil texture triangle (ternary diagram)
#'
#' Creates a USDA texture triangle with **filled texture-class regions**,
#' USDA class boundary lines, class name labels, and optional data points —
#' all using a pure `ggplot2` ternary-to-Cartesian projection (Clay at top,
#' Sand at bottom-left, Silt at bottom-right).  No external ternary-plot
#' package is required.
#'
#' The background is always coloured by USDA texture class (12-class
#' USDA-inspired palette).  Data points are overlaid and can be mapped to a
#' separate variable via `color_col`.
#'
#' @param df         A data frame.
#' @param sand_col   Column name for sand (default `"sand_total"`).
#' @param silt_col   Column name for silt (default `"silt"`).  Used only
#'   for data point projection; silt for the background grid is derived as
#'   `100 - clay - sand`.
#' @param clay_col   Column name for clay (default `"clay"`).
#' @param color_col  Column name for colouring data points (default `NULL` —
#'   points are drawn in black).  If the column contains USDA texture class
#'   names the same USDA palette is applied automatically.
#' @param title      Plot title.
#' @param point_size Point size (default `3.0`).
#' @param alpha      Point transparency (default `0.85`).
#'
#' @return A `ggplot` object.
#'
#' @examples
#' df <- data.frame(sand_total = c(70, 20, 10, 40),
#'                  silt       = c(15, 50, 30, 40),
#'                  clay       = c(15, 30, 60, 20),
#'                  Texture    = c("Sandy Loam", "Silt Loam", "Clay", "Loam"))
#' texture_triangle(df, color_col = "Texture")
#'
#' @importFrom ggplot2 ggplot aes geom_tile geom_path geom_point geom_text
#'   annotate scale_fill_manual scale_colour_manual guide_legend coord_equal
#'   labs theme_void theme element_text margin
#' @importFrom tibble tibble tribble
#' @importFrom purrr map_dfr
#' @export
texture_triangle <- function(df,
                             sand_col   = "sand_total",
                             silt_col   = "silt",
                             clay_col   = "clay",
                             color_col  = NULL,
                             title      = "Soil Texture Triangle",
                             point_size = 3.0,
                             alpha      = 0.85) {

  # ── Ternary → Cartesian (Clay = top, Sand = BL, Silt = BR) ─────────────────
  .t2c <- function(clay, sand, silt) {
    list(x = silt / 100 + clay / 200,
         y = clay * sqrt(3) / 200)
  }

  # ── Texture class fill palette (background) ──────────────────────────────────
  tex_fill <- c(
    "Clay"            = "#7ECDC8",
    "Silty Clay"      = "#CC99CC",
    "Sandy Clay"      = "#FFEE66",
    "Silty Clay Loam" = "#AADDAA",
    "Clay Loam"       = "#66BB66",
    "Sandy Clay Loam" = "#AAAADD",
    "Silt Loam"       = "#C8C8C8",
    "Loam"            = "#FFBBBB",
    "Sandy Loam"      = "#FF9988",
    "Loamy Sand"      = "#7799DD",
    "Sand"            = "#FFBB55",
    "Silt"            = "#EEFFBB"
  )

  # ── Texture class colour palette (data points, when color_col = Texture) ─────
  tex_col <- c(
    "Clay"            = "#007B77",
    "Silty Clay"      = "#6A0DAD",
    "Sandy Clay"      = "#B8860B",
    "Silty Clay Loam" = "#2E8B57",
    "Clay Loam"       = "#228B22",
    "Sandy Clay Loam" = "#4040AA",
    "Silt Loam"       = "#555555",
    "Loam"            = "#BB3333",
    "Sandy Loam"      = "#CC2200",
    "Loamy Sand"      = "#1144AA",
    "Sand"            = "#CC7700",
    "Silt"            = "#557700"
  )

  # ── Background raster: classify a regular Cartesian grid ────────────────────
  # Back-project (x,y) → (clay,silt,sand) using:
  #   y = clay*sqrt(3)/200  →  clay = 200*y/sqrt(3)
  #   x = silt/100 + clay/200  →  silt = 100*x - clay/2 = 100*x - 100*y/sqrt(3)
  nx <- 400L; ny <- 350L
  bg <- expand.grid(
    x = seq(0, 1,          length.out = nx),
    y = seq(0, sqrt(3)/2,  length.out = ny)
  )
  bg$clay <- 200 * bg$y / sqrt(3)
  bg$silt <- 100 * bg$x - 100 * bg$y / sqrt(3)
  bg$sand <- 100 - bg$clay - bg$silt

  # Keep only valid interior points
  bg <- bg[bg$clay >= -0.3 & bg$silt >= -0.3 & bg$sand >= -0.3, ]
  bg$clay <- pmax(0, bg$clay)
  bg$silt <- pmax(0, bg$silt)
  bg$sand <- pmax(0, bg$sand)

  bg$Texture <- classify_texture(sand = bg$sand, silt = bg$silt, clay = bg$clay)
  bg <- bg[!is.na(bg$Texture), ]
  bg$Texture <- factor(bg$Texture, levels = names(tex_fill))

  tile_w <- 1.015 / (nx - 1L)
  tile_h <- (1.015 * sqrt(3) / 2) / (ny - 1L)

  # ── USDA class boundary segments ─────────────────────────────────────────────
  segs <- list(
    list(.t2c(40,60,0),  .t2c(40,0,60)),
    list(.t2c(35,65,0),  .t2c(35,45,20)),
    list(.t2c(27,73,0),  .t2c(27,20,53)),
    list(.t2c(27,20,53), .t2c(27,0,73)),
    list(.t2c(20,80,0),  .t2c(20,52,28)),
    list(.t2c(0,50,50),  .t2c(27,23,50)),
    list(.t2c(0,20,80),  .t2c(12,8,80)),
    list(.t2c(12,8,80),  .t2c(12,80,8)),
    list(.t2c(0,70,30),  .t2c(20,70,10)),
    list(.t2c(0,85,15),  .t2c(10,85,5)),
    list(.t2c(7,78,15),  .t2c(7,63,30)),
    list(.t2c(20,52,28), .t2c(7,63,30))
  )
  bnd_df <- purrr::map_dfr(seq_along(segs), function(i) {
    s <- segs[[i]]
    tibble::tibble(x   = c(s[[1L]]$x, s[[2L]]$x),
                   y   = c(s[[1L]]$y, s[[2L]]$y),
                   grp = as.character(i))
  })

  # ── Triangle outline ─────────────────────────────────────────────────────────
  tri_df <- tibble::tibble(
    x = c(0, 1, 0.5, 0),
    y = c(0, 0, sqrt(3) / 2, 0)
  )

  # ── Dashed iso-composition gridlines (every 20 %) ────────────────────────────
  .gridline <- function(axis, val) {
    if (axis == "clay") { p1 <- .t2c(val,100-val,0); p2 <- .t2c(val,0,100-val) }
    if (axis == "sand") { p1 <- .t2c(0,val,100-val); p2 <- .t2c(100-val,val,0) }
    if (axis == "silt") { p1 <- .t2c(0,100-val,val); p2 <- .t2c(100-val,0,val) }
    tibble::tibble(x = c(p1$x, p2$x), y = c(p1$y, p2$y),
                   grp = paste0(axis, val))
  }
  grid_df <- purrr::map_dfr(
    c("clay", "sand", "silt"),
    function(ax) purrr::map_dfr(c(20, 40, 60, 80), ~ .gridline(ax, .x))
  )

  # ── Class label positions ────────────────────────────────────────────────────
  lbl_raw <- tibble::tribble(
    ~clay, ~sand, ~silt,  ~label,
      60,    20,    20,   "Clay",
      47,     6,    47,   "Silty\nClay",
      42,    52,     6,   "Sandy\nClay",
      34,    10,    56,   "Silty Clay\nLoam",
      33,    32,    35,   "Clay\nLoam",
      27,    58,    15,   "Sandy Clay\nLoam",
      18,    41,    41,   "Loam",
      13,    65,    22,   "Sandy\nLoam",
      14,    12,    74,   "Silt\nLoam",
       6,     8,    86,   "Silt",
       6,    82,    12,   "Loamy\nSand",
       3,    92,     5,   "Sand"
  )
  lbl_cart <- purrr::map_dfr(seq_len(nrow(lbl_raw)), function(i) {
    pos <- .t2c(lbl_raw$clay[i], lbl_raw$sand[i], lbl_raw$silt[i])
    tibble::tibble(x = pos$x, y = pos$y, label = lbl_raw$label[i])
  })

  # ── Project data points to Cartesian ────────────────────────────────────────
  si_vals <- 100 - df[[clay_col]] - df[[sand_col]]
  proj    <- .t2c(df[[clay_col]], df[[sand_col]], si_vals)
  pts     <- df
  pts$.tx <- proj$x
  pts$.ty <- proj$y

  # ── Build plot ───────────────────────────────────────────────────────────────
  p <- ggplot2::ggplot() +
    # Filled texture class regions
    ggplot2::geom_tile(
      data    = bg,
      mapping = ggplot2::aes(x = x, y = y, fill = Texture),
      width   = tile_w, height = tile_h
    ) +
    ggplot2::scale_fill_manual(
      values = tex_fill, name = "Texture Class",
      drop   = TRUE, guide = ggplot2::guide_legend(ncol = 1)
    ) +
    # Dashed grid
    ggplot2::geom_path(
      data    = grid_df,
      mapping = ggplot2::aes(x = x, y = y, group = grp),
      colour  = "grey50", linewidth = 0.25, linetype = "dashed"
    ) +
    # USDA class boundaries
    ggplot2::geom_path(
      data    = bnd_df,
      mapping = ggplot2::aes(x = x, y = y, group = grp),
      colour  = "grey20", linewidth = 0.55
    ) +
    # Triangle outline
    ggplot2::geom_path(
      data    = tri_df,
      mapping = ggplot2::aes(x = x, y = y),
      colour  = "black", linewidth = 1.0
    ) +
    # Class name labels
    ggplot2::geom_text(
      data    = lbl_cart,
      mapping = ggplot2::aes(x = x, y = y, label = label),
      size = 2.5, colour = "grey10", lineheight = 0.85, fontface = "bold"
    )

  # ── Data points ──────────────────────────────────────────────────────────────
  if (!is.null(color_col)) {
    vals <- unique(as.character(pts[[color_col]]))
    p <- p + ggplot2::geom_point(
      data    = pts,
      mapping = ggplot2::aes(x = .tx, y = .ty, colour = .data[[color_col]]),
      size = point_size, alpha = alpha, shape = 19, stroke = 0.3
    )
    if (all(vals[!is.na(vals)] %in% names(tex_col))) {
      p <- p + ggplot2::scale_colour_manual(
        values = tex_col, name = color_col,
        drop   = TRUE, guide = ggplot2::guide_legend(ncol = 1)
      )
    }
  } else {
    p <- p + ggplot2::geom_point(
      data    = pts,
      mapping = ggplot2::aes(x = .tx, y = .ty),
      colour  = "black", size = point_size, alpha = alpha, shape = 19
    )
  }

  # ── Corner labels, tick annotations and theme ────────────────────────────────
  tick_vals <- c(20, 40, 60, 80)
  tick_len  <- 0.018

  # Bottom edge: Silt increases left→right; Sand increases right→left
  # Silt tick labels (bottom edge, x = silt/100 at clay=0)
  silt_ticks <- purrr::map_dfr(tick_vals, function(v) {
    px <- v / 100
    tibble::tibble(
      x = px, xend = px,
      y = -tick_len, yend = 0,
      lx = px, ly = -tick_len * 2.5, lab = as.character(v)
    )
  })
  # Sand tick labels (bottom edge, x = silt/100 = (100-sand)/100 at clay=0)
  sand_ticks <- purrr::map_dfr(tick_vals, function(v) {
    px <- (100 - v) / 100        # x position on bottom edge for sand = v%
    tibble::tibble(
      x = px, xend = px,
      y = -tick_len, yend = 0,
      lx = px, ly = -tick_len * 2.5, lab = as.character(v)
    )
  })
  # Clay tick labels (left edge, clay = v%)
  clay_ticks <- purrr::map_dfr(tick_vals, function(v) {
    pos  <- .t2c(v, 100 - v, 0)
    off  <- tick_len * c(-sin(pi/3), -cos(pi/3))   # perpendicular outward
    tibble::tibble(
      x = pos$x, xend = pos$x + off[1],
      y = pos$y, yend = pos$y + off[2],
      lx = pos$x + off[1] * 2.5, ly = pos$y + off[2] * 2.5,
      lab = as.character(v)
    )
  })

  for (tdf in list(silt_ticks, sand_ticks, clay_ticks)) {
    p <- p +
      ggplot2::geom_segment(
        data = tdf,
        ggplot2::aes(x = x, y = y, xend = xend, yend = yend),
        colour = "black", linewidth = 0.4
      ) +
      ggplot2::geom_text(
        data = tdf,
        ggplot2::aes(x = lx, y = ly, label = lab),
        size = 2.5, colour = "grey20"
      )
  }

  p +
    ggplot2::annotate("text", x = 0,    y = -0.09,
                      label = "Sand", size = 5, fontface = "bold", colour = "#1a1aaa") +
    ggplot2::annotate("text", x = 1,    y = -0.09,
                      label = "Silt", size = 5, fontface = "bold", colour = "#006600") +
    ggplot2::annotate("text", x = 0.5,  y = sqrt(3) / 2 + 0.07,
                      label = "Clay", size = 5, fontface = "bold", colour = "#aa0000") +
    ggplot2::coord_equal(clip = "off") +
    ggplot2::labs(title = title) +
    ggplot2::theme_void(base_size = 12) +
    ggplot2::theme(
      plot.title      = ggplot2::element_text(face = "bold", size = 12, hjust = 0.5,
                                               margin = ggplot2::margin(b = 8)),
      legend.position = "right",
      plot.margin     = ggplot2::margin(20, 5, 35, 5)
    )
}

Try the soilFlux package in your browser

Any scripts or data that you put into this service are public.

soilFlux documentation built on Dec. 4, 2026, 5:10 p.m.