From 450411f46319c55fa1989835cf8a066af41eb2c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Greni=C3=A9?= Date: Tue, 23 Jul 2024 11:38:27 +0200 Subject: [PATCH] Implement it for fb_plot_site_traits_completeness() --- R/fb_plot_number_sites_by_species.R | 50 +++++++++++++++++-- .../test-fb_plot_site_traits_completeness.R | 1 + 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/R/fb_plot_number_sites_by_species.R b/R/fb_plot_number_sites_by_species.R index 7e32ff66..5b095387 100644 --- a/R/fb_plot_number_sites_by_species.R +++ b/R/fb_plot_number_sites_by_species.R @@ -19,21 +19,49 @@ #' fb_plot_number_sites_by_species(site_species) #' #' # Add a vertical cutoff line (40% of sites) -#' fb_plot_number_sites_by_species(site_species, 0.4) +#' fb_plot_number_sites_by_species(site_species, threshold = 0.4) fb_plot_number_sites_by_species <- function( - site_species, threshold_sites_proportion = NULL + site_species, species_categories = NULL, threshold_sites_proportion = NULL ) { # Check ---------------------------------------------------------------------- check_site_species(site_species) + check_species_categories(species_categories) + if (!is.null(threshold_sites_proportion)) { check_threshold_proportion(threshold_sites_proportion, "site") } + + # Splitting species by category + species_split <- list(single_cat = species_traits[["species"]]) + category_name <- "single_cat" + + if (!is.null(species_categories)) { + + category_name <- colnames(species_categories)[2] + + species_split <- split( + species_categories[, 1], species_categories[, 2] + ) + + } + + + # Split sites according to species' categories + site_species_categories <- lapply( + species_split, + function(x) site_species[, c("site", x), drop = FALSE] + ) + # Get the numbers - number_sites_by_species <- fb_count_sites_by_species(site_species) - n_species <- nrow(site_species) + number_sites_by_species <- lapply( + site_species_categories, fb_count_sites_by_species + ) + n_species <- lapply(site_species_categories, nrow) + + # Construct y-axis breaks # Under 25 observation, label everyone of them @@ -68,6 +96,20 @@ fb_plot_number_sites_by_species <- function( levels = rev(number_sites_by_species$species) ) + # Manage conditional faceting + if (is.null(species_categories)) { + + category_facet <- NULL + + } else { + + category_facet <- ggplot2::facet_wrap( + ggplot2::vars( + !!rlang::sym(category_name)), scales = "free" + ) + + } + # Clean environment rm(site_species) diff --git a/tests/testthat/test-fb_plot_site_traits_completeness.R b/tests/testthat/test-fb_plot_site_traits_completeness.R index 75b67700..c26f151b 100644 --- a/tests/testthat/test-fb_plot_site_traits_completeness.R +++ b/tests/testthat/test-fb_plot_site_traits_completeness.R @@ -33,4 +33,5 @@ test_that("fb_plot_site_traits_completeness works", { ) ) ) + })