Skip to content

Commit

Permalink
deprecate(dopng=)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
kellijohnson-NOAA committed Nov 22, 2022
1 parent 4215d33 commit 9c4c679
Show file tree
Hide file tree
Showing 12 changed files with 303 additions and 283 deletions.
3 changes: 2 additions & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
@@ -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",
Expand All @@ -26,6 +26,7 @@ Imports:
httr,
jsonlite,
kableExtra,
lifecycle,
reshape2,
ggplot2 (>= 3.0.0),
xtable,
Expand Down
11 changes: 6 additions & 5 deletions Examples/example_code_pop.R
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
87 changes: 40 additions & 47 deletions R/PlotMap.fn.R
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -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"
Expand All @@ -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(
Expand All @@ -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) +
Expand All @@ -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()
}
}
Expand All @@ -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) +
Expand All @@ -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()
}
}
Expand Down
74 changes: 45 additions & 29 deletions R/PlotPresenceAbsence.fn.R
Original file line number Diff line number Diff line change
@@ -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",
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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
)

}
54 changes: 26 additions & 28 deletions R/PlotSexRatioStrata.fn.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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, ]

Expand All @@ -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()
}
}
Loading

0 comments on commit 9c4c679

Please sign in to comment.