From 4c830bd3f7845e40c6e28320b29dec0e965416f9 Mon Sep 17 00:00:00 2001 From: Kelli Johnson Date: Thu, 17 Nov 2022 15:37:02 -0800 Subject: [PATCH] deprecate(dopng=) Deprecates `dopng =` because dir = NULL can serve as FALSE. * Remove importsFrom for two functions with :: * Uses ifelse to create main_ to remove so many if statements with duplicated code. * Uses on.exit to call dev.off() in case the function fails, then the device is not left on. * fix(PlotPresenceAbsence.fn): * dim: `match.arg` allows you to list all of the possible options in the function call so users know what is available. Then, `match.arg` will use the first listed as the default. * Uses dontrun plot b/c the figures and download take too long and `check()` complains. So, I wrapped them in dontrun{} and I added an example with the package data where you do not have to download anything. * Checked spelling in documentation and wrapped at 80 characters. Part of #31 TODO: * Use `ggplot2::ggsave()` * Remove the call to windows() which only works on windows machines and will cause GitHub actions to fail if there was a test. --- DESCRIPTION | 3 +- Examples/example_code_pop.R | 11 ++--- R/PlotMap.fn.R | 87 +++++++++++++++++-------------------- R/PlotPresenceAbsence.fn.R | 74 ++++++++++++++++++------------- R/PlotSexRatioStrata.fn.R | 54 +++++++++++------------ R/plotBio.fn.R | 54 ++++++++++++----------- R/plotBioStrata.fn.R | 62 +++++++++++++------------- R/plotFreqData.fn.R | 52 ++++++++++++---------- R/plotSexRatio.fn.R | 52 +++++++++++++--------- R/plotVarLengthAtAge.fn.R | 52 ++++++++++++---------- R/plot_proportion.R | 73 +++++++++++++------------------ vignettes/nwfscSurvey.Rmd | 12 +++-- 12 files changed, 303 insertions(+), 283 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index b65c257..19e2478 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Package: nwfscSurvey Type: Package Title: Northwest Fisheries Science Center Survey -Version: 2.0 +Version: 2.1 Authors@R: c(person(given = c("Chantel", "R."), family = "Wetzel", @@ -26,6 +26,7 @@ Imports: httr, jsonlite, kableExtra, + lifecycle, reshape2, ggplot2 (>= 3.0.0), xtable, diff --git a/Examples/example_code_pop.R b/Examples/example_code_pop.R index 832f963..f01f5e0 100644 --- a/Examples/example_code_pop.R +++ b/Examples/example_code_pop.R @@ -51,8 +51,8 @@ biomass = Biomass.fn(dir = getwd(), dat = catch, strat.df = strata, printfolder # Creates a csv file within the "printfolder" that will be saved within the directory location (dir). # Plot the biomass index -PlotBio.fn(dir = getwd(), dat = biomass, main = "NWFSC WCBBT Survey", dopng = TRUE) -PlotBioStrata.fn(dir = getwd(), survey.name = "NWFSC_WCGBT_Survey", dat = biomass, mfrow.in = c(3,2), sameylim = TRUE, ylim = c(0, 22), dopng = TRUE) +PlotBio.fn(dir = getwd(), dat = biomass, main = "NWFSC WCBBT Survey") +PlotBioStrata.fn(dir = getwd(), survey.name = "NWFSC_WCGBT_Survey", dat = biomass, mfrow.in = c(3,2), sameylim = TRUE, ylim = c(0, 22)) # Plot the CPUE plot_cpue(dir = getwd(), catch = catch) @@ -116,7 +116,8 @@ LFs <- SurveyLFs.fn(dir = getwd(), datL = len, datTows = catch, # NWFSC combo survey data in the past). plot_comps(data = LFs, dir = getwd()) -PlotSexRatio.fn(dir = getwd(), dat = len, data.type = "length", dopng = TRUE, main = "NWFSC WCGBT Survey") +PlotSexRatio.fn(dir = getwd(), dat = len, data.type = "length", main = "NWFSC WCGBT Survey") + #============================================================================================ #Length Biological Data without expansion @@ -148,8 +149,8 @@ AFs <- SurveyAFs.fn(dir = getwd(), datA = age, datTows = catch, sex = 3, nSamps = n, fleet = 7) plot_comps(data = AFs, dir = getwd()) -PlotVarLengthAtAge.fn(dir = getwd(), dat = age, main = "NWFSC WCGBT Survey", dopng = TRUE) -PlotSexRatio.fn(dir = getwd(), dat = age, data.type = "age", dopng = TRUE, main = "NWFSC WCGBT Survey") +PlotVarLengthAtAge.fn(dir = getwd(), dat = age, main = "NWFSC WCGBT Survey") +PlotSexRatio.fn(dir = getwd(), dat = age, data.type = "age", main = "NWFSC WCGBT Survey") #============================================================================================ #Age Biological Data without Expansion diff --git a/R/PlotMap.fn.R b/R/PlotMap.fn.R index 0358703..6ce6545 100644 --- a/R/PlotMap.fn.R +++ b/R/PlotMap.fn.R @@ -1,21 +1,37 @@ -#' #This function will create two plots -#' 1. CPUE from survey data across all years, and -#' 2. CPUE plot of the survey data by year. +#' Create maps with catch-per-unit-effort #' -#' @param dir directory -#' @param dat object created by the PullCatch.fn function -#' @param main name that will be used to name the saved png (i.e., "NWFSC" results in a file called "NWFSC_CPUE_Map.png") -#' @param dopng save the plot as a png inside plots folder -#' @param plot select a subset of plots: 1 = coastwide across all years, 2 = coastwide by year +#' Create the following figures: +#' 1. CPUE plot of the data across all years and/or +#' 2. CPUE plot of the data by year. #' -#' @author Chantel Wetzel +#' @template dir +#' @param dat An object created by [PullCatch.fn()]. +#' @param main A string that will be prepended to the name of the saved png +#' (i.e., "NWFSC" results in a file called "NWFSC_CPUE_Map.png"). +#' @param dopng Deprecated with {nwfscSurvey} 2.1 because providing a non-NULL +#' value to `dir` can serve the same purpose as `dopng = TRUE` without the +#' potential for errors when `dopng = TRUE` and `dir = NULL`. Thus, users +#' no longer have to specify `dopng` to save the plot as a png. +#' @param plot A vector of integers specifying the selection of a subset of +#' plots: 1 = coastwide across all years, 2 = coastwide by year. +#' +#' @author Chantel R. Wetzel #' @export #' #' @import ggplot2 -#' @importFrom rnaturalearth ne_states -#' @importFrom stats quantile -PlotMap.fn <- function(dir = NULL, dat, main = NULL, dopng = FALSE, plot = 1:2) { +PlotMap.fn <- function(dir = NULL, + dat, + main = NULL, + dopng = lifecycle::deprecated(), + plot = 1:2) { + + if (lifecycle::is_present(dopng)) { + lifecycle::deprecate_warn( + when = "2.1", + what = "nwfscSurvey::PlotMap.fn(dopng =)" + ) + } # Create specialized plots pngfun <- function(dir, file, w = 7, h = 7, pt = 12) { @@ -28,28 +44,15 @@ PlotMap.fn <- function(dir = NULL, dat, main = NULL, dopng = FALSE, plot = 1:2) ) } + plotdir <- file.path(dir, "map_plots") + check_dir(dir = plotdir) + main_ <- ifelse(is.null(main), "", paste0(main, "_")) - if (dopng) { - if (is.null(dir)) { - stop("Directory needs to be set.") - } - if (!file.exists(dir)) { - stop("The dir argument leads to a location", ",\ni.e., ", dir, ", that doesn't exist.") - } - - plotdir <- file.path(dir, paste("map_plots", sep = "")) - plotdir.isdir <- file.info(plotdir)$isdir - if (is.na(plotdir.isdir) | !plotdir.isdir) { - dir.create(plotdir) - } - } - - if (!dopng) { + if (!is.null(dir)) { windows(width = 5, height = 7, record = TRUE) } - - map.hires <- ne_states(country = c( + map.hires <- rnaturalearth::ne_states(country = c( "United States of America", "Mexico", "Canada" @@ -59,7 +62,7 @@ PlotMap.fn <- function(dir = NULL, dat, main = NULL, dopng = FALSE, plot = 1:2) ind <- dat$cpue_kg_km2 > 0 pos.cat <- dat[ind, ] neg <- dat[dat$cpue_kg_km2 == 0, ] - mid <- as.numeric(quantile(pos.cat$cpue_kg_km2, 0.50)) + mid <- as.numeric(stats::quantile(pos.cat$cpue_kg_km2, 0.50)) max.size <- 12 plot_format <- theme( @@ -71,13 +74,8 @@ PlotMap.fn <- function(dir = NULL, dat, main = NULL, dopng = FALSE, plot = 1:2) igroup <- 1 if (igroup %in% plot) { - if (dopng) { - if (is.null(main)) { - pngfun(dir = plotdir, file = "CPUE_Map.png", h = 7, w = 5) - } - if (!is.null(main)) { - pngfun(dir = plotdir, file = paste0(main, "_CPUE_Map.png"), h = 7, w = 5) - } + if (!is.null(dir)) { + pngfun(dir = plotdir, file = paste0(main_, "_CPUE_Map.png"), w = 5) } g <- ggplot(dat) + @@ -97,7 +95,7 @@ PlotMap.fn <- function(dir = NULL, dat, main = NULL, dopng = FALSE, plot = 1:2) theme(legend.position = "right") print(g) - if (dopng) { + if (!is.null(dir)) { dev.off() } } @@ -113,13 +111,8 @@ PlotMap.fn <- function(dir = NULL, dat, main = NULL, dopng = FALSE, plot = 1:2) axis.ticks.x = element_blank() ) - if (dopng) { - if (is.null(main)) { - pngfun(dir = plotdir, file = "CPUE_Map_Year.png", h = 7, w = 7) - } - if (!is.null(main)) { - pngfun(dir = plotdir, file = paste0(main, "_CPUE_Map_Year.png"), h = 7, w = 7) - } + if (!is.null(dir)) { + pngfun(dir = plotdir, file = paste0(main_, "_CPUE_Map_Year.png")) } h <- ggplot(dat) + @@ -141,7 +134,7 @@ PlotMap.fn <- function(dir = NULL, dat, main = NULL, dopng = FALSE, plot = 1:2) # coord_fixed(1.3) print(h) - if (dopng) { + if (!is.null(dir)) { dev.off() } } diff --git a/R/PlotPresenceAbsence.fn.R b/R/PlotPresenceAbsence.fn.R index caeec14..d751bd5 100644 --- a/R/PlotPresenceAbsence.fn.R +++ b/R/PlotPresenceAbsence.fn.R @@ -1,37 +1,39 @@ -#' Plot showing presence and absence per haul by depth or latitute bin +#' Plot showing presence and absence per haul by depth, latitude, or sex bin #' -#' Uses the data.frame of data values extracted from the data warehouse -#' by either [PullCatch.fn()] or [PullBio.fn()] to make a table of -#' proportion by depth or latitude bins. If biological data are passed -#' to the function then there is a single option to plot the sex -#' ratio by depth. +#' This function was deprecated in {nwfsc} version 2.1. Please use +#' [plot_proportion()] instead. #' -#' @param data data.frame containing data per haul created by -#' PullCatch.fn() or biological data created by PullBio.fn() where the -#' dim input must be "sex". -#' @param dim Dimension of interest, either "depth", "lat", or "sex" -#' @param dir The directory name to print to -#' @param plot_type Two options area avialable "proportion" or "total" where -#' the default, "proportion", plot the proportion by depth/latitude with equal -#' bar widths and the "total" option plot the numbers by depth/latitude were -#' the bar widths in a production of sampling by depth/latitude. -#' @param depth_min Minimum depth (in meters) +#' @param data data.frame containing data per haul created by [PullCatch.fn()] +#' or biological data created by [PullBio.fn()] where the `dim = "sex"` must +#' be true for the latter. +#' @param dim Dimension of interest, either "depth", "lat", or "sex". +#' @template dir +#' @param plot_type Two options area available "proportion" or "total" where the +#' default, "proportion", plot the proportion by depth/latitude with equal bar +#' widths and the "total" option plot the numbers by depth/latitude were the +#' bar widths in a production of sampling by depth/latitude. +#' @param dopng Deprecated with {nwfscSurvey} 2.1 because providing a non-NULL +#' value to `dir` can serve the same purpose as `dopng = TRUE` without the +#' potential for errors when `dopng = TRUE` and `dir = NULL`. Thus, users +#' no longer have to specify `dopng` to save the plot as a png. +#' @param depth_min Minimum depth (in meters). #' @param depth_max Maximum depth (in meters). A NULL value will cause the -#' function to automatically set depth_max to the multiple of depth_bin_width beyond -#' the 99.9 percentile of the observations. -#' @param depth_bin_width Width of each depth bin (in meters) -#' @param lat_min Minimum latitute (in decimal degrees) -#' @param lat_max Maximum latitute (in decimal degrees) -#' @param lat_bin_width Width of each latitude bin (in decimal degrees) +#' function to automatically set depth_max to the multiple of depth_bin_width +#' beyond the 99.9 percentile of the observations. +#' @param depth_bin_width Width of each depth bin (in meters). +#' @param lat_min Minimum latitute (in decimal degrees). +#' @param lat_max Maximum latitute (in decimal degrees). +#' @param lat_bin_width Width of each latitude bin (in decimal degrees). #' @param add_range_to_main Add the range of latitude or depth by which the data -#' are filtered +#' are filtered. #' @param xlab Label for x-axis. A NULL value will cause the function -#' to choose either "Depth (m)" or "Latitude (°N)" +#' to choose either "Depth (m)" or "Latitude (°N)". #' #' @author Ian G. Taylor and Chantel Wetzel #' @importFrom grDevices gray #' @export #' @examples +#' \dontrun{ #' # load WCGBTS data data #' data.WCGBTS.ling <- nwfscSurvey::PullCatch.fn( #' Name = "lingcod", @@ -44,11 +46,15 @@ #' PlotPresenceAbsence.fn(data = data.WCGBTS.ling, dim = "lat") #' PlotPresenceAbsence.fn(data = data.WCGBTS.ling, dim = "depth") #' PlotPresenceAbsence.fn(data = bio.WCGBTS.ling, dim = "sex") -#' +#' +#' # Plot with package data +#' PlotPresenceAbsence.fn(catch_nwfsc_combo) +#' } PlotPresenceAbsence.fn <- function(data, - dim = c("depth", "lat", "sex")[1], + dim = c("depth", "lat", "sex"), dir = NULL, - plot_type = c('proportion', 'total')[1], + dopng = lifecycle::deprecated(), + plot_type = c("proportion", "total"), depth_min = 50, depth_max = NULL, depth_bin_width = 25, @@ -57,8 +63,17 @@ PlotPresenceAbsence.fn <- function(data, lat_bin_width = 1.0, add_range_to_main = TRUE, xlab = NULL) { + lifecycle::deprecate_soft( + when = "2.1", + what = "PlotPresenceAbsence.fn()", + with = "plot_proportion()" + ) + + dim <- match.arg(dim) + plot_type <- match.arg(plot_type) - plot_proportion(data = data, + plot_proportion( + data = data, dim = dim, dir = dir, plot_type = plot_type, @@ -69,6 +84,7 @@ PlotPresenceAbsence.fn <- function(data, lat_max = lat_max, lat_bin_width = lat_bin_width, add_range_to_main = add_range_to_main, - xlab = xlab) + xlab = xlab + ) } diff --git a/R/PlotSexRatioStrata.fn.R b/R/PlotSexRatioStrata.fn.R index 77cbcc6..bad6d3d 100644 --- a/R/PlotSexRatioStrata.fn.R +++ b/R/PlotSexRatioStrata.fn.R @@ -6,32 +6,38 @@ #' @param strat.vars the parameters to stratify the data #' @param strat.df the created strata matrix with the calculated areas by the createStrataDF.fn function #' @param circleSize circle size -#' @param dopng TRUE/FALSE whether to save a png file +#' @param dopng Deprecated with {nwfscSurvey} 2.1 because providing a non-NULL +#' value to `dir` can serve the same purpose as `dopng = TRUE` without the +#' potential for errors when `dopng = TRUE` and `dir = NULL`. Thus, users +#' no longer have to specify `dopng` to save the plot as a png. #' @param ... Additional arguments for the plots #' #' @author Allan Hicks and Chantel Wetzel #' @export #' @seealso \code{\link{StrataFactors.fn}} -PlotSexRatioStrata.fn <- function(dir = NULL, dat, type = "length", strat.vars = c("Depth_m", "Latitude_dd"), strat.df = NULL, circleSize = 0.05, dopng = FALSE, ...) { - if (dopng) { - if (is.null(dir)) { - stop("Directory needs to be set.") - } - if (!file.exists(dir)) { - stop("The dir argument leads to a location", ",\ni.e., ", dir, ", that doesn't exist.") - } - plotdir <- file.path(dir, paste("plots", sep = "")) - plotdir.isdir <- file.info(plotdir)$isdir - if (is.na(plotdir.isdir) | !plotdir.isdir) { - dir.create(plotdir) - } - if (is.null(main)) { - png(file.path(dir, paste("plots/fraction_female.png", sep = "")), height = 7, width = 7, units = "in", res = 300) - } - if (!is.null(main)) { - png(file.path(dir, paste("plots/", main, "_fraction_female.png", sep = "")), height = 7, width = 7, units = "in", res = 300) - } +PlotSexRatioStrata.fn <- function(dir = NULL, dat, type = "length", strat.vars = c("Depth_m", "Latitude_dd"), strat.df = NULL, circleSize = 0.05, dopng = lifecycle::deprecated(), ...) { + if (lifecycle::is_present(dopng)) { + lifecycle::deprecate_warn( + when = "2.1", + what = "nwfscSurvey::PlotMap.fn(dopng =)" + ) + } + plotdir <- file.path(dir, "plots") + check_dir(dir = plotdir) + main_ <- ifelse(is.null(main), "", paste0(main, "_")) + if (!is.null(dir)) { + png( + filename = file.path( + plotdir, + paste0(main_, "fraction_female.png") + ), + height = 7, + width = 7, + units = "in", + res = 300 + ) + on.exit(dev.off(), add = TRUE) } row.names(strat.df) <- strat.df[, 1] # put in rownames to make easier to index later @@ -41,13 +47,9 @@ PlotSexRatioStrata.fn <- function(dir = NULL, dat, type = "length", strat.vars = datB <- data.frame(datB, stratum = StrataFactors.fn(datB, strat.vars, strat.df)) # create a new column for the stratum factor - # if (dopng) { png(paste0(dir, "/plots/", survey,"_fraction_female.png") ) } - # if (dopng) { png(file.path(dir, paste("plots/", survey,"_fraction_female.png", sep ="")), height=7, width=7, units="in",res=300) } par(mfrow = c(3, 3)) for (i in 1:length(row.names(strat.df))) { - # if (dopng) { png(paste0(dir, "/plots/", survey,"_", row.names(strat.df)[i], "_fraction_female.png"), height=7, width=7, units="in",res=300) } - # par(mfrow = c(5,3)) z <- which(datB$stratum == row.names(strat.df)[i]) subDF <- datB[z, ] @@ -64,9 +66,5 @@ PlotSexRatioStrata.fn <- function(dir = NULL, dat, type = "length", strat.vars = nobs <- temp[, "F"] + temp[, "M"] plot(ratioF, type = "l", col = "red", xlab = axis.name, ylab = "Fraction female", main = row.names(strat.df)[i], ylim = c(0, 1)) # ,...) symbols(ratioF, circles = nobs, inches = circleSize, fg = "red", bg = rgb(1, 0, 0, alpha = 0.5), add = T) - # if (dopng) {dev.off()} - } - if (dopng) { - dev.off() } } diff --git a/R/plotBio.fn.R b/R/plotBio.fn.R index 87a9093..678b0f1 100644 --- a/R/plotBio.fn.R +++ b/R/plotBio.fn.R @@ -11,34 +11,42 @@ #' @param add add additional line to plot #' @param col color #' @param main plot label -#' @param dopng save the plot as a png inside plots folder +#' @param dopng Deprecated with {nwfscSurvey} 2.1 because providing a non-NULL +#' value to `dir` can serve the same purpose as `dopng = TRUE` without the +#' potential for errors when `dopng = TRUE` and `dir = NULL`. Thus, users +#' no longer have to specify `dopng` to save the plot as a png. #' @param ... Additional arguments for the plots #' #' @author Allan Hicks and John Wallace #' @export PlotBio.fn <- function(dir = NULL, dat, CI = 0.95, scalar = 1e6, gap = 0.03, ylab = "Biomass ('000 mt)", xlab = "Year", - main = NULL, ylim = NULL, add = FALSE, col = "black", dopng = FALSE, ...) { + main = NULL, ylim = NULL, add = FALSE, col = "black", dopng = lifecycle::deprecated(), ...) { + + if (lifecycle::is_present(dopng)) { + lifecycle::deprecate_warn( + when = "2.1", + what = "nwfscSurvey::PlotMap.fn(dopng =)" + ) + } + bio <- dat$Bio - if (dopng) { - if (is.null(dir)) { - stop("Directory needs to be set.") - } - if (!file.exists(dir)) { - stop("The dir argument leads to a location", ",\ni.e., ", dir, ", that doesn't exist.") - } - plotdir <- file.path(dir, paste("plots", sep = "")) - plotdir.isdir <- file.info(plotdir)$isdir - if (is.na(plotdir.isdir) | !plotdir.isdir) { - dir.create(plotdir) - } - if (is.null(main)) { - png(paste0(dir, "/plots/designed_based_index.png"), height = 7, width = 7, units = "in", res = 300) - } - if (!is.null(main)) { - png(paste0(dir, "/plots/", main, "_designed_based_index.png"), height = 7, width = 7, units = "in", res = 300) - } + plotdir <- file.path(dir, "plots") + check_dir(plotdir) + main_ <- ifelse(is.null(main), "", paste0(main, "_")) + if (!is.null(dir)) { + png( + filename = file.path( + plotdir, + paste0(main_, "_designed_based_index.png") + ), + height = 7, + width = 7, + units = "in", + res = 300 + ) + on.exit(dev.off(), add = TRUE) } par(mfrow = c(1, 1)) @@ -56,13 +64,9 @@ PlotBio.fn <- function(dir = NULL, dat, CI = 0.95, scalar = 1e6, gap = 0.03, yla gap <- gap * max(y) if (add) { points(x, y, col = col) - } - else { + } else { plot(x, y, ylab = ylab, xlab = xlab, ylim = ylim, main = main, col = col, ...) } segments(x, y + gap, x, ci[1, ], col = col) segments(x, y - gap, x, ci[2, ], col = col) - if (dopng) { - dev.off() - } } diff --git a/R/plotBioStrata.fn.R b/R/plotBioStrata.fn.R index aae12d5..7a13c9e 100644 --- a/R/plotBioStrata.fn.R +++ b/R/plotBioStrata.fn.R @@ -16,7 +16,10 @@ #' @param strata.names custom strata names, if not specified will use the defined names from CreateStrataDF.fn #' @param pch.col Color as string, defaults to "black" #' @param pch.type Numeric pch type, defaults to 16 -#' @param dopng save the plot as a png inside plots folder +#' @param dopng Deprecated with {nwfscSurvey} 2.1 because providing a non-NULL +#' value to `dir` can serve the same purpose as `dopng = TRUE` without the +#' potential for errors when `dopng = TRUE` and `dir = NULL`. Thus, users +#' no longer have to specify `dopng` to save the plot as a png. #' @param ... Additional arguments for the plots #' #' @author Allan Hicks and John Wallace @@ -24,41 +27,41 @@ PlotBioStrata.fn <- function(dir = NULL, dat, CI = 0.95, scalar = 1e6, gap = 0.03, ylab = "Biomass ('000 mt)", xlab = "Year", survey.name = NULL, strata.names = NULL, ylim = NULL, sameylim = FALSE, add = FALSE, mfrow.in = NULL, col = "black", - pch.col = "black", pch.type = 16, dopng = FALSE, ...) { + pch.col = "black", pch.type = 16, dopng = lifecycle::deprecated(), ...) { + + if (lifecycle::is_present(dopng)) { + lifecycle::deprecate_warn( + when = "2.1", + what = "nwfscSurvey::PlotMap.fn(dopng =)" + ) + } + bio_strat <- dat$StrataEsts - if (dopng) { - if (is.null(dir)) { - stop("Directory needs to be set.") - } - if (!file.exists(dir)) { - stop("The dir argument leads to a location", ",\ni.e., ", dir, ", that doesn't exist.") - } - plotdir <- file.path(dir, paste("plots", sep = "")) - plotdir.isdir <- file.info(plotdir)$isdir - if (is.na(plotdir.isdir) | !plotdir.isdir) { - dir.create(plotdir) - } - if (is.null(survey.name)) { - png(paste0(dir, "/plots/designed_based_by_strata_index.png"), height = 7, width = 7, units = "in", res = 300) - } - if (!is.null(survey.name)) { - png(paste0(dir, "/plots/", survey.name, "_designed_based_by_strata_index.png"), height = 7, width = 7, units = "in", res = 300) - } + plotdir <- file.path(dir, "plots") + check_dir(dir = plotdir) + main_ <- ifelse(is.null(survey.name), "", paste0(survey.name, "_")) + if (!is.null(dir)) { + png( + filename = file.path( + plotdir, + paste0(main_, "designed_based_by_strata_index.png") + ), + height = 7, + width = 7, + units = "in", + res = 300 + ) + on.exit(dev.off(), add = TRUE) } + if (is.null(strata.names)) { strata.names <- names(bio_strat) } if (!is.null(mfrow.in)) { - if (length(mfrow.in) == 1) { - par(mfrow = c(mfrow.in[1], mfrow.in[1])) - } - if (length(mfrow.in) != 1) { - par(mfrow = c(mfrow.in[1], mfrow.in[2])) - } - } - if (is.null(mfrow.in)) { + par(mfrow = c(mfrow.in[1], mfrow.in[length(mfrow.in)])) + } else { par(mfrow = c(length(bio_strat) / 2, 2)) } @@ -99,7 +102,4 @@ PlotBioStrata.fn <- function(dir = NULL, dat, CI = 0.95, scalar = 1e6, gap = 0.0 segments(x0 = x, y0 = y - gap, x1 = x, y1 = ci[2, ], col = col) } - if (dopng) { - dev.off() - } } diff --git a/R/plotFreqData.fn.R b/R/plotFreqData.fn.R index f222b3f..b860b36 100644 --- a/R/plotFreqData.fn.R +++ b/R/plotFreqData.fn.R @@ -11,7 +11,10 @@ #' @param main main plot text #' @param xlim x-limit values #' @param ymax Value used to truncate y-axis, defaults to NULL -#' @param dopng save the plot as a png inside plots folder +#' @param dopng Deprecated with {nwfscSurvey} 2.1 because providing a non-NULL +#' value to `dir` can serve the same purpose as `dopng = TRUE` without the +#' potential for errors when `dopng = TRUE` and `dir = NULL`. Thus, users +#' no longer have to specify `dopng` to save the plot as a png. #' @param w Numeric figure width, defaults to 7 #' @param h Numeric figure height, defaults to 7 #' @param ... Additional arguments for the plots @@ -20,29 +23,33 @@ #' @export PlotFreqData.fn <- function(dir = NULL, dat, inch = 0.15, ylab = "Bins", xlab = "Year", zero2NAs = T, main = NULL, - xlim = NULL, ymax = NULL, dopng = FALSE, w = 7, h = 7, ...) { + xlim = NULL, ymax = NULL, dopng = lifecycle::deprecated(), w = 7, h = 7, ...) { + + if (lifecycle::is_present(dopng)) { + lifecycle::deprecate_warn( + when = "2.1", + what = "nwfscSurvey::PlotMap.fn(dopng =)" + ) + } + dataType <- sum(names(dat) == "ageErr") dataType <- ifelse(dataType == 0, "Length", "Age") - if (dopng) { - if (is.null(dir)) { - stop("Directory needs to be set.") - } - if (!file.exists(dir)) { - stop("The dir argument leads to a location", ",\ni.e., ", dir, ", that doesn't exist.") - } - - plotdir <- file.path(dir, paste("plots", sep = "")) - plotdir.isdir <- file.info(plotdir)$isdir - if (is.na(plotdir.isdir) | !plotdir.isdir) { - dir.create(plotdir) - } - if (is.null(main)) { - png(file.path(dir, paste("plots/", dataType, "_Frequency.png", sep = "")), height = h, width = w, units = "in", res = 300) - } - if (!is.null(main)) { - png(file.path(dir, paste("plots/", main, "_", dataType, "_Frequency.png", sep = "")), height = h, width = w, units = "in", res = 300) - } + plotdir <- file.path(dir, "plots") + check_dir(dir = plotdir) + main_ <- ifelse(is.null(main), "", paste0(main, "_")) + if (!is.null(dir)) { + png( + filename = file.path( + plotdir, + paste0(main_, dataType, "_Frequency.png") + ), + height = h, + width = w, + units = "in", + res = 300 + ) + on.exit(dev.off(), add = TRUE) } x <- as.numeric(as.character(dat$year)) @@ -115,7 +122,4 @@ PlotFreqData.fn <- function(dir = NULL, dat, inch = 0.15, ylab = "Bins", xlab = z <- c(unlist(dat[, (numLens + 1):ncol(dat)]), min(dat, na.rm = TRUE)) symbols(c(rep(x, length(y)), 0), c(rep(y, each = length(x)), 0), circles = z, main = name, inches = inch, xlab = xlab, ylab = ylab, xlim = xlim, ...) } - if (dopng) { - dev.off() - } } diff --git a/R/plotSexRatio.fn.R b/R/plotSexRatio.fn.R index 0ee00bf..79e1520 100644 --- a/R/plotSexRatio.fn.R +++ b/R/plotSexRatio.fn.R @@ -5,29 +5,45 @@ #' @param data.type "length" or "age" #' @param main ame that will be used to name the saved png #' @param circleSize circle size +#' @param dopng Deprecated with {nwfscSurvey} 2.1 because providing a non-NULL +#' value to `dir` can serve the same purpose as `dopng = TRUE` without the +#' potential for errors when `dopng = TRUE` and `dir = NULL`. Thus, users +#' no longer have to specify `dopng` to save the plot as a png. #' @param ... Additional arguments for the plots #' #' @author Allan Hicks and Chantel Wetzel #' @importFrom graphics abline #' @export -PlotSexRatio.fn <- function(dir, dat, data.type = "length", main = NULL, circleSize = 0.1, ...) { +PlotSexRatio.fn <- function(dir, + dat, + data.type = "length", + main = NULL, + circleSize = 0.1, + dopng = lifecycle::deprecated(), + ...) { + if (lifecycle::is_present(dopng)) { + lifecycle::deprecate_warn( + when = "2.1", + what = "nwfscSurvey::PlotMap.fn(dopng =)" + ) + } - if(!is.null(dir)) { - if (!file.exists(dir)) { - stop("The dir argument leads to a location", ",\ni.e., ", dir, ", that doesn't exist.") - } - plotdir <- file.path(dir, paste("plots", sep = "")) - plotdir.isdir <- file.info(plotdir)$isdir - if (is.na(plotdir.isdir) | !plotdir.isdir) { - dir.create(plotdir) - } - if (is.null(main)) { - png(file.path(dir, "plots", paste(data.type, "_fraction_female.png", sep = "")), height = 7, width = 7, units = "in", res = 300) - } - if (!is.null(main)) { - png(file.path(dir, "plots", paste(main, "_", data.type, "_fraction_female.png", sep = "")), height = 7, width = 7, units = "in", res = 300) - } + plotdir <- file.path(dir, "plots") + check_dir(dir = plotdir) + main_ <- ifelse(is.null(main), "", paste0(main, "_")) + if (!is.null(dir)) { + png( + filename = file.path( + plotdir, + paste0(main_, data.type, "_fraction_female.png") + ), + height = 7, + width = 7, + units = "in", + res = 300 + ) + on.exit(dev.off(), add = TRUE) } round_any <- function(x, accuracy, f = round) { @@ -57,10 +73,6 @@ PlotSexRatio.fn <- function(dir, dat, data.type = "length", main = NULL, circleS inches = circleSize, fg = "red", bg = rgb(1, 0, 0, alpha = 0.5), add = TRUE) - if (!is.null(dir)) { - dev.off() - } - test <- dplyr::count(dat, bin, Sex) %>% mutate(Proportion = n / sum(n)) diff --git a/R/plotVarLengthAtAge.fn.R b/R/plotVarLengthAtAge.fn.R index efcfaf0..bf36832 100644 --- a/R/plotVarLengthAtAge.fn.R +++ b/R/plotVarLengthAtAge.fn.R @@ -13,13 +13,24 @@ #' @param bins The bins to put ages into. If NULL then simply uses the ages as recorded. #' @param legX legend location for x axis, defaults to "bottomleft" #' @param legY legend location for y axis, defaults to NULL -#' @param dopng TRUE/FALSE whether to save a png file +#' @param dopng Deprecated with {nwfscSurvey} 2.1 because providing a non-NULL +#' value to `dir` can serve the same purpose as `dopng = TRUE` without the +#' potential for errors when `dopng = TRUE` and `dir = NULL`. Thus, users +#' no longer have to specify `dopng` to save the plot as a png. #' @param ... Additional arguments for the plots #' #' @author Allan Hicks and Chantel Wetzel #' @export -PlotVarLengthAtAge.fn <- function(dir = NULL, dat, main = NULL, ageBin = 1, bySex = T, parStart = c(52, 0.09, 1), estVB = T, bins = NULL, legX = "bottomleft", legY = NULL, dopng = FALSE, ...) { +PlotVarLengthAtAge.fn <- function(dir = NULL, dat, main = NULL, ageBin = 1, bySex = T, parStart = c(52, 0.09, 1), estVB = T, bins = NULL, legX = "bottomleft", legY = NULL, dopng = lifecycle::deprecated(), ...) { + + if (lifecycle::is_present(dopng)) { + lifecycle::deprecate_warn( + when = "2.1", + what = "nwfscSurvey::PlotMap.fn(dopng =)" + ) + } + # calculate and plot the sd and cv for length at age # if you enter estVB=F, then it uses the parStart as the VB parameters @@ -57,24 +68,21 @@ PlotVarLengthAtAge.fn <- function(dir = NULL, dat, main = NULL, ageBin = 1, bySe nn <- 2 } - if (dopng) { - if (is.null(dir)) { - stop("Directory needs to be set.") - } - if (!file.exists(dir)) { - stop("The dir argument leads to a location", ",\ni.e., ", dir, ", that doesn't exist.") - } - plotdir <- file.path(dir, paste("plots", sep = "")) - plotdir.isdir <- file.info(plotdir)$isdir - if (is.na(plotdir.isdir) | !plotdir.isdir) { - dir.create(plotdir) - } - if (is.null(main)) { - png(file.path(dir, paste("plots/VarLengthAtAge.png", sep = "")), height = 7, width = 7, units = "in", res = 300) - } - if (!is.null(main)) { - png(file.path(dir, paste("plots/", main, "_VarLengthAtAge.png", sep = "")), height = 7, width = 7, units = "in", res = 300) - } + plotdir <- file.path(dir, "plots") + check_dir(dir = plotdir) + main_ <- ifelse(is.null(main), "", paste0(main, "_")) + if (!is.null(dir)) { + png( + filename = file.path( + plotdir, + paste0(main_, "VarLengthAtAge.png") + ), + height = 7, + width = 7, + units = "in", + res = 300 + ) + on.exit(dev.off(), add = TRUE) } par(mfcol = c(2, nn), mar = c(3, 5, 3, 5)) @@ -117,8 +125,6 @@ PlotVarLengthAtAge.fn <- function(dir = NULL, dat, main = NULL, ageBin = 1, bySe mtext("CV", side = 4, line = 2.6) legend(x = legX, y = legY, c("SD", "CV"), pch = c(16, 3), lty = c(1, 2)) } - if (dopng) { - dev.off() - } + return(out) } diff --git a/R/plot_proportion.R b/R/plot_proportion.R index 602237d..39e9a66 100644 --- a/R/plot_proportion.R +++ b/R/plot_proportion.R @@ -1,38 +1,39 @@ -#' Plot showing presence and absence per haul by depth or latitute bin +#' Plot showing presence and absence per haul by depth, latitude, or sex bin #' -#' Uses the data.frame of data values extracted from the data warehouse -#' by either [PullCatch.fn()] or [PullBio.fn()] to make a table of +#' Uses the `data.frame` of data values extracted from the data warehouse +#' by either [PullCatch.fn()] or [PullBio.fn()] to make a table of #' proportion by depth or latitude bins. If biological data are passed -#' to the function then there is a single option to plot the sex +#' to the function then there is a single option to plot the sex #' ratio by depth. #' -#' @param data data.frame containing data per haul created by -#' PullCatch.fn() or biological data created by PullBio.fn() where the -#' dim input must be "sex". +#' @param data `data.frame` containing data per haul created by +#' [PullCatch.fn()] or biological data created by [PullBio.fn()] where +#' `dim` must be `dim = "sex"`. #' @param dim Dimension of interest, either "depth", "lat", or "sex". -#' @param dir The directory name to save figures to where they will be save -#' via file.path(dir, "plots"). -#' @param plot_type Two options area avialable "proportion" or "total" where -#' the default, "proportion", plot the proportion by depth/latitude with equal -#' bar widths and the "total" option plot the numbers by depth/latitude were -#' the bar widths in a production of sampling by depth/latitude. -#' @param depth_min Minimum depth (in meters) +#' @dir dir The directory name to save figures to where they will be save +#' via `file.path(dir, "plots")`. +#' @param plot_type Two options area available, `"proportion"` or `"total"` where +#' the default, `"proportion"`, plots the proportion by depth/latitude with equal +#' bar widths and the `"total"` option plots the numbers by depth/latitude with +#' the bar widths in relation to sampling by depth/latitude. +#' @param depth_min Minimum depth (in meters). #' @param depth_max Maximum depth (in meters). A NULL value will cause the #' function to automatically set depth_max to the multiple of depth_bin_width beyond #' the 99.9 percentile of the observations. -#' @param depth_bin_width Width of each depth bin (in meters) -#' @param lat_min Minimum latitute (in decimal degrees) -#' @param lat_max Maximum latitute (in decimal degrees) -#' @param lat_bin_width Width of each latitude bin (in decimal degrees) +#' @param depth_bin_width Width of each depth bin (in meters). +#' @param lat_min Minimum latitude (in decimal degrees). +#' @param lat_max Maximum latitude (in decimal degrees). +#' @param lat_bin_width Width of each latitude bin (in decimal degrees). #' @param add_range_to_main Add the range of latitude or depth by which the data -#' are filtered +#' are filtered. #' @param xlab Label for x-axis. A NULL value will cause the function -#' to choose either "Depth (m)" or "Latitude (°N)" +#' to choose either "Depth (m)" or "Latitude (°N)". #' #' @author Ian G. Taylor and Chantel Wetzel #' @importFrom grDevices gray #' @export #' @examples +#' \dontrun{ #' # load WCGBTS data data #' data.WCGBTS.ling <- nwfscSurvey::PullCatch.fn( #' Name = "lingcod", @@ -45,11 +46,11 @@ #' plot_proportion(data = data.WCGBTS.ling, dim = "lat") #' plot_proportion(data = data.WCGBTS.ling, dim = "depth") #' plot_proportion(data = bio.WCGBTS.ling, dim = "sex") -#' +#' } plot_proportion <- function(data, - dim = c("depth", "lat", "sex")[1], + dim = c("depth", "lat", "sex"), dir = NULL, - plot_type = c('proportion', 'total')[1], + plot_type = c("proportion", "total"), depth_min = 50, depth_max = NULL, depth_bin_width = 25, @@ -60,17 +61,12 @@ plot_proportion <- function(data, xlab = NULL) { # check inputs - if (!dim %in% c("depth", "lat", "sex")) { - message( - "The dim function input needs to be either depth, lat, or sex.") - break() - } + dim <- match.arg(dim) + dim <- match.arg(plot_type) if (dim == "sex"){ if (sum(colnames(data) == "Sex") != 1) { - message( - "The data function input needs to be a biological data file.") - break() + stop("The data function input needs to be a biological data file.") } } @@ -149,18 +145,13 @@ plot_proportion <- function(data, filename <- paste0("sex_", plot_type, "_by_depth.png") } - if (!is.null(dir)) { - if (!file.exists(dir)) { - stop("The dir argument leads to a location", ",\ni.e., ", dir, ", that doesn't exist.") - } + if (!is.null(dir)) { plotdir <- file.path(dir, paste("plots", sep = "")) - plotdir.isdir <- file.info(plotdir)$isdir - if (is.na(plotdir.isdir) | !plotdir.isdir) { - dir.create(plotdir) - } + check_dir(plotdir) png(file.path(dir, "plots", filename), height = 7, width = 7, units = "in", res = 300 ) + on.exit(dev.off()) } # make table @@ -201,8 +192,4 @@ plot_proportion <- function(data, } abline(h = 0.5, col = 'white', lty = 1, lwd = 4) - # close PNG if it was used - if (!is.null(dir)) { - dev.off() - } } diff --git a/vignettes/nwfscSurvey.Rmd b/vignettes/nwfscSurvey.Rmd index 4ae45cb..410c709 100644 --- a/vignettes/nwfscSurvey.Rmd +++ b/vignettes/nwfscSurvey.Rmd @@ -107,7 +107,7 @@ PlotBio.fn(dir = getwd(), main = "NWFSC shelf-slope bottom trawl survey", ...) ``` -The Biomass.fn returns a list with the second element containing the design-based index of abundance. The design based index is calculated based on the defined stratas. The function writes a csv file inside the dir input location to a "forSS" folder. The PlotBio.fn plots the calculated design based index from the Biomass.fn. If the dopng is set to true a "plot" folder will be created in the directory location and a png of the plot will be saved. +The Biomass.fn returns a list with the second element containing the design-based index of abundance. The design based index is calculated based on the defined stratas. The function writes a csv file inside the dir input location to a "forSS" folder. The PlotBio.fn plots the calculated design based index from the Biomass.fn. If `dir` does not equal `NULL`, then a "plot" folder will be created in the directory location and a png of the plot will be saved. #### Length composition data @@ -141,12 +141,11 @@ PlotFreqData.fn(dir = getwd(), dat = Lengths, ylim = c(0,50), yaxs = "i", - ylab = "Length (cm)", - dopng = TRUE, + ylab = "Length (cm)", ...) ``` -If the dopng is set to true a "plot" folder will be created in the directory location and a png of the plot will be saved. +If `dir` does not equal `NULL`, then a "plot" folder will be created in the directory location and a png of the plot will be saved. #### Marginal age composition data @@ -176,11 +175,10 @@ To plot the age frequency data: PlotFreqData.fn(dir = getwd(), dat = Ages, ylim = c(0,100), - ylab = "Age", - dopng = TRUE, + ylab = "Age", ...) ``` -If the dopng is set to true a "plot" folder will be created in the directory location and a png of the plot will be saved. +If `dir` is not `NULL`, then a "plot" folder will be created in the directory location and a png of the plot will be saved. #### Conditional-age-at-length data To calculate conditional-age-at-length data formatted for SS: