## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  message = FALSE,
  warning = FALSE,
  fig.align = "center"
)

library(dplyr)
library(ggplot2)
library(scales)
library(kableExtra)

# A sober palette for a sober subject
ember <- "#B23A2E"   # loss, highlight
charcoal <- "#2B2B2B"  # text, structure
ash <- "#9A9A9A"   # secondary
sand <- "#D9C7B8"   # neutral fill
slate <- "#4C6472"   # cool accent

theme_extinct <- function(base_size = 14) {
  theme_minimal(base_size = base_size) +
    theme(
      plot.title = element_text(face = "bold", colour = charcoal, size = rel(1.15)),
      plot.subtitle = element_text(colour = ash, size = rel(0.95), margin = margin(b = 10)),
      plot.caption  = element_text(colour = ash, size = rel(0.75), hjust = 0),
      axis.title = element_text(colour = charcoal),
      axis.text = element_text(colour = charcoal),
      panel.grid.minor = element_blank(),
      panel.grid.major = element_line(colour = "grey90"),
      legend.position = "top",
      plot.margin = margin(12, 16, 12, 12)
    )
}
theme_set(theme_extinct())

# Data
ex <- readRDS("data/extinct_data_sis.rds")

## ----query, eval = FALSE------------------------------------------------------
# library(redlist)
# library(dplyr)
# 
# # 1. Retrieve every assessment currently classified as Extinct
# extinct <- rl_red_list_categories(code = "EX", page = NA)
# 
# # Save
# saveRDS(extinct, "data/extinct_data.rds")

## ----ids, eval = FALSE--------------------------------------------------------
# # 2. The species I want: the latest listing of each taxon
# ids <- unique(extinct$sis_taxon_id[extinct$latest == TRUE])

## ----enrich, eval = FALSE-----------------------------------------------------
# # 3. Enrich each species with its taxonomy
# sis_data <- tibble()
# for (i in seq_along(ids)) {
# 
#   # System sleep set to 1s to avoid the API call overload
#   Sys.sleep(1)
# 
#   # Show simple progress status
#   cat(paste0("\f", i, "/", length(ids), " (", round(i * 100 / length(ids), 2), "%)", "\r"))
# 
#   # Red List taxa by SIS ID
#   one <- rl_sis(ids[i]) %>%
#     slice_max(as.numeric(year_published), n = 1, with_ties = FALSE)
# 
#   # Bind every single request to one data set in sis_data
#   sis_data <- bind_rows(sis_data, one)
# }
# 
# # Save
# saveRDS(sis_data, "data/extinct_data_sis.rds")

## ----load-data-real, include = FALSE------------------------------------------
extinct_raw <- readRDS("data/extinct_data.rds")
ex <- readRDS("data/extinct_data_sis.rds")

## ----tidy---------------------------------------------------------------------
ex <- ex %>%
  mutate(
    year_published = as.integer(year_published),
    genus  = taxon_genus_name,
    # Fold taxonomic class into reader-friendly major groups
    group = case_when(
      taxon_class_name == "MAMMALIA" ~ "Mammals",
      taxon_class_name == "AVES" ~ "Birds",
      taxon_class_name == "AMPHIBIA" ~ "Amphibians",
      taxon_class_name == "REPTILIA" ~ "Reptiles",
      taxon_class_name %in% c("ACTINOPTERYGII", "CHONDRICHTHYES") ~ "Fishes",
      taxon_class_name == "GASTROPODA" ~ "Snails & slugs",
      taxon_class_name == "BIVALVIA" ~ "Mussels & clams",
      taxon_class_name == "INSECTA" ~ "Insects",
      taxon_class_name %in% c("ARACHNIDA", "MALACOSTRACA", "DIPLOPODA",
                              "MAXILLOPODA", "HEXANAUPLIA", "OSTRACODA") ~ "Other arthropods",
      taxon_class_name %in% c("MAGNOLIOPSIDA", "LILIOPSIDA") ~ "Flowering plants",
      taxon_class_name %in% c("BRYOPSIDA", "POLYPODIOPSIDA") ~ "Ferns & mosses",
      taxon_kingdom_name == "PLANTAE" ~ "Other plants",
      TRUE ~ "Other invertebrates"
    ),
    kingdom = tools::toTitleCase(tolower(taxon_kingdom_name)),
    branch = case_when(
      group %in% c("Mammals", "Birds", "Amphibians", "Reptiles", "Fishes") ~ "Vertebrates",
      taxon_kingdom_name == "PLANTAE" ~ "Plants",
      TRUE ~ "Invertebrates"
    )
  )

glimpse(ex[, c("taxon_scientific_name", "kingdom", "taxon_class_name",
               "group", "year_published")])

## ----headline-numbers---------------------------------------------------------
n_records <- nrow(extinct_raw)
n_species <- nrow(ex)
n_genera <- n_distinct(ex$genus)
n_family <- n_distinct(ex$taxon_family_name)
n_animals <- sum(ex$kingdom == "Animalia")
n_plants <- sum(ex$kingdom == "Plantae")
n_mollusc <- sum(ex$group %in% c("Snails & slugs", "Mussels & clams"))
yr_min <- min(ex$year_published)
yr_max <- max(ex$year_published)
since_2020 <- sum(ex$year_published >= 2020)

## ----overview-table-----------------------------------------------------------
dplyr::tibble(
  Measure = c(
    "Assessment records returned",
    "Distinct Extinct species (latest listing)",
    "Genera represented",
    "Families represented",
    "Animals / Plants",
    "Species listed since 2020",
    "Publication span of current listings"
  ),
  Value = c(
    comma(n_records),
    comma(n_species),
    comma(n_genera),
    comma(n_family),
    paste0(comma(n_animals), " / ", comma(n_plants)),
    comma(since_2020),
    paste0(yr_min, " to ", yr_max)
  )
) %>%
  kable(align = c("l", "r"), caption = "The Extinct record in numbers") %>%
  kable_styling(full_width = FALSE, bootstrap_options = c("striped", "hover"))

## ----groups, fig.width = 8, fig.height = 5.5, fig.alt = "Number of Extinct species by major taxonomic group"----
group_tbl <- ex %>%
  count(group, branch, name = "species") %>%
  mutate(group = reorder(group, species))

ggplot(group_tbl, aes(species, group, colour = branch)) +
  geom_segment(aes(x = 0, xend = species, y = group, yend = group),
               colour = ash, linewidth = 0.6) +
  geom_point(size = 4) +
  geom_text(aes(label = species), colour = charcoal, size = 2.9, hjust = -0.6) +
  scale_colour_manual(values = c(Vertebrates = slate, Invertebrates = ember,
                                 Plants = "#4E7A51"), name = NULL) +
  scale_x_continuous(expand = expansion(mult = c(0, 0.10))) +
  labs(
    title = "Which groups have lost the most species",
    x = "Extinct species", y = NULL
  ) +
  theme_extinct() +
  theme(panel.grid.major.y = element_blank())

## ----group-table--------------------------------------------------------------
ex %>%
  group_by(Group = group) %>%
  summarise(
    Species = n(),
    `Since 2020` = sum(year_published >= 2020),
    Example = first(sort(taxon_scientific_name)),
    .groups = "drop"
  ) %>%
  arrange(desc(Species)) %>%
  mutate(Share = percent(Species / sum(Species), accuracy = 0.1)) %>%
  select(Group, Species, Share, `Since 2020`, `Example species` = Example) %>%
  kable(align = c("l", "r", "r", "r", "l"),
        caption = "Confirmed extinctions by major group") %>%
  kable_styling(full_width = FALSE, bootstrap_options = c("striped", "hover"))

## ----timeline, fig.alt = "Number of species newly listed as Extinct per publication year", fig.width=8, fig.height=4----
per_year <- ex %>% count(year_published, name = "species")

ggplot(per_year, aes(year_published, species)) +
  geom_area(fill = ember, alpha = 0.12) +
  geom_line(colour = ember, linewidth = 0.9) +
  geom_point(colour = ember, size = 1.6) +
  scale_x_continuous(breaks = pretty_breaks(8)) +
  labs(
    title = "When the world's Extinct species entered the Red List",
    subtitle = "Species counted by the publication year of their current Extinct assessment",
    x = "Publication year", y = "Species listed"
  ) +
  theme_extinct()

## ----cumulative, fig.alt = "Cumulative number of species listed as Extinct over time", fig.width=8, fig.height=4----
cumulative <- per_year %>%
  arrange(year_published) %>%
  mutate(cumulative = cumsum(species))

ggplot(cumulative, aes(year_published, cumulative)) +
  geom_area(fill = charcoal, alpha = 0.08) +
  geom_line(colour = charcoal, linewidth = 1) +
  scale_x_continuous(breaks = pretty_breaks(8)) +
  scale_y_continuous(labels = comma) +
  labs(
    title = "The rising tally of confirmed extinctions on the Red List",
    subtitle = "Cumulative species carrying a current Extinct listing",
    x = "Publication year", y = "Cumulative species"
  ) +
  theme_extinct()

## ----decade-table-------------------------------------------------------------
ex %>%
  mutate(decade = paste0(floor(year_published / 10) * 10, "s")) %>%
  group_by(Decade = decade) %>%
  summarise(
    Animals = sum(kingdom == "Animalia"),
    Plants  = sum(kingdom == "Plantae"),
    Total   = n(),
    .groups = "drop"
  ) %>%
  kable(align = c("l", "r", "r", "r"),
        caption = "Extinct listings by publication decade and kingdom") %>%
  kable_styling(full_width = FALSE, bootstrap_options = c("striped", "hover"))

## ----genera, fig.width = 8, fig.height = 5.5, fig.alt = "Genera with the most Extinct species"----
top_genera <- ex %>%
  count(genus, group, name = "species") %>%
  slice_max(species, n = 12) %>%
  mutate(genus = reorder(genus, species))

ggplot(top_genera, aes(species, genus, fill = group)) +
  geom_col(width = 0.7) +
  geom_text(aes(label = species), hjust = -0.3, size = 3, colour = charcoal) +
  scale_x_continuous(expand = expansion(mult = c(0, 0.10))) +
  scale_fill_manual(values = c(
    "Snails & slugs" = ember, "Fishes" = slate, "Amphibians" = "#7A5C99",
    "Flowering plants" = "#4E7A51", "Mussels & clams" = "#C9862B"
  ), name = NULL) +
  labs(
    title = "The genera that lost the most species",
    x = "Extinct species", y = NULL
  ) +
  theme_extinct() +
  theme(panel.grid.major.y = element_blank())

## ----genera-table-------------------------------------------------------------
ex %>%
  count(genus, Group = group, name = "Species") %>%
  slice_max(Species, n = 10, with_ties = FALSE) %>%
  left_join(
    ex %>% group_by(genus) %>%
      summarise(Example = first(sort(taxon_scientific_name)), .groups = "drop"),
    by = "genus"
  ) %>%
  rename(Genus = genus) %>%
  select(Genus, Group, Species, `Example species` = Example) %>%
  kable(align = c("l", "l", "r", "l"),
        caption = "The ten hardest-hit genera in the Extinct catalogue") %>%
  kable_styling(full_width = FALSE, bootstrap_options = c("striped", "hover"))

## ----recent-table-------------------------------------------------------------
ex %>%
  filter(year_published >= 2024) %>%
  arrange(desc(year_published), taxon_scientific_name) %>%
  transmute(
    Species = paste0("*", taxon_scientific_name, "*"),
    `Common name` = ifelse(is.na(taxon_common_names_name), " _ ", taxon_common_names_name),
    Group = group,
    Listed = year_published
  ) %>%
  head(15) %>%
  kable(align = c("l", "l", "l", "r"),
        caption = "A selection of the most recently published Extinct listings") %>%
  kable_styling(full_width = FALSE, bootstrap_options = c("striped", "hover"))

