Package 'stockplotr'

Title: Tables and Figures for Stock Assessments
Description: Creates exploratory and finished tables and figures for stock assessment documents from U.S. stock assessment model outputs. This packages addresses parts of the stock assessment workflow that interprets outputs of stock assessment models as well as allows the analyst to create report ready tables and figures, reducing the need to create their own and format then when adding into a report. This package is intended to be used in conjuction with 'asar', a partially automated template for writing various stock assessment reports. Throughout development, we will be creating a set of standardized figures and tables for a stock assessment report, developing functions to produce a variety of diagonostic plots, and other helpful materials. The advantage of using this package over others is that it applies to a range of stock assessment model outputs and standardizes them.
Authors: Samantha Bredeck [aut, cre] (ORCID: <https://orcid.org/0009-0003-3744-6428>), Sophie Breitbart [aut, ctb] (ORCID: <https://orcid.org/0000-0001-9641-9786>), Steve Saul [aut], Kelli Johnson [ctb] (ORCID: <https://orcid.org/0000-0002-5149-451X>), Megumi Oshima [ctb] (ORCID: <https://orcid.org/0000-0002-8249-1442>)
Maintainer: Samantha Bredeck <[email protected]>
License: MIT + file LICENSE
Version: 0.16.0.9000
Built: 2026-11-23 22:05:27 UTC
Source: https://github.com/nmfs-ost/stockplotr

Help Index


Add caption and alt text to the captions_alt_text.csv file

Description

Adds a new row to an existing captions_alt_text.csv file with a label, type, caption, and alt_text for a figure or table not present in stockplotr.

Usage

add_caption_alt_text(
  topic_label,
  fig_or_table,
  caption,
  alt_text = "",
  dir = file.path(getwd(), "captions_alt_text.csv")
)

Arguments

topic_label

String. Figure/table label. For automated matching in asar-based report, it must match the label in your plot's chunk options, MINUS the "fig-" or "tab-". For example, the label "custom_table1" would match up properly with the "tbl-custom_table1" code chunk label.

fig_or_table

String. Indicates whether the object is a "table" or "figure"

Options: "figure" or "table"

caption

String. Figure/table caption.

alt_text

String. Figure alternative text. Unnecessary for text-based tables.

Default: ""

dir

Path. Path to the existing captions_alt_text.csv file that will be updated with the new caption and alt text.

Default: file.path(getwd(), "captions_alt_text.csv")

Examples

## Not run: 
add_caption_alt_text(
  topic_label = "my_topic",
  fig_or_table = "figure",
  caption = "My example figure caption.",
  alt_text = "My example figure alt text.",
  dir = file.path(getwd(), "captions_alt_text.csv")
)

## End(Not run)

Big Skate conditional age-at-length data

Description

Conditional age-at-length data and fits from the 2019 Big Skate stock assessment (see bigskate_lencomp). The data are the condbase rows of convert_output() applied to the output of r4ss::SS_output(). Each age composition is for one sex and one length bin, and sums to one. See data-raw/bigskate_comps.R.

Usage

bigskate_caal

Format

A tibble in the standard convert_output() format with 26240 rows and 35 columns. The columns used for compositions are:

label

"conditional_age_composition_observed", "conditional_age_composition_predicted", "conditional_age_composition_pearson_residual", or "conditional_age_composition_sample_size"

estimate

Value of the label

module_name

"condbase"

year

Year of the observation

fleet

Fleet name: "Fishery_current" or "WCGBTS"

sex

"female" or "male"

part

Partition: 0 = whole catch, 1 = discard, 2 = retained

length_bins

Length bin the ages are conditioned on (Lbin_lo in r4ss)

age

Age

Source

Taylor, I.G., Gertseva, V., Stephens, A., and Bizzarro, J. (2019). Status of Big Skate (Beringraja binoculata) off the U.S. Pacific Coast in 2019. Pacific Fishery Management Council, Portland, OR.

See Also

bigskate_lencomp, prepare_composition_data(), plot_composition_andre()


Big Skate length composition data

Description

Length compositions and fits from the 2019 Big Skate stock assessment for the U.S. West Coast (BigSkate_2019 in the Stock Synthesis test models), the model used for the r4ss example plots at https://r4ss.github.io/r4ss/BigSkate/. The data are the lendbase rows of convert_output() applied to the output of r4ss::SS_output(). See data-raw/bigskate_comps.R.

Usage

bigskate_lencomp

Format

A tibble in the standard convert_output() format with 14504 rows and 35 columns. The columns used for compositions are:

label

"length_composition_observed", "length_composition_predicted", "length_composition_pearson_residual" (as reported by Stock Synthesis), or "length_composition_sample_size" (adjusted input sample size, Nsamp_adj in r4ss)

estimate

Value of the label

module_name

"lendbase"

year

Year of the observation

fleet

Fleet name: "Fishery_current", "WCGBTS", or "Triennial"

sex

"female" or "male"

part

Partition: 0 = whole catch, 1 = discard, 2 = retained

length_bins

Lower edge of the length bin (cm)

Details

Compositions are sex-specific, with female and male proportions summing to one within each year, fleet, and partition. Fishery_current has separate retained and discarded compositions.

Source

Taylor, I.G., Gertseva, V., Stephens, A., and Bizzarro, J. (2019). Status of Big Skate (Beringraja binoculata) off the U.S. Pacific Coast in 2019. Pacific Fishery Management Council, Portland, OR.

See Also

bigskate_caal, prepare_composition_data(), plot_composition_distribution()


Calculate key quantities

Description

Calculate key quantities

Usage

calc_kqs(
  returned_kq,
  prepared_data = NULL,
  dat = NULL,
  final = NULL,
  relative = NULL,
  module = NULL,
  ...
)

Arguments

returned_kq

String. Key quantity to be returned.

prepared_data

Data frame. The prepared_data object.

dat

Data frame. The original data object.

final

ggplot2 object. The final figure.

relative

Logical. TRUE/FALSE; specify whether to set y-axis values relative to the ref_line value.

module

Character vector. Module name found in dat$module_name.

...

Additional arguments to be passed to the function.

Value

The value of the specified key quantity.

Examples

## Not run: 
calc_kqs(
  returned_kq = "F.min",
  dat = dat
)

## End(Not run)

Calculate reference value point

Description

Calculate reference value point

Usage

calculate_reference_point(dat, reference_name, lbs = FALSE)

Arguments

dat

Data frame or list. A tibble or named list of tibbles (input as list()) returned from convert_output.

If inputting a list of tibbles, the first tibble's reference point defined in ref_line is used to plot a reference line or calculate relative spawning biomass.

reference_name

String. Name of the reference point (e.g. "spawning biomass msy")

lbs

[Deprecated] Logical. TRUE/FALSE; indicate whether to convert the y-axis values from kilograms to pounds. The default units match the default in the unit_label argument - 'mt'. – Deprecate

Default: FALSE

Value

the value of the reference point name found in the dat file.


Create loop to test for differences in column values

Description

Create loop to test for differences in column values

Usage

check_label_differences(dat, index_variables, id_group = NULL)

Arguments

dat

Data frame. Input data into process_table

index_variables

Character vector. The index_variables vector created within process_table

id_group

String. The identifying index variable as a string

Default: NULL


Code to convert BAM output to standard framework.

Description

Does not change naming conventions.

Usage

conout_bam(file, out_new, fleet_names = NULL)

Arguments

file

Assessment model output file path or object in the user's environment. Currently accepts SS3 Report.sso file, BAM .rda file, Rceattle model object, and FIMS model object.

out_new

The empty standard output data frame from convert_output(), which sets the columns of the output.

fleet_names

List of named character vectors. Names of fleets in the assessment model as shortened in the output file or names of fleets to replace the native fleet names in the output. For example, if fleet names in the model are 1, 2, 3 then fleet_names = c("fleet1" = 1, "fleet2" = 2, "fleet3" = 3).

Default: NULL

Should match length of files if >1 model.

Value

Reshaped data frame.


Code to convert Rceattle output to standard framework.

Description

Does not change naming conventions.

Usage

conout_rceattle(file, out_new, fleet_names = NULL)

Arguments

file

Assessment model output file path or object in the user's environment. Currently accepts SS3 Report.sso file, BAM .rda file, Rceattle model object, and FIMS model object.

out_new

The empty standard output data frame from convert_output(), which sets the columns of the output.

fleet_names

List of named character vectors. Names of fleets in the assessment model as shortened in the output file or names of fleets to replace the native fleet names in the output. For example, if fleet names in the model are 1, 2, 3 then fleet_names = c("fleet1" = 1, "fleet2" = 2, "fleet3" = 3).

Default: NULL

Should match length of files if >1 model.

Value

Reshaped data frame.


Code to convert SS3 output to standard framework.

Description

Does not change naming conventions. Contains code to work with SS3 Report.sso file or returned object from r4ss::ss_output().

Usage

conout_ss3(file, out_new, fleet_names = NULL)

Arguments

file

Assessment model output file path or object in the user's environment. Currently accepts SS3 Report.sso file, BAM .rda file, Rceattle model object, and FIMS model object.

out_new

The empty standard output data frame from convert_output(), which sets the columns of the output.

fleet_names

List of named character vectors. Names of fleets in the assessment model as shortened in the output file or names of fleets to replace the native fleet names in the output. For example, if fleet names in the model are 1, 2, 3 then fleet_names = c("fleet1" = 1, "fleet2" = 2, "fleet3" = 3).

Default: NULL

Should match length of files if >1 model.

Value

Reshaped data frame.


Convert Output

Description

Format stock assessment output file to a standardized tibble.

Usage

convert_output(
  files,
  models = NULL,
  fleet_names = NULL,
  save_dir = NULL,
  start_year = NULL,
  file = lifecycle::deprecated(),
  model = lifecycle::deprecated()
)

Arguments

files

List of paths. Assessment model output file paths. Currently accepts SS3 r4ss::ss_output() or Report.sso file (being deprecated), BAM .rda file, Rceattle model object, and FIMS output (the tibble returned by FIMS::get_estimates(), a FIMSFit object, or an .rds file with either). If multiple elements, all valid models will be read, converted, and appended together.

names(files) will be used as the name of the model in the output.

models

Character vector. Assessment model used in evaluation

Default: NULL

Options: "ss3", "bam", "fims", "rceattle"

Should match length of files if >1 model.

fleet_names

List of named character vectors. Names of fleets in the assessment model as shortened in the output file or names of fleets to replace the native fleet names in the output. For example, if fleet names in the model are 1, 2, 3 then fleet_names = c("fleet1" = 1, "fleet2" = 2, "fleet3" = 3).

Default: NULL

Should match length of files if >1 model.

save_dir

Path. Full file path to save the converted output file. If saved file name is not indicated, the file will be saved as "std_output.rda" in the file path provided.

Default: NULL

start_year

Number. First year of the model, for FIMS output only. FIMS reports years as indices (1 = first model year), which are converted to years when start_year is given.

Default: NULL (years are left as indices)

file

[Deprecated] This argument was deprecated in favor of the files argument in order to clarify that multiple files can be processed simultaneously.

model

[Deprecated] This argument was deprecated in favor of the models argument in order to clarify that multiple models can be processed simultaneously.

Details

The resulting object is a long-format, transformed and machine readable version of a model output file. Converted data frame is always returned. It will also be saved if save_dir is not NULL.

For FIMS, each data point (index, landings, and age and length compositions) is split into an observed row (e.g., "index_observed") and a predicted row (e.g., "index_predicted"), as for the other models. Observed rows hold the observation error (a log-scale standard error for lognormal data) in uncertainty and the negative log-likelihood in likelihood. Other estimates are relabeled with fims_var_names.csv (e.g., "expected_recruitment" becomes "recruitment").

Value

A reformatted and standardized tibble of assessment model results for application in building stock assessment reports and to easily adapt results among regional assessments.

Author(s)

Samantha Bredeck

Examples

## Not run: 
convert_output(
  files = here::here("model1", "Report.sso"),
  models = "ss3",
  fleet_names = c("TWL", "NONTWL"),
  save_dir = here::here("standard_output.rda")
)
convert_output(
  files = list(
    "model1" = here::here("model1", "Report.sso"),
    "model2" = here::here("model2", "Report.sso")
  ),
  models = c("ss3", "ss3"),
  fleet_names = list(
    "model1" = c("TWL", "NONTWL"),
    "model2" = c("Fishery1", "Survey1", "Survey2")
  ),
  save_dir = here::here("standard_output.rda")
)

## End(Not run)

Create the rda package for a plot or table

Description

Create the rda package for a plot or table

Usage

create_latex_table(data, caption, label)

Arguments

data

Data frame. A dataframe-based table

caption

String. Table caption

label

String. Table label

Value

A table based in LaTeX.

Examples

create_latex_table(
  data = as.data.frame(head(mtcars, 6)),
  caption = "My caption",
  label = "My label"
)

Create the rda package for a plot or table

Description

Create the rda package for a plot or table

Usage

create_rda(
  object,
  topic_label,
  fig_or_table,
  dat,
  dir = getwd(),
  ref_line = "msy",
  scale_amount = 1,
  table_df = NULL
)

Arguments

object

Object. Table or plot object

topic_label

String. Name of the object

fig_or_table

String. Indicates whether the object is a "table" or "figure"

Options: "figure" or "table"

dat

Data frame. Data which will fill in captions and alternative text for the object

dir

Path. Directory to where the rda will be saved

Default: the working directory (getwd())

ref_line

String. Reference line value

Default: "msy"

Options: Including, but not limited to: "msy", "target", "unfished"

scale_amount

Number. A number describing how much to scale down the quantities shown on the y axis. For example, scale_amount = 100 would scale down a value from 500,000 –> 5,000. This scale will be reflected in the y axis label.

Default: 1

table_df

Data frame. The data frame that the table will be made into for purposes of exporting a latex formatted table.

Value

An rda package for a plot or table object. Requires an object from the R environment such as a ggplot or flextable object.

See Also

export_rda(), extract_caps_alttext()

Examples

## Not run: 
create_rda(
  object = my_plot,
  topic_label = "my_plot",
  fig_or_table = "figure",
  dat = my_data,
  dir = "path/to/save"
)

## End(Not run)

SS3 Example data

Description

Included data set that represents a Report.sso file converted using convert_output(). This example is from the 2022 Petrale sole stock assessment.

Usage

example_data

Format

A tibble (tbl_df, tbl, data.frame) with 591109 rows and 33 variables:

label

Standard name for estimate or value name

estimate

Actual value of the label

year

Annual indexing value

fleet

Names of fleets or surveys indexed by the data

sex

Native reference to male, female, unknown, or none

area

Specified areas by the model

growth_pattern

Indexing column of data

uncertainty

Value of uncertainty associated with the label column

uncertainty_label

Uncertainty label or name associated with the label columns

module_name

Name of keyword (SS3) or list indexing in the original model output for tracking purposes

time

Time sometimes referenced in decimals to the year and month

era

"time" for current time series in model; "fore" representing the projected or forecasted years of the model

month

Month factor

season

Season usually associated with year

subseason

Subseason when used

birthseas

Birthseason found in SS3

initial

Initial input value in the model when available associated with the label column

likelihood

Likelihood value for the data point

platoon

Platoon also an SS3 indexing value

age

Age of fish

bio_pattern

Indexing column of data

settlement

Indexing column of data

morph

Indexing column of data

type

Indexing column of data

factor

Indexing column of data

part

Indexing column of data

kind

Indexing column of data

nsim

Indexing column of data

bin

Indexing column of data

age_a

Alternative age column

length_bins

Length bins for composition or other length based data

count

Indexing column of data

block

Indexing column of data


Export updated key quantities template

Description

Export updated key quantities template

Usage

export_kqs(..., dir = getwd())

Arguments

...

Key quantities whose values should be added to the exported "key_quantities.csv"

dir

String directory to write "key_quantities.csv" to.

DEFAULT: getwd()

Value

Exports a file based on key quantities template, with values added next to the names of the key quantities specified as ellipsis arguments. File is saved as "key_quantities.csv" to the specified directory.

See Also

fill_in_kqs(), insert_kqs()

Examples

## Not run: 
export_kqs(
  F.min,
  F.max,
)

export_kqs(
  F.min,
  F.max,
  dir = fs::path(getwd(), "plots")
)

## End(Not run)

Export a figure or table to rda

Description

Export a figure/table, and its caption and alternative text, to an rda object. Typically used after stockplotr::extract_caps_alttext().

Usage

export_rda(
  object = NULL,
  caps_alttext = NULL,
  figures_tables_dir = NULL,
  topic_label = NULL,
  fig_or_table = NULL,
  latex_table = NULL
)

Arguments

object

Object. The final figure (ggplot) or table (flextable) object.

Default: NULL

caps_alttext

Data frame or list. The object containing a figure's caption and alternative text, in a list, or a table's caption, likely generated with stockplotr::extract_caps_alttext().

Default: NULL

figures_tables_dir

Path. If the user has already created folders containing figures and tables ("figures" and "tables"), figures_tables_dir represents the location of these folders. Otherwise, these two folders will be created automatically, then used to store the exported rda files.

Default: NULL

topic_label

String. Figure or table label. These labels are found in the "label" column of the "captions_alt_text.csv" file and are used to link the figure or table with its caption/alt text.

Default: NULL

fig_or_table

String. Indicates whether the plot is a figure or table.

Default: NULL

Options: "figure", "table"

latex_table

Table object. The object containing a LaTeX-based table.

Default: NULL

Value

An rda file with a figure's ggplot, caption, and alternative text, or a table's gt-based table, caption, and LaTeX-based table.

See Also

create_rda(), extract_caps_alttext()

Examples

## Not run: 
export_rda(
  final = final_table_object,
  caps_alttext = caps_alttext_object,
  figures_tables_dir = here::here(),
  topic_label = "biomass_abundance_catch",
  fig_or_table = "table",
  latex_table = "latex_table"
)

export_rda(
  final = final_figure_object,
  caps_alttext = another_caps_alttext_object,
  figures_tables_dir = "my_figures_tables_dir",
  topic_label = "landings",
  fig_or_table = "figure"
)

## End(Not run)

Extract captions and alternative texts

Description

Extract a figure or table's caption and alternative text for usage when generating a figure or table. Typically used before stockplotr::export_rda().

Usage

extract_caps_alttext(topic_label = NULL, fig_or_table = NULL, dir = getwd())

Arguments

topic_label

String. Figure or table label. These labels are found in the "label" column of the "captions_alt_text.csv" file and are used to link the figure or table with its caption/alt text.

Default: NULL

fig_or_table

String. Indicates whether the plot is a figure or table.

Default: NULL

dir

Path. The directory containing the "captions_alt_text.csv" file.

Default: the working directory (getwd())

Value

A figure's caption and alternative text, in a list, or a table's caption.

See Also

export_rda(), create_rda()

Examples

## Not run: 
extract_caps_alttext(
  topic_label = "biomass",
  fig_or_table = "figure",
  dir = here::here()
)

extract_caps_alttext(
  topic_label = "biomass_abundance_catch",
  fig_or_table = "table",
  dir = getwd()
)

## End(Not run)

Extract data from model results to send to SIS

Description

Semi-automate the extraction of key quantities from model results and time series data from exported figure/table .rda files for eventual transmittance to SIS via asar::export_to_sis().

Usage

extract_sis_data(
  sis_data_dir = getwd(),
  key_quantities_dir = getwd(),
  figures_tables_dir = getwd()
)

Arguments

sis_data_dir

Path. Location to save the sis_assmt_template.csv and sis_ts_template.csv files or, if present, the location of the existing sis_assmt_template.csv file.

Default: The working directory.

key_quantities_dir

Path. Location of the existing key_quantities.csv file.

Default: The working directory.

figures_tables_dir

Path. Location of the existing 'figures' and 'tables' directories.

Default: The working directory.

Details

See the "Automating data extraction for SIS" vignette for a detailed overview of the workflow and requirements for this function.

Examples

## Not run: 
extract_sis_data(
  sis_data_dir = getwd(),
  key_quantities_dir = "my_dir",
  figures_tables_dir = "my_other_dir"
)

## End(Not run)

Substitute key quantities' values into template

Description

Substitute key quantities' values into template

Usage

fill_in_kqs(df, ...)

Arguments

df

Data frame. Dataframe created by importing "key_quantity_template.csv" or "key_quantities.csv", empty or partially-filled templates with key quantity names and other associated information

...

Key quantity objects whose values will be added to the output dataframe

Details

The returned dataframe is input for fill_in_kqs().

Value

Dataframe based on key quantities template that contains newly-added values of key quantities indicated via ellipsis.

See Also

export_kqs(), insert_kqs()

Examples

## Not run: 
fill_in_kqs(
  df = data,
  F.min,
  F.max
)

## End(Not run)

Filter data for input into aesthetics for ggplot2

Description

Filter data for input into aesthetics for ggplot2

Usage

filter_data(
  dat,
  label_name,
  module = NULL,
  model = NULL,
  era = NULL,
  geom,
  group = NULL,
  facet = NULL,
  scale_amount = 1,
  interactive = TRUE,
  allow_multiple_models = TRUE
)

Arguments

dat

Data frame or list. A tibble or named list of tibbles (input as list()) returned from convert_output.

If inputting a list of tibbles, the first tibble's reference point defined in ref_line is used to plot a reference line or calculate relative spawning biomass.

label_name

String. Name of the label used to filter the data.

module

Character vector. (Optional) Module name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

model

Character vector. (Optional) Model name found in dat$model. If selecting >1 model, place them in a vector like c("model1", "model2").

Default: NULL

If the interactive and >1 model is found, user will select the model in the console. @seealso filter_data()

era

String. Era of data.

Default: "time"

Options: "early", "time", "fore" (forecast), or NULL (all data)

geom

String. Geom used for the plot.

Default: "line".

Options: "line", "point", or "area"

group

String. Single column that groups the data.

Set group = "none" to summarize data over all indexing values.

Default: NULL Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

facet

Character vector. Column name or names used for faceting.

Default: NULL

scale_amount

Number. A number to scale the y-axis values. If > 1, the magnitude of the scale amount will be added to the unit label (e.g. scale_amount = 1000 with a unit label of "1000s of lbs" will result in "thousands of 1000s of lbs")

Default: 1

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

allow_multiple_models

Logical. Whether to allow multiple models.

Default: TRUE

Value

a data frame that is preformatted for plotting with ggplot2.

Examples

## Not run: 
filter_data(dat, "biomass", "line", group = "fleet")
filter_data(
  dat,
  label = "biomass",
  geom = "line",
  module = "derived_quants",
  model = NULL,
  allow_multiple_models = FALSE # can only select one model to filter by
)

## End(Not run)

Filter plot data interactively

Description

Allows user to interactively select values from those available to filter their data by.

Usage

filter_interactive(
  dat,
  column_name,
  column_value = NULL,
  interactive = TRUE,
  allow_multiple_selection = TRUE
)

Arguments

dat

data.frame. A tibble or named list of tibbles (input as list()) returned from convert_output.

column_name

String. Name of the column to allow interactive filtering for.

column_value

String. Value of the column to filter by. If NULL, interactive selection will be enabled.

Default: NULL

interactive

Logical. indicate whether the environment is interactive.

Default: TRUE

allow_multiple_selection

Logical. Whether to allow the selection of multiple inputs.

Default: FALSE

Value

List. filtered data.frame (plot_data) and selected option(selected).

Examples

## Not run: 
filter_interactive(
  dat = example_dat,
  column_name = "model",
  column_value = NULL,
  allow_multiple_selection = TRUE # allow selecting multiple models
)

## End(Not run)

Insert key quantities into the captions and alternative text file

Description

Insert key quantities into the captions and alternative text file

Usage

insert_kqs(..., dir = getwd())

Arguments

...

Key quantities whose values should be added to the exported "captions_alt_text.csv"

dir

String directory to write "captions_alt_text.csv" to.

DEFAULT: getwd()

Value

Exports a file ("captions_alt_text.csv") containing captions and alternative text for figures and tables, with key quantities inserted into the "captions_alt_text_template.csv" template's placeholders.

See Also

fill_in_kqs(), export_kqs()

Examples

## Not run: 
insert_kqs(
  F.min,
  F.max
)

## End(Not run)

Rename columns and merge estimate and uncertainty columns for table presentation

Description

Rename columns and merge estimate and uncertainty columns for table presentation

Usage

merge_error(table_data, id_col_vals, unit_label, uncert_lab)

Arguments

table_data

List of dataframes that will be eventually turned into tables

id_col_vals

List. A list of variables identifying grouping of the data and their unique values.

unit_label

String. The units of the estimate being presented in the table.

uncert_lab

String. Uncertainty label. Typically inherited from another function but is the exact string of the uncertainty in the data (e.g., "sd", "se", "cv", "uncertainty").)

Value

List of formatted dataframes that contain column names formatted for a table along with a merge of values in the estimate and error columns to reduce redundancy in the table.


Create "at-age" plot

Description

Create "at-age" plot

Usage

plot_aa(
  dat,
  x = "year",
  y = "age",
  z = "estimate",
  label = "Abundance",
  xlab = "Year",
  ylab = "Age",
  facet = NULL,
  proportional = TRUE,
  ...
)

Arguments

dat

Data frame. Filtered data frame from standard output file(s) preformatted for the target label from filter_data

x

String. Column name of data used to plot on the x-axis

Default: "year"

y

String. Column name of data used to plot on the y-axis

Default: "age"

z

String. Column name of data used to control the size of the bubbles

Default: "estimate"

label

String. Label for the size of the bubbles

Default: "Abundance"

xlab

String. X-axis label

Default: "Year"

ylab

String. Y-axis label

Default: "Age"

facet

Character vector. Column name or names used for faceting. It is not recommended to include more than one facet due to the complexity of the plot.

Default: NULL

Options: Including, but not limited to: "sex", "area", "fleet"

proportional

Logical. TRUE/FALSE; set size of points relative to z when TRUE, point size are relative to one another while when set to FALSE, point size is relative to z

Default: TRUE

...

Inherited arguments from internal functions from geom_point

Value

Create a plot of abundance at age for a stock assessment report.

Examples

## Not run: 
plot_aa(dat)

## End(Not run)

Plot Abundance at Age

Description

Plot Abundance at Age

Usage

plot_abundance_at_age(
  dat,
  facet = NULL,
  unit_label = NULL,
  scale_amount = 1,
  proportional = TRUE,
  module = NULL,
  model = NULL,
  interactive = TRUE,
  make_rda = FALSE,
  figures_dir = getwd()
)

Arguments

dat

Data frame. A data frame returned from convert_output

facet

Character vector. Column name or names used for faceting. Set facet = "none" to summarize the data in a single plot.

Default: NULL

Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

unit_label

String. Abundance units

Default: NULL

scale_amount

Number. A number describing how much to scale down the abundance at age. Please choose a value ranging from 1-1,000,000,000 (one billion) in orders of magnitude (e.g., 1, 10, 100, 1000, etc.). For example, scale_amount = 100 would scale down a value from 500,000 –> 5,000 and would report abundance in hundreds of fish (if "fish" was the unit_label). This scale will be reflected in the legend label if proportional is set to FALSE.

Default: 1,000

proportional

Logical. TRUE/FALSE; set size of points relative to z when TRUE, point size are relative to one another while when set to FALSE, point size is relative to z

Default: TRUE

module

(Optional) A string indicating the module_name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

model

Character vector. (Optional) Model name found in dat$model. If selecting >1 model, place them in a vector like c("model1", "model2").

Default: NULL

If the interactive and >1 model is found, user will select the model in the console. @seealso filter_data()

interactive

A logical value indicating if the environment is interactive.

Default: FALSE

make_rda

Logical. TRUE/FALSE; indicate whether to produce an .rda file containing a list with the figure/table, caption, and alternative text (if figure). If TRUE, the .rda will be exported to the folder indicated in the argument "rda_dir".

Default: FALSE

figures_dir

Path. Folder containing the generated .rda files ("rda_files") that will be created if the argument make_rda = TRUE.

Default: the working directory (getwd())

Details

The input is from an assessment model output file translated to a standardized output (convert_output). There are options to return a ggplot2 object or export an .rda object containing associated caption and alternative text for the figure.

Value

A plot showing total abundance (or numbers) at age.

See Also

convert_output(), filter_data(), process_data(), plot_aa(), export_kqs(), insert_kqs(), create_rda()

Examples

plot_abundance_at_age(
  dat = stockplotr::example_data,
  facet = "growth_pattern",
  unit_label = "fish",
  scale_amount = 1000,
  proportional = TRUE
)
plot_abundance_at_age(
  dat = stockplotr::example_data,
  facet = "none",
  proportional = FALSE
)

Plot Total Biomass

Description

Plot Total Biomass

Usage

plot_biomass(
  dat,
  geom = "line",
  group = NULL,
  facet = NULL,
  ref_line = "msy",
  era = NULL,
  unit_label = NULL,
  module = NULL,
  model = NULL,
  scale_amount = 1,
  relative = FALSE,
  make_rda = FALSE,
  figures_dir = getwd(),
  interactive = TRUE,
  ...
)

Arguments

dat

Data frame or list. A tibble or named list of tibbles (input as list()) returned from convert_output.

If inputting a list of tibbles, the first tibble's reference point defined in ref_line is used to plot a reference line or calculate relative spawning biomass.

geom

String. Geom used for the plot.

Default: "line".

Options: "line", "point", or "area"

group

String. Single column that groups the data.

Set group = "none" to summarize data over all indexing values.

Default: NULL Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

facet

Character vector. Column name or names used for faceting.

Default: NULL

ref_line

String. Type of reference point to compare biomass to. The default "msy" looks for "biomass_msy" in the "label" column of dat. The actual searching in dat is case-agnostic and will work with either upper- or lower-case letters. However, you must use one of the options specified in the default list to ensure that the label on the figure looks correct regardless of how it is specified in dat.

Default: "msy"

Options: Including, but not limited to: "target", "MSY", "unfished"

era

String. Era of data.

Default: "time"

Options: "early", "time", "fore" (forecast), or NULL (all data)

unit_label

String. Biomass units

Default: NULL

module

Character vector. (Optional) Module name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

model

Character vector. (Optional) Model name found in dat$model. If selecting >1 model, place them in a vector like c("model1", "model2").

Default: NULL

If the interactive and >1 model is found, user will select the model in the console. @seealso filter_data()

scale_amount

Number. A number to scale the y-axis values. If > 1, the magnitude of the scale amount will be added to the unit label (e.g. scale_amount = 1000 with a unit label of "1000s of lbs" will result in "thousands of 1000s of lbs")

Default: 1

relative

Logical. TRUE/FALSE; specify whether to set y-axis values relative to the ref_line value.

Default: FALSE

make_rda

Logical. TRUE/FALSE; indicate whether to save the object and make an automated caption and alternative text in the form of an rda object. If TRUE, the rda will be exported to the folder indicated in the argument "figures_dir".

Default: FALSE.

figures_dir

Path. Path to the "figures" folder.

Default: getwd()

The folder is created within the path if it does not exist.

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

...

Arguments called from geom_line or geom_point

Details

The input is from an assessment model output file translated to a standardized output (convert_output). There are options to return a ggplot2 object or export an .rda object containing associated caption and alternative text for the figure.

Value

A plot showing total biomass.

See Also

convert_output(), plot_timeseries(), calculate_reference_point(), reference_line(), filter_data(), process_data(), export_kqs(), insert_kqs(), create_rda()

Examples

plot_biomass(
  dat = stockplotr::example_data,
  unit_label = "mt",
  ref_line = c("target" = 20000),
  scale_amount = 100,
  module = "TIME_SERIES",
  figures_dir = getwd()
)
plot_biomass(
  dat = stockplotr::example_data,
  ref_line = NULL,
  module = "TIME_SERIES",
  figures_dir = getwd()
)

Plot Total Biomass at Age (BAA)

Description

Plot Total Biomass at Age (BAA)

Usage

plot_biomass_at_age(
  dat,
  facet = NULL,
  unit_label = NULL,
  scale_amount = 1,
  proportional = TRUE,
  module = NULL,
  model = NULL,
  interactive = TRUE,
  make_rda = FALSE,
  figures_dir = getwd()
)

Arguments

dat

Data frame. A data frame returned from convert_output

facet

Character vector. Column name or names used for faceting. Set facet = "none" to summarize the data in a single plot.

Default: NULL

Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

unit_label

String. Abundance units

Default: NULL

scale_amount

Number. A number describing how much to scale down the biomass at age. For example, scale_amount = 100 would scale down a value from 500,000 –> 5,000. This scale will be reflected in the legend label if proportion is set to FALSE.

Default: 1,000

proportional

Logical. TRUE/FALSE; set size of points relative to z when TRUE, point size are relative to one another while when set to FALSE, point size is relative to z

Default: TRUE

module

(Optional) A string indicating the module_name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

model

Character vector. (Optional) Model name found in dat$model. If selecting >1 model, place them in a vector like c("model1", "model2").

Default: NULL

If the interactive and >1 model is found, user will select the model in the console. @seealso filter_data()

interactive

Logical. TRUE/FALSE; indicate whether the environment in which the function is operating is interactive. This bypasses some options for filtering when preparing data for the plot.

Default: TRUE

make_rda

Logical. TRUE/FALSE; indicate whether to produce an .rda file containing a list with the figure/table, caption, and alternative text (if figure). If TRUE, the .rda will be exported to the folder indicated in the argument "rda_dir".

Default: FALSE

figures_dir

Path. Folder containing the generated .rda files ("rda_files") that will be created if the argument make_rda = TRUE.

Default: the working directory (getwd())

Details

The input is from an assessment model output file translated to a standardized output (convert_output). There are options to return a ggplot2 object or export an .rda object containing associated caption and alternative text for the figure.

Value

A plot showing total biomass at age.

See Also

convert_output(), filter_data(), process_data(), plot_aa(), export_kqs(), insert_kqs(), create_rda()

Examples

plot_biomass_at_age(
  dat = stockplotr::example_data,
  unit_label = "mt",
  scale_amount = 100,
  proportional = FALSE, # displays legend
  make_rda = FALSE
)
plot_biomass_at_age(
  dat = stockplotr::example_data,
  unit_label = "mt",
  facet = "none",
  proportional = FALSE
)

Plot catch-at-age

Description

Plot catch-at-age

Usage

plot_catch_at_age(
  dat,
  facet = NULL,
  era = "time",
  unit_label = NULL,
  scale_amount = 1,
  proportional = TRUE,
  interactive = TRUE,
  module = NULL,
  model = NULL,
  make_rda = FALSE,
  figures_dir = getwd()
)

Arguments

dat

Data frame. A data frame returned from convert_output

facet

Character vector. Column name or names used for faceting. Set facet = "none" to summarize the data in a single plot.

Default: NULL

Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

era

String. Era of data.

Default: "time"

Options: "early", "time", "fore" (forecast), or NULL (all data)

unit_label

String. Units of catch used to label the axis

Default: NULL

scale_amount

Number. A number describing how much to scale down the catch at age. Please choose a value ranging from 1-1,000,000,000 (one billion) in orders of magnitude (e.g., 1, 10, 100, 1000, etc.). For example, scale_amount = 100 would scale down a value from 500,000 –> 5,000 and would report catch in hundreds of the 'unit_label'. This scale will be reflected in the legend label if proportional is set to FALSE.

Default: 1

proportional

Logical. TRUE/FALSE; set size of points relative to z when TRUE, point size are relative to one another while when set to FALSE, point size is relative to z

Default: TRUE

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

module

Character vector. (Optional) Module name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

model

Character vector. (Optional) Model name found in dat$model. If selecting >1 model, place them in a vector like c("model1", "model2").

Default: NULL

If the interactive and >1 model is found, user will select the model in the console. @seealso filter_data()

make_rda

Logical. TRUE/FALSE; indicate whether to produce an .rda file containing a list with the figure/table, caption, and alternative text (if figure). If TRUE, the .rda will be exported to the folder indicated in the argument "rda_dir".

Default: FALSE

figures_dir

Path. Folder containing the generated .rda files ("rda_files") that will be created if the argument make_rda = TRUE.

Default: the working directory (getwd())

Details

This plot is made only when catch or landings are explicitly named in the output file. The current plot function does not combine all sources of catch. The input is from an assessment model output file translated to a standardized output (convert_output). There are options to return a ggplot2 object or export an .rda object containing associated caption and alternative text for the figure.

Value

A plot showing catch or landings at age

See Also

convert_output(), filter_data(), process_data(), plot_aa(), export_kqs(), insert_kqs(), create_rda()

Examples

plot_catch_at_age(
  dat = stockplotr::example_data,
  facet = "fleet",
  unit_label = "fish",
  scale_amount = 100,
  interactive = FALSE,
  make_rda = FALSE,
  figures_dir = getwd()
)

plot_catch_at_age(
  dat = stockplotr::example_data,
  facet = "none",
  unit_label = "mt",
  scale_amount = 100,
  interactive = FALSE,
  era = "fore",
  proportional = FALSE
)

Plot Andre Punt's mean age at length for conditional age-at-length data

Description

For conditional age-at-length data, plot the observed and expected mean age in each length bin, and the standard error of the mean age, for each year. These are "Andre's plots" from r4ss::SSplotComps() (subplot 12).

Usage

plot_composition_andre(
  dat,
  interval = 0.9,
  flip = FALSE,
  fleet = NULL,
  ncol = NULL
)

Arguments

dat

A tibble returned from convert_output() that contains conditional age-at-length data (see bigskate_caal), or conditional data in any other format accepted by prepare_composition_data() with conditional = TRUE.

interval

Number. Coverage of the intervals around the observed values. Default: 0.90, corresponding to 90% intervals

flip

Logical. TRUE/FALSE; put age (the mean age or its standard error) on the horizontal axis and length on the vertical axis, as in a growth curve. The default (FALSE) puts length on the horizontal axis, as in r4ss.

fleet

Character or numeric vector. Fleet(s) to keep, matching either the fleet name (e.g., "Fishery_current") or the fleet name with its partition (e.g., "Fishery_current (retained)"). NULL keeps all fleets. Default: NULL

ncol

Number. Number of facet columns. NULL lets ggplot2 choose. Default: NULL

Details

Within each year and length bin, the observed and expected mean ages are ∑aa oa\sum_a a\, o_a and ∑aa ea\sum_a a\, e_a, and the standard errors are the corresponding standard deviations of age divided by N\sqrt{N}, where NN is the number of fish aged in the length bin. Following r4ss, the interval for the mean is the observed mean plus or minus the normal quantile times the observed standard error, and the interval for the standard error is based on the chi-square distribution. Observed values outside the intervals, or expected values that consistently differ from the observed values, suggest mis-specified growth or variability in length at age.

The statistics are calculated separately for each sex. Unlike r4ss, which combines sexes, this avoids jumps in the expected values when the ratio of sample sizes varies between sexes. Length bins with no observations or no sample size are omitted. Plot one fleet at a time with fleet, and subset years by filtering dat.

Value

A ggplot2 object with one row of panels per year (and per sex and fleet when there is more than one): mean age at length on the left and standard error of the mean age on the right.

Equivalent plots in other packages

r4ss: r4ss::SSplotComps() subplot 12 (Andre's plots of mean age and standard deviation for conditional age-at-length data).

See Also

prepare_composition_data(), plot_composition_bubble()

Examples

plot_composition_andre(
  dplyr::filter(bigskate_caal, year %in% 2016:2018),
  fleet = "WCGBTS"
)

# Age on the horizontal axis
plot_composition_andre(
  dplyr::filter(bigskate_caal, year %in% 2016:2018),
  fleet = "WCGBTS",
  flip = TRUE
)

Plot composition bubble plots

Description

Bubble plot of compositions by year (x-axis) and bin (y-axis). Bubbles can show the observed (or expected) proportions, which makes strong and weak cohorts easy to follow through time, or the Pearson residuals, which show blocks or stripes of misfit among years or bins.

Usage

plot_composition_bubble(
  dat,
  value = c("observed", "pearson", "expected"),
  comp_type = NULL,
  fleet = NULL,
  max_size = 6,
  ncol = NULL,
  direction = "v",
  conditional = FALSE
)

Arguments

dat

A tibble returned from convert_output() that contains composition data (see bigskate_lencomp), or composition data in any other format accepted by prepare_composition_data().

value

String. Value to plot. Options: "observed", "expected", or "pearson". Default: "observed"

comp_type

String. Type of composition to keep when dat contains more than one. Options: "age", "length", or NULL (keep all). Default: NULL

fleet

Character or numeric vector. Fleet(s) to keep, matching either the fleet name (e.g., "Fishery_current") or the fleet name with its partition (e.g., "Fishery_current (retained)"). NULL keeps all fleets. Default: NULL

max_size

Number. Size of the largest bubble. Default: 6

ncol

Number. Number of facet columns. NULL lets ggplot2 choose. Default: NULL

direction

String. Order of the panels: "v" fills panels down each column and then across, so consecutive years are stacked vertically and cohorts are easier to follow from panel to panel; "h" fills panels across each row.

Default: "v"

conditional

Logical. TRUE/FALSE; plot conditional age-at-length data (see prepare_composition_data()), with age on the y-axis, length bin on the x-axis, and one panel per year. Default: FALSE

Details

Panels are created for each fleet, and for each sex when compositions are sex-specific. For Pearson residuals, filled bubbles are positive residuals (observed > expected) and open bubbles are negative residuals (observed < expected), with bubble area proportional to the absolute value of the residual. The maximum absolute residual for each panel is included in the panel label.

Value

A ggplot2 object.

Equivalent plots in other packages

r4ss: r4ss::SSplotComps() subplot 2 (bubble plot of observations or residuals) and subplot 3 (conditional age-at-length).

See Also

prepare_composition_data(), plot_composition_residuals(), plot_composition_distribution()

Examples

# Observed proportions
plot_composition_bubble(bigskate_lencomp)

# Pearson residuals
plot_composition_bubble(bigskate_lencomp, value = "pearson")

# Residuals for conditional age-at-length data
plot_composition_bubble(
  dplyr::filter(bigskate_caal, year %in% 2016:2018),
  value = "pearson",
  fleet = "WCGBTS",
  conditional = TRUE
)

Plot composition distributions

Description

Plot age or length compositions as distributions (proportion by bin), one panel per year, optionally overlaying the model-expected values. Setting aggregate = TRUE instead sums the compositions across years so that each fleet is summarized in a single panel.

Usage

plot_composition_distribution(
  dat,
  show_expected = TRUE,
  aggregate = FALSE,
  comp_type = NULL,
  fleet = NULL,
  ncol = NULL,
  direction = "v"
)

Arguments

dat

A tibble returned from convert_output() that contains composition data (see bigskate_lencomp), or composition data in any other format accepted by prepare_composition_data().

show_expected

Logical. TRUE/FALSE; overlay the expected values as lines. Ignored if dat contains no expected values. Default: TRUE

aggregate

Logical. TRUE/FALSE; aggregate compositions across years within each fleet. Years are weighted by their sample size when sample sizes are available. Default: FALSE

comp_type

String. Type of composition to keep when dat contains more than one. Options: "age", "length", or NULL (keep all). Default: NULL

fleet

Character or numeric vector. Fleet(s) to keep, matching either the fleet name (e.g., "Fishery_current") or the fleet name with its partition (e.g., "Fishery_current (retained)"). NULL keeps all fleets. Default: NULL

ncol

Number. Number of facet columns. NULL lets ggplot2 choose. Default: NULL

direction

String. Order of the panels: "v" fills panels down each column and then across, so consecutive years are stacked vertically and cohorts are easier to follow from panel to panel; "h" fills panels across each row.

Default: "v"

Details

When compositions are sex-specific (both "female" and "male" values in the sex column), females are plotted above zero and males below zero. Bars show observed proportions and lines show expected proportions. Females and males are colored with the two ends of viridis::viridis(2, option = "viridis", end = 0.75) ("#440154" and "#5DC863"); add ggplot2::scale_fill_manual() and ggplot2::scale_color_manual() to the returned plot to use other colors.

If more than one fleet is plotted without aggregating, panels are created for every fleet and year combination; use fleet to focus on one fleet at a time.

Value

A ggplot2 object.

Equivalent plots in other packages

r4ss: r4ss::SSplotComps() subplot 1 (by year) and subplot 21 (aggregated across years).

See Also

prepare_composition_data(), plot_composition_bubble(), plot_composition_residuals(), plot_composition_sexratio(), plot_composition_francis()

Examples

# Observations only
plot_composition_distribution(bigskate_lencomp, fleet = "WCGBTS", show_expected = FALSE)

# Observed and expected
plot_composition_distribution(bigskate_lencomp, fleet = "Triennial")

# All fleets aggregated across years
plot_composition_distribution(bigskate_lencomp, aggregate = TRUE)

Plot mean age or length with Francis (method 8 in Table A1, TA1.8) data weights

Description

Time series of the mean age or length in the observed and expected compositions. Developed as a diagnostic for the Francis (2011) data weighting method (TA1.8), the plot is also a useful summary of trends in compositions and lack of fit among years.

Usage

plot_composition_francis(
  dat,
  interval = 0.95,
  show_francis = TRUE,
  comp_type = NULL,
  fleet = NULL,
  ncol = NULL,
  direction = "v"
)

Arguments

dat

A tibble returned from convert_output() that contains composition data (see bigskate_lencomp), or composition data in any other format accepted by prepare_composition_data().

interval

Number. Coverage of the interval around the observed mean. Default: 0.95

show_francis

Logical. TRUE/FALSE; add the Francis TA1.8 weight for each fleet to the panel label and show thinner, capped intervals representing sample sizes after applying that weight. Default: TRUE

comp_type

String. Type of composition to keep when dat contains more than one. Options: "age", "length", or NULL (keep all). Default: NULL

fleet

Character or numeric vector. Fleet(s) to keep, matching either the fleet name (e.g., "Fishery_current") or the fleet name with its partition (e.g., "Fishery_current (retained)"). NULL keeps all fleets. Default: NULL

ncol

Number. Number of facet columns. NULL lets ggplot2 choose. Default: NULL

direction

String. Order of the panels: "v" fills panels down each column and then across, so consecutive years are stacked vertically and cohorts are easier to follow from panel to panel; "h" fills panels across each row.

Default: "v"

Details

For each year and fleet (with sexes combined), the observed mean is xˉo=∑bxbob\bar{x}_o = \sum_b x_b o_b and the expected mean is xˉe=∑bxbeb\bar{x}_e = \sum_b x_b e_b, where xbx_b is the bin and obo_b and ebe_b are the observed and expected proportions. Assuming a multinomial distribution, the standard error of the mean is ve/N\sqrt{v_e / N}, where ve=∑bxb2eb−xˉe2v_e = \sum_b x_b^2 e_b - \bar{x}_e^2 is the variance of the expected composition and NN is the sample size. Intervals are drawn around the observed means.

The Francis weight is 1/var(r)1 / \mathrm{var}(r) where r=(xˉo−xˉe)/SEr = (\bar{x}_o - \bar{x}_e) / SE are the standardized residuals of the mean across years. As in Stock Synthesis and r4ss::SSMethod.TA1.8(), all partitions of a fleet (e.g., retained and discarded) share one weight, and its 95% interval is calculated by bootstrapping the standardized residuals (1000 resamples), so use set.seed() for reproducible intervals. The weight assumes a multinomial likelihood and has not been adapted for Dirichlet-multinomial or other likelihoods.

Without expected values, only the observed means are plotted. Without sample sizes, no intervals or weights are shown.

Value

A ggplot2 object.

Equivalent plots in other packages

r4ss: r4ss::SSplotComps() subplots 8 and 9, which use r4ss::SSMethod.TA1.8().

References

Francis, R.I.C.C. (2011). Data weighting in statistical fisheries stock assessment models. Canadian Journal of Fisheries and Aquatic Sciences 68: 1124-1138.

See Also

prepare_composition_data(), plot_composition_distribution()

Examples

plot_composition_francis(bigskate_lencomp)

Plot the distribution of composition residuals

Description

Quantile-quantile plot or histogram of Pearson residuals for each fleet, to check for heavy tails, skewness, and outliers.

Usage

plot_composition_residual_distribution(
  dat,
  type = c("qq", "histogram"),
  comp_type = NULL,
  fleet = NULL,
  ncol = NULL,
  direction = "v"
)

Arguments

dat

A tibble returned from convert_output() that contains composition data (see bigskate_lencomp), or composition data in any other format accepted by prepare_composition_data().

type

String. Type of plot. Options: "qq" (normal quantile-quantile plot) or "histogram" (with a standard normal density overlaid). Default: "qq"

comp_type

String. Type of composition to keep when dat contains more than one. Options: "age", "length", or NULL (keep all). Default: NULL

fleet

Character or numeric vector. Fleet(s) to keep, matching either the fleet name (e.g., "Fishery_current") or the fleet name with its partition (e.g., "Fishery_current (retained)"). NULL keeps all fleets. Default: NULL

ncol

Number. Number of facet columns. NULL lets ggplot2 choose. Default: NULL

direction

String. Order of the panels: "v" fills panels down each column and then across, so consecutive years are stacked vertically and cohorts are easier to follow from panel to panel; "h" fills panels across each row.

Default: "v"

Details

The standard deviation of the normalized residuals (SDNR) for each fleet is included in the panel label. Values well above one suggest that the compositions are given more weight (larger sample sizes) than the fit supports. Pearson residuals for compositions are not expected to be exactly normally distributed, especially for bins with small expected proportions or small sample sizes, so treat departures in the tails with some caution.

Value

A ggplot2 object.

See Also

plot_composition_residuals(), plot_composition_residual_pattern(), prepare_composition_data()

Examples

plot_composition_residual_distribution(bigskate_lencomp)
plot_composition_residual_distribution(bigskate_lencomp, type = "histogram")

Plot patterns in composition residuals by bin or year

Description

Plot the mean Pearson residual for each bin (across years) or each year (across bins), with a runs test for non-random patterns in the signs of the residuals. These plots summarize the stripes that can appear in residual bubble plots, for example, consistently negative residuals at older ages caused by mis-specified selectivity.

Usage

plot_composition_residual_pattern(
  dat,
  by = c("bin", "year"),
  comp_type = NULL,
  fleet = NULL,
  ncol = NULL,
  direction = "v"
)

Arguments

dat

A tibble returned from convert_output() that contains composition data (see bigskate_lencomp), or composition data in any other format accepted by prepare_composition_data().

by

String. Summarize residuals by "bin" (age or length) or by "year". Default: "bin"

comp_type

String. Type of composition to keep when dat contains more than one. Options: "age", "length", or NULL (keep all). Default: NULL

fleet

Character or numeric vector. Fleet(s) to keep, matching either the fleet name (e.g., "Fishery_current") or the fleet name with its partition (e.g., "Fishery_current (retained)"). NULL keeps all fleets. Default: NULL

ncol

Number. Number of facet columns. NULL lets ggplot2 choose. Default: NULL

direction

String. Order of the panels: "v" fills panels down each column and then across, so consecutive years are stacked vertically and cohorts are easier to follow from panel to panel; "h" fills panels across each row.

Default: "v"

Details

Vertical lines are plus and minus two standard errors of the mean residual. The runs test (Wald-Wolfowitz) is applied to the signs of the residuals ordered by year (when by = "bin") or by bin (when by = "year"). Filled points have fewer runs than expected by chance (one-sided p < 0.05), which indicates a non-random pattern of residuals. When all residuals have the same sign, the p-value is the probability of that happening by chance, 2×0.5n2 \times 0.5^n. Residuals are summarized separately for each fleet and sex.

Value

A ggplot2 object.

See Also

plot_composition_residuals(), plot_composition_residual_distribution(), prepare_composition_data()

Examples

plot_composition_residual_pattern(bigskate_lencomp)
plot_composition_residual_pattern(bigskate_lencomp, by = "year")

Plot composition Pearson residuals

Description

A convenience wrapper around plot_composition_bubble() with value = "pearson". Residuals are taken from dat when supplied or calculated by prepare_composition_data() assuming a multinomial distribution.

Usage

plot_composition_residuals(dat, ...)

Arguments

dat

A tibble returned from convert_output() that contains composition data (see bigskate_lencomp), or composition data in any other format accepted by prepare_composition_data().

...

Additional arguments passed to plot_composition_bubble().

Value

A ggplot2 object.

Equivalent plots in other packages

r4ss: r4ss::SSplotComps() subplot 2 for residuals by fleet and subplot 24 (residuals compared across fleets).

See Also

plot_composition_bubble(), prepare_composition_data()

Examples

plot_composition_residuals(bigskate_lencomp)

# Compare residuals across fleets for females
plot_composition_residuals(
  dplyr::filter(bigskate_lencomp, sex == "female"),
  ncol = 1
)

Plot input versus effective sample size of compositions

Description

Compare the input (or adjusted input) sample size of each composition with its effective sample size, the sample size implied by how well the model fits the composition. This is the diagnostic behind the McAllister and Ianelli (1997) data weighting method.

Usage

plot_composition_samples(
  dat,
  comp_type = NULL,
  fleet = NULL,
  show_years = FALSE,
  ncol = NULL,
  direction = "v"
)

Arguments

dat

A tibble returned from convert_output() that contains composition data (see bigskate_lencomp), or composition data in any other format accepted by prepare_composition_data(). For Stock Synthesis output converted from a Report.sso file without compositions by bin, the adjusted input (nsamp_adj) and effective (effn) sample sizes in the FIT_LEN_COMPS and FIT_AGE_COMPS tables are used instead (as in stockplotr::example_data).

comp_type

String. Type of composition to keep when dat contains more than one. Options: "age", "length", or NULL (keep all). Default: NULL

fleet

Character or numeric vector. Fleet(s) to keep, matching either the fleet name (e.g., "Fishery_current") or the fleet name with its partition (e.g., "Fishery_current (retained)"). NULL keeps all fleets. Default: NULL

show_years

Logical. TRUE/FALSE; label each point with its year. Default: FALSE

ncol

Number. Number of facet columns. NULL lets ggplot2 choose. Default: NULL

direction

String. Order of the panels: "v" fills panels down each column and then across, so consecutive years are stacked vertically and cohorts are easier to follow from panel to panel; "h" fills panels across each row.

Default: "v"

Details

For each composition (year and fleet), the effective sample size is

Neff=∑beb(1−eb)/∑b(ob−eb)2N_{eff} = \sum_b e_b (1 - e_b) / \sum_b (o_b - e_b)^2

where obo_b and ebe_b are the observed and expected proportions in bin bb (McAllister and Ianelli 1997), the same calculation used by Stock Synthesis.

Each panel shows a 1:1 line, a loess smoother (dashed red, when there are more than six distinct input sample sizes), the arithmetic mean of the input sample sizes (vertical dashed line), and the harmonic mean of the effective sample sizes (horizontal dashed line). The ratio of the harmonic mean effective sample size to the mean input sample size, the McAllister-Ianelli weight, is included in each panel label. Ratios below one suggest that input sample sizes are too large relative to the fit. As in Stock Synthesis, the weight is calculated across all partitions of a fleet; multiplying it by the current variance adjustment gives the Recommend_var_adj reported by Stock Synthesis.

Effective sample sizes from this formula are not appropriate for compositions fit with a Dirichlet-multinomial likelihood.

Value

A ggplot2 object.

Equivalent plots in other packages

r4ss: r4ss::SSplotComps() subplot 7 ("N-EffN comparison").

References

McAllister, M.K., and Ianelli, J.N. (1997). Bayesian stock assessment using catch-age data and the sampling-importance resampling algorithm. Canadian Journal of Fisheries and Aquatic Sciences 54: 284-300.

See Also

prepare_composition_data(), plot_composition_francis()

Examples

plot_composition_samples(bigskate_lencomp)

# Stock Synthesis output converted with convert_output()
plot_composition_samples(stockplotr::example_data, comp_type = "length")

Plot sex ratios implied by composition data

Description

Plot the proportion female, female / (female + male), by bin for the observed and expected compositions. Trends in the lack of fit to sex ratios can be easier to see here than in residuals, especially for bins with small proportions.

Usage

plot_composition_sexratio(
  dat,
  aggregate = FALSE,
  interval = 0.75,
  comp_type = NULL,
  fleet = NULL,
  ncol = NULL,
  direction = "v"
)

Arguments

dat

A tibble returned from convert_output() that contains composition data (see bigskate_lencomp), or composition data in any other format accepted by prepare_composition_data().

aggregate

Logical. TRUE/FALSE; aggregate compositions across years within each fleet. Years are weighted by their sample size when sample sizes are available. Default: FALSE

interval

Number. Coverage of the interval around the observed sex ratio, calculated as a Jeffreys interval using the sample size in each bin (the sample size multiplied by the proportion of the composition in the bin). Set to NULL to omit intervals. Intervals are only shown when sample sizes are available. Default: 0.75

comp_type

String. Type of composition to keep when dat contains more than one. Options: "age", "length", or NULL (keep all). Default: NULL

fleet

Character or numeric vector. Fleet(s) to keep, matching either the fleet name (e.g., "Fishery_current") or the fleet name with its partition (e.g., "Fishery_current (retained)"). NULL keeps all fleets. Default: NULL

ncol

Number. Number of facet columns. NULL lets ggplot2 choose. Default: NULL

direction

String. Order of the panels: "v" fills panels down each column and then across, so consecutive years are stacked vertically and cohorts are easier to follow from panel to panel; "h" fills panels across each row.

Default: "v"

Details

Requires sex-specific compositions with both "female" and "male" values in the sex column of dat. Points show observed ratios and lines show expected ratios. As in r4ss, the smallest observed proportion in each composition (such as the small constant Stock Synthesis adds to every bin) is subtracted from the observed and expected values first, so bins with no fish observed are omitted. When aggregate = TRUE, female and male compositions are summed across years (weighted by sample size when available) before calculating ratios.

Value

A ggplot2 object.

Equivalent plots in other packages

r4ss: r4ss::SSplotSexRatio() with sexratio.option = 2 (female:total).

See Also

prepare_composition_data(), plot_composition_distribution()

Examples

plot_composition_sexratio(bigskate_lencomp, fleet = "WCGBTS")
plot_composition_sexratio(bigskate_lencomp, aggregate = TRUE)

Plot the data available to an assessment model

Description

Plot the years in which each fleet has each type of data (landings, discards, indices of abundance, and age and length compositions), as in r4ss (SSplotData()), stockassessment (dataplot()), and spict (plotspict.data()). Each type of data is a panel, each fleet a row, and each year with data a square. It works with output from any model converted with convert_output() and with input data for a FIMS model (a FIMSFrame or the data from FIMS::get_data()).

Usage

plot_data_availability(
  dat,
  interactive = TRUE,
  make_rda = FALSE,
  figures_dir = getwd()
)

Arguments

dat

A tibble from convert_output(), a FIMSFrame, or a data frame of FIMS input data (FIMS::get_data()), with columns type, fleet, timing, and observed.

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

make_rda

Logical. TRUE/FALSE; indicate whether to save the object and make an automated caption and alternative text in the form of an rda object. If TRUE, the rda will be exported to the folder indicated in the argument "figures_dir".

Default: FALSE.

figures_dir

Path. Path to the "figures" folder.

Default: getwd()

The folder is created within the path if it does not exist.

Details

The data are the observations in output from convert_output(), found by their labels:

  • Landings: "landings_observed", "landings_observed_weight", "landings_observed_numbers", or "catch_observed", or "catch" when the output also has "catch_predicted". Only the first of these labels in the output is used, so that landings reported in more than one table are not shown twice.

  • Discards: "discard_observed".

  • Index: "index_observed".

  • Age and length compositions: "age_composition_observed" and "length_composition_observed", or the composition fit tables of Stock Synthesis ("all_obs_mean" in the age and length composition modules).

  • Compositions: "composition_observed", when the type of composition is not reported.

A year has data when it has an observation greater than zero. Fleets are in alphabetical order from top to bottom. To plot only some fleets, filter dat first (e.g., dplyr::filter(dat, fleet %in% c("fleet1", "fleet2"))).

FIMS input data are found by their type: "landings" or "catch" (landings), "index", "age_comp", and "length_comp"; timing is the year, and observations coded as missing (-999) are not data. Other types of input (e.g., "weight_at_age") are not observations and are not shown.

All modules are plotted, so interactive is not used; it is accepted for consistency with the other plotting functions (e.g., in save_all_plots()).

Value

A ggplot2 object.

Examples

plot_data_availability(stockplotr::example_data)

Plot observed and predicted discards

Description

Plot observed and predicted discards

Usage

plot_discard(
  dat,
  geom = "line",
  group = NULL,
  facet = NULL,
  unit_label = NULL,
  era = NULL,
  lbs = FALSE,
  scale_amount = 1,
  interactive = TRUE,
  module = NULL,
  model = NULL,
  predicted = TRUE,
  interval = 0.95,
  tolerance = 0.001,
  make_rda = FALSE,
  figures_dir = getwd(),
  ...
)

Arguments

dat

Data frame or list. A tibble or named list of tibbles (input as list()) returned from convert_output.

If inputting a list of tibbles, the first tibble's reference point defined in ref_line is used to plot a reference line or calculate relative spawning biomass.

geom

String. How the discards are drawn. Default: "line". Options: "line" draws the predicted discards as lines (with intervals as ribbons) and the observed discards as points, or the observed discards as lines when there are no predicted discards to show; "bar" draws the observed discards of each fleet as side-by-side bars for each year (pass position = "stack" to stack them); "point" draws the observed discards as points.

group

String. Single column that groups the data.

Set group = "none" to summarize data over all indexing values.

Default: NULL Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

facet

Character vector. Column name or names used for faceting.

Default: NULL

unit_label

String. Spawning biomass unit as indicated from the data. When setting a unit of pounds please use one of the following keywords: "lbs", "pounds", "lb". For example "1000s of lbs" would still be recognized as pounds. Do not set unit_label to the desired order of magnitude, rather the unit label reflected in the data. Please refer to the argument scale_amount.

Default: NULL

era

String. Era of data.

Default: "time"

Options: "early", "time", "fore" (forecast), or NULL (all data)

lbs

[Deprecated] Logical. TRUE/FALSE; indicate whether to convert the y-axis values from kilograms to pounds. The default units match the default in the unit_label argument - 'mt'. – Deprecate

Default: FALSE

scale_amount

Number. A number to scale the y-axis values. If > 1, the magnitude of the scale amount will be added to the unit label (e.g. scale_amount = 1000 with a unit label of "1000s of lbs" will result in "thousands of 1000s of lbs")

Default: 1

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

module

Character vector. (Optional) Module name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

model

Character vector. (Optional) Model name found in dat$model. If selecting >1 model, place them in a vector like c("model1", "model2").

Default: NULL

If the interactive and >1 model is found, user will select the model in the console. @seealso filter_data()

predicted

Logical. TRUE (Default) or FALSE; show the discards predicted by the model as lines, with the observed discards as points, to show the fit to the observed discards. The predicted discards are shown only when they differ from the observed discards by more than tolerance.

interval

Number. Coverage of the intervals drawn as ribbons around the lines (e.g., 0.95), based on the observation error of the discards. NULL draws no intervals. Default: 0.95

tolerance

Number. The predicted discards are shown only when the range of their differences from the observed discards is more than this proportion of the largest observed discards, as in plot_landings(). Models that fit the discards almost exactly otherwise show two identical series. Use 0 to always show the predicted discards. Default: 0.001 (0.1%)

make_rda

Logical. TRUE/FALSE; indicate whether to save the object and make an automated caption and alternative text in the form of an rda object. If TRUE, the rda will be exported to the folder indicated in the argument "figures_dir".

Default: FALSE.

figures_dir

Path. Path to the "figures" folder.

Default: getwd()

The folder is created within the path if it does not exist.

...

Arguments passed to the geom that draws the main series (ggplot2::geom_line() for the predicted discards, ggplot2::geom_col() for bars, e.g., position = "stack").

Details

The input is from an assessment model output file translated to a standardized output (convert_output). There are options to return a ggplot2 object or export an .rda object containing associated caption and alternative text for the figure.

When dat has observed and predicted discards ("discard_observed" and "discard_predicted") and predicted = TRUE, the predicted discards are drawn as lines in the color of each fleet, with the observed discards as points, for the fleets and years with observed discards, as in plot_landings(). Use facet = "fleet" to plot each fleet in its own panel. When the observed and predicted discards are the same (within tolerance), only the observed discards are drawn, as lines, with a message. Otherwise, the observed discards (or the first label starting with "discard") are drawn as lines.

The intervals are lognormal, from the log-scale standard error or the coefficient of variation of the discards, as in plot_index(). Around the predicted discards, they show the range in which observations are expected given the fit and the observation error; observed discards outside the ribbon are poorly fit. Discards with another type of uncertainty are drawn without intervals.

Value

A ggplot showing discards over time, usually by fleet.

Note

All plotting functions automatically recognize indexing variables and will use them in groupings and/or facetting. @seealso process_data().

See Also

convert_output(), plot_landings(), plot_timeseries(), filter_data(), process_data(), export_kqs(), insert_kqs(), create_rda()

Examples

plot_discard(
  dat = stockplotr::example_data,
  unit_label = "fish",
  module = "DISCARD_OUTPUT"
)
# Fit to the discards: observed (points) and predicted (lines, with 95%
# intervals), one panel per fleet
plot_discard(
  dat = stockplotr::vermilion_snapper,
  facet = "fleet",
  interactive = FALSE
)
# Observed discards of each fleet as stacked bars
plot_discard(
  dat = stockplotr::vermilion_snapper,
  geom = "bar",
  position = "stack",
  interactive = FALSE
)

Create plot with error

Description

Create plot with error

Usage

plot_error(
  dat,
  x = "year",
  y = "estimate",
  geom = "point",
  group = NULL,
  facet = NULL,
  xlab = "Year",
  ylab = NULL,
  hline = TRUE,
  ...
)

Arguments

dat

Data frame. Filtered data frame from standard output file(s) preformatted for the target label from filter_data

x

String. Column name of data used to plot on the x-axis

Default: "year"

y

String. Column name of data used to plot on the y-axis

Default: "estimate"

geom

String. Type of geom to use for plotting found in ggplot2 (e.g. "point", "line", etc.).

Default: "line"

Options: "point" and "area"

group

String. Single column that groups the data. Currently can only have one level of grouping.

Default: NULL Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

facet

Character vector. Column name or names used for faceting (e.g. "year", "area", etc.)

Default: NULL

xlab

String. X-axis label

Default: "Year"

ylab

String. Y-axis label. If NULL, it will be set to the name of y.

Default: NULL

hline

Logical. TRUE/FALSE; indicate whether to place a horizontal line at 1

Default: TRUE

...

Inherited arguments from internal functions from ggplot2::geom_xx

Details

The user can create a line, point, or area plot, where the x-axis is year and y can vary for any time series quantity. Currently, grouping is restricted to one group where faceting can be any number of facets.

Value

Create a plot with error for a stock assessment report.


Plot fishing mortality timeseries

Description

Plot fishing mortality timeseries

Usage

plot_fishing_mortality(
  dat,
  geom = "line",
  group = NULL,
  facet = NULL,
  ref_line = "msy",
  era = NULL,
  module = NULL,
  model = NULL,
  make_rda = FALSE,
  figures_dir = getwd(),
  interactive = TRUE,
  ...
)

Arguments

dat

Data frame or list. A tibble or named list of tibbles (input as list()) returned from convert_output.

If inputting a list of tibbles, the first tibble's reference point defined in ref_line is used to plot a reference line or calculate relative spawning biomass.

geom

String. Geom used for the plot.

Default: "line".

Options: "line", "point", or "area"

group

String. Single column that groups the data.

Set group = "none" to summarize data over all indexing values.

Default: NULL Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

facet

Character vector. Column name or names used for faceting.

Default: NULL

ref_line

String or named vector. Reference point name (and value if custom). When multiple models are being compared, a reference line for each model will appear, if desired. The following options can be used to customize the reference line:

  1. all lines are comparing same ref_line = "msy", ref_line = "target", ref_line = "unfished", etc

  2. custom input vector - ref_line = c("sable23_msy"=30, "sable25_msy"=40) – user must indicate which model in label otherwise it will assign in order of dat

  3. input vector of labels - ref_line = c("msy", "target")

Default: "msy"

Options: (including, but not limited to) "target", "msy", and "unfished" If the reference point is not found in the data, set ref_line = c("name" = value).

era

String. Era of data.

Default: "time"

Options: "early", "time", "fore" (forecast), or NULL (all data)

module

Character vector. (Optional) Module name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

model

Character vector. (Optional) Model name found in dat$model. If selecting >1 model, place them in a vector like c("model1", "model2").

Default: NULL

If the interactive and >1 model is found, user will select the model in the console. @seealso filter_data()

make_rda

Logical. TRUE/FALSE; indicate whether to save the object and make an automated caption and alternative text in the form of an rda object. If TRUE, the rda will be exported to the folder indicated in the argument "figures_dir".

Default: FALSE.

figures_dir

Path. Path to the "figures" folder.

Default: getwd()

The folder is created within the path if it does not exist.

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

...

Arguments called from geom_line or geom_point

Details

The input is from an assessment model output file translated to a standardized output (convert_output). There are options to return a ggplot2 object or export an .rda object containing associated caption and alternative text for the figure.

Value

A plot showing fishing mortality over time.

See Also

convert_output(), filter_data(), process_data(), plot_timeseries(), reference_line(), export_kqs(), insert_kqs(), create_rda()

Examples

plot_fishing_mortality(
  dat = stockplotr:::example_data,
  ref_line = c("target" = 0.2),
  group = "fleet",
  interactive = FALSE,
  module = "TIME_SERIES"
)
plot_fishing_mortality(
  dat = stockplotr:::example_data,
  ref_line = c("target" = 0.2),
  group = "none",
  interactive = FALSE,
  module = "TIME_SERIES"
)

Plot Index of Abundance

Description

Plot Index of Abundance

Usage

plot_index(
  dat,
  unit_label = NULL,
  group = NULL,
  facet = NULL,
  interactive = TRUE,
  module = NULL,
  model = NULL,
  focus = NULL,
  interval = 0.95,
  log = FALSE,
  relative = FALSE,
  make_rda = FALSE,
  figures_dir = getwd(),
  ...
)

Arguments

dat

Data frame or list. A tibble or named list of tibbles (input as list()) returned from convert_output.

If inputting a list of tibbles, the first tibble's reference point defined in ref_line is used to plot a reference line or calculate relative spawning biomass.

unit_label

String. Index of abundance/CPUE units, Default: NULL

group

String. Single column that groups the data.

Set group = "none" to summarize data over all indexing values.

Default: NULL Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

facet

Character vector. Column name or names used for faceting. "fleet" is always added on to any faceting selections. Default: NULL Options may include, but is not limited to: "fleet", "year", "area", NULL

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

module

Character vector. (Optional) Module name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

model

Character vector. (Optional) Model name found in dat$model. If selecting >1 model, place them in a vector like c("model1", "model2").

Default: NULL

If the interactive and >1 model is found, user will select the model in the console. @seealso filter_data()

focus

Character vector. Column name or names used to filter data. (i.e. select names of fleets to zoom into the plot). Default = NULL

interval

Number. Coverage of intervals around the observed index based on its observation error (e.g., 0.95), drawn as vertical lines. NULL draws no intervals. Default: 0.95

log

Logical. TRUE/FALSE; plot the index on a log scale. Indices with lognormal errors are often easier to judge on a log scale, where the intervals are symmetric. Default: FALSE

relative

Logical. TRUE/FALSE; divide each fleet's observed and predicted index (and intervals) by the mean of its observed index, and plot all fleets on one panel, colored by fleet. Indices with conflicting trends (data conflicts) are a common cause of poor fits and are easiest to see this way (r4ss::SSplotIndices() subplot 9). Any group other than "fleet" is added to facet. Default: FALSE

make_rda

Logical. TRUE/FALSE; indicate whether to save the object and make an automated caption and alternative text in the form of an rda object. If TRUE, the rda will be exported to the folder indicated in the argument "figures_dir".

Default: FALSE.

figures_dir

Path. Path to the "figures" folder.

Default: getwd()

The folder is created within the path if it does not exist.

...

Arguments called from geom_line or geom_point

Details

Intervals assume lognormal observation errors, as in Stock Synthesis, FIMS, BAM, and Rceattle: oexp⁡(±z⋅σ)o \exp(\pm z \cdot \sigma), where oo is the observed index and σ\sigma is its log-scale standard error. Uncertainty labeled "se", "sd", or "log_sd" is used as σ\sigma, and a coefficient of variation ("cv") is converted to σ=log⁡(1+CV2)\sigma = \sqrt{\log(1 + CV^2)}. Observations without an uncertainty have no interval.

Intervals assume lognormal observation errors, as in Stock Synthesis, FIMS, BAM, and Rceattle: oexp⁡(±z⋅σ)o \exp(\pm z \cdot \sigma), where oo is the observed index and σ\sigma is its log-scale standard error. Uncertainty labeled "se", "sd", or "log_sd" is used as σ\sigma, and a coefficient of variation ("cv") is converted to σ=log⁡(1+CV2)\sigma = \sqrt{\log(1 + CV^2)}. Observations without an uncertainty have no interval.

The input is from an assessment model output file translated to a standardized output (convert_output). There are options to return a ggplot2 object or export an .rda object containing associated caption and alternative text for the figure.

Value

A plot showing the expected and predicted index.

See Also

convert_output(), filter_data(), process_data(), plot_obsvpred(), export_kqs(), insert_kqs(), create_rda()

Examples

plot_index(
  dat = stockplotr::example_data,
  unit_label = "fish/hr",
  interactive = FALSE
)

# 95% intervals around the observed index, on a log scale
plot_index(
  dat = stockplotr::example_data,
  interval = 0.95,
  log = TRUE,
  interactive = FALSE
)
# All indices relative to their means on one panel
plot_index(
  dat = stockplotr::example_data,
  relative = TRUE,
  interactive = FALSE
)

Plot joint residuals of the fits to indices of abundance

Description

Plot the residuals of the fits to all indices over time with a loess smoother and a fit statistic, as in JABBA (jbplot_residuals() and jbplot_stdresiduals()) and ss3diags (SSplotJABBAres()). A trend in the smoother shows a pattern in the residuals; a large statistic shows a poor fit.

Usage

plot_joint_residuals(
  dat,
  fleet = NULL,
  module = NULL,
  scaled = FALSE,
  overlay = TRUE,
  show_stat = TRUE,
  ncol = NULL,
  interactive = TRUE,
  make_rda = FALSE,
  figures_dir = getwd()
)

Arguments

dat

A tibble from convert_output() with labels "index_observed" and "index_predicted".

fleet

Character vector. Fleet(s) to plot. Default: NULL (all fleets)

module

Character vector. (Optional) Module name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

scaled

Logical. TRUE/FALSE; plot standardized residuals (log residuals divided by their standard error) instead of log residuals.

Default: FALSE

overlay

Logical. TRUE/FALSE; plot all indices on one panel, with a boxplot of the residuals in each year. FALSE plots each index on its own panel.

Default: TRUE

show_stat

Logical. TRUE/FALSE; show the fit statistic in the top right corner of each panel: the root mean square error (RMSE) of log residuals, or the standard deviation of normalized residuals (SDNR) of scaled residuals. When overlay = TRUE, the statistic of each index is also shown in the legend.

Default: TRUE

ncol

Number. Number of columns of panels when overlay = FALSE.

Default: NULL

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

make_rda

Logical. TRUE/FALSE; indicate whether to save the object and make an automated caption and alternative text in the form of an rda object. If TRUE, the rda will be exported to the folder indicated in the argument "figures_dir".

Default: FALSE.

figures_dir

Path. Path to the "figures" folder.

Default: getwd()

The folder is created within the path if it does not exist.

Details

Log residuals are r=log⁡(o)−log⁡(p)r = \log(o) - \log(p) for observed oo and predicted pp, as in plot_runs_test(); scaled residuals are z=r/sz = r / s for the log-scale standard error ss of the observation. The RMSE is 100r2‾100 \sqrt{\overline{r^2}} percent. The SDNR is ∑z2/(n−1)\sqrt{\sum z^2 / (n - 1)}, shown with its critical value χ0.95,n−12/(n−1)\sqrt{\chi^2_{0.95, n - 1} / (n - 1)}; an SDNR above the critical value suggests the standard errors are too small (Francis 2011).

The smoother is a loess regression (span 0.75) of the mean residual of each year on year, for all indices together or for each index on its own panel. It is not drawn for fewer than five years of residuals, or when the years are too sparse for a stable fit; a message names the indices without one.

Observations are treated as in plot_runs_test(): a fleet observed in more than one area, season, subseason, month, or sex becomes separate series, and observations without a positive observed and predicted value are reported in a message. Scaled residuals also need a standard error; observations without one are reported in a message.

Value

A ggplot2 object.

References

Francis, R.I.C.C. 2011. Data weighting in statistical fisheries stock assessment models. Canadian Journal of Fisheries and Aquatic Sciences 68: 1124-1138.

See Also

plot_runs_test(), plot_index(), convert_output()

Examples

plot_joint_residuals(stockplotr::example_data, interactive = FALSE)
plot_joint_residuals(
  stockplotr::example_data,
  scaled = TRUE,
  overlay = FALSE,
  interactive = FALSE
)

Plot observed and predicted landings

Description

Plot observed and predicted landings

Usage

plot_landings(
  dat,
  unit_label = NULL,
  geom = "line",
  group = NULL,
  facet = NULL,
  lbs = FALSE,
  era = NULL,
  scale_amount = 1,
  module = NULL,
  model = NULL,
  interactive = TRUE,
  predicted = TRUE,
  interval = 0.95,
  tolerance = 0.001,
  make_rda = FALSE,
  figures_dir = getwd(),
  ...
)

Arguments

dat

Data frame or list. A tibble or named list of tibbles (input as list()) returned from convert_output.

If inputting a list of tibbles, the first tibble's reference point defined in ref_line is used to plot a reference line or calculate relative spawning biomass.

unit_label

String. Spawning biomass unit as indicated from the data. When setting a unit of pounds please use one of the following keywords: "lbs", "pounds", "lb". For example "1000s of lbs" would still be recognized as pounds. Do not set unit_label to the desired order of magnitude, rather the unit label reflected in the data. Please refer to the argument scale_amount.

Default: NULL

geom

String. How the landings are drawn. Default: "line". Options: "line" draws the predicted landings as lines (with intervals as ribbons) and the observed landings as points, or the observed landings as lines when there are no predicted landings to show; "bar" draws the observed landings of each fleet as side-by-side bars for each year (pass position = "stack" to stack them, as in r4ss::SSplotCatch()); "point" and "area" draw the observed landings only.

group

String. Single column that groups the data.

Set group = "none" to summarize data over all indexing values.

Default: NULL Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

facet

Character vector. Column name or names used for faceting.

Default: NULL

lbs

[Deprecated] Logical. TRUE/FALSE; indicate whether to convert the y-axis values from kilograms to pounds. The default units match the default in the unit_label argument - 'mt'. – Deprecate

Default: FALSE

era

String. Era of data.

Default: "time"

Options: "early", "time", "fore" (forecast), or NULL (all data)

scale_amount

Number. A number to scale the y-axis values. If > 1, the magnitude of the scale amount will be added to the unit label (e.g. scale_amount = 1000 with a unit label of "1000s of lbs" will result in "thousands of 1000s of lbs")

Default: 1

module

Character vector. (Optional) Module name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

model

Character vector. (Optional) Model name found in dat$model. If selecting >1 model, place them in a vector like c("model1", "model2").

Default: NULL

If the interactive and >1 model is found, user will select the model in the console. @seealso filter_data()

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

predicted

Logical. TRUE (Default) or FALSE; show the landings predicted by the model as lines, with the observed landings as points, to show the fit to the observed landings. The predicted landings are shown only when they differ from the observed landings by more than tolerance.

interval

Number. Coverage of the intervals drawn as ribbons around the lines (e.g., 0.95), based on the observation error of the landings. NULL draws no intervals. Default: 0.95

tolerance

Number. The predicted landings are shown only when the range of their differences from the observed landings is more than this proportion of the largest observed landings, as in r4ss::SSplotCatch(). Models that fit the landings almost exactly (e.g., Stock Synthesis with a small catch standard error) otherwise show two identical series. Use 0 to always show the predicted landings. Default: 0.001 (0.1%)

make_rda

Logical. TRUE/FALSE; indicate whether to save the object and make an automated caption and alternative text in the form of an rda object. If TRUE, the rda will be exported to the folder indicated in the argument "figures_dir".

Default: FALSE.

figures_dir

Path. Path to the "figures" folder.

Default: getwd()

The folder is created within the path if it does not exist.

...

Arguments passed to the geom that draws the main series (ggplot2::geom_line() for the predicted landings, ggplot2::geom_col() for bars, e.g., position = "stack").

Details

The input is from an assessment model output file translated to a standardized output (convert_output). There are options to return a ggplot2 object or export an .rda object containing associated caption and alternative text for the figure.

The landings plotted are the observed landings: "landings_observed", "landings_observed_weight", "landings_observed_numbers", or "catch" when the output also has "catch_predicted" (the first of these in dat). When dat has none of these, the first label containing "landings" is plotted, with a message.

When predicted = TRUE and geom = "line", the matching predicted landings ("landings_predicted", "landings_predicted_weight", "landings_predicted_numbers", or "catch_predicted") are drawn as lines in the color of each fleet, with the observed landings as points, for the fleets and years with observed landings. Use facet = "fleet" to plot each fleet in its own panel. When the observed and predicted landings are the same (within tolerance), only the observed landings are drawn, as lines, with a message.

The intervals are lognormal, from the log-scale standard error or the coefficient of variation of the landings, as in plot_index(). Around the predicted landings, they show the range in which observations are expected given the fit and the observation error; observed landings outside the ribbon are poorly fit. Landings are often given a small observation error (e.g., a standard error of 0.01 in Stock Synthesis), so their intervals can be narrow.

Value

A plot showing the landings over time.

See Also

convert_output(), filter_data(), process_data(), plot_timeseries(), export_kqs(), insert_kqs(), create_rda()

Examples

plot_landings(
  dat = stockplotr::example_data,
  unit_label = "metric tons",
  group = "fleet",
  interactive = FALSE,
  make_rda = FALSE
)
# Fit to the landings: observed (points) and predicted (lines, with 95%
# intervals), one panel per fleet
plot_landings(
  dat = stockplotr::vermilion_snapper,
  facet = "fleet",
  interactive = FALSE
)
# Observed landings of each fleet as side-by-side bars
plot_landings(
  dat = stockplotr::vermilion_snapper,
  geom = "bar",
  interactive = FALSE
)
# ... or stacked, as in r4ss::SSplotCatch()
plot_landings(
  dat = stockplotr::vermilion_snapper,
  geom = "bar",
  position = "stack",
  interactive = FALSE
)

Plot natural mortality (M) at age

Description

Plot natural mortality (M) at age

Usage

plot_natural_mortality(
  dat,
  group = NULL,
  facet = NULL,
  era = NULL,
  interactive = TRUE,
  module = NULL,
  model = NULL,
  make_rda = FALSE,
  figures_dir = getwd(),
  ...
)

Arguments

dat

Data frame or list. A tibble or named list of tibbles (input as list()) returned from convert_output.

If inputting a list of tibbles, the first tibble's reference point defined in ref_line is used to plot a reference line or calculate relative spawning biomass.

group

String. Single column that groups the data.

Set group = "none" to summarize data over all indexing values.

Default: NULL Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

facet

Character vector. Column name or names used for faceting.

Default: NULL

era

String. Era of data.

Default: "time"

Options: "early", "time", "fore" (forecast), or NULL (all data)

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

module

Character vector. (Optional) Module name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

model

Character vector. (Optional) Model name found in dat$model. If selecting >1 model, place them in a vector like c("model1", "model2").

Default: NULL

If the interactive and >1 model is found, user will select the model in the console. @seealso filter_data()

make_rda

Logical. TRUE/FALSE; indicate whether to save the object and make an automated caption and alternative text in the form of an rda object. If TRUE, the rda will be exported to the folder indicated in the argument "figures_dir".

Default: FALSE.

figures_dir

Path. Path to the "figures" folder.

Default: getwd()

The folder is created within the path if it does not exist.

...

Arguments called from geom_line or geom_point

Details

The input is from an assessment model output file translated to a standardized output (convert_output). There are options to return a ggplot2 object or export an .rda object containing associated caption and alternative text for the figure.

Value

A plot showing natural mortality at age.

See Also

convert_output(), filter_data(), process_data(), plot_timeseries(), export_kqs(), insert_kqs(), create_rda()

Examples

plot_natural_mortality(
  dat = stockplotr:::example_data,
  module = "Natural_Mortality",
  interactive = FALSE
)

Plot observed vs. predicted data

Description

Plot observed vs. predicted data

Usage

plot_obsvpred(
  dat,
  x = "year",
  y = "estimate",
  observed_label = "observed",
  predicted_label = "predicted",
  geom = "line",
  xlab = "Year",
  ylab = NULL,
  group = NULL,
  facet = NULL
)

Arguments

dat

Data frame. Filtered data frame from standard output file(s) preformatted for the target label from filter_data

x

String. Column name of data used to plot on the x-axis

Default: "year"

y

String. Column name of data used to plot on the y-axis

Default: "estimate"

observed_label

String. Label used to filter the observed data

Default: "observed"

predicted_label

String. Label used to filter the predicted data Default: "predicted"

geom

String. Type of geom to use for plotting found in ggplot2 (e.g. "point", "line", etc.).

Default: "line"

Options: "point" and "area"

xlab

String. X-axis label

Default: "Year"

ylab

String. Y-axis label. If NULL, it will be set to the name of y.

Default: NULL

group

String. Single column that groups the data. Currently can only have one level of grouping.

Default: NULL Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

facet

Character vector. Column name or names used for faceting (e.g. "year", "area", etc.)

Default: NULL

Value

A plot of observed vs. predicted data for a stock assessment report.


Plot Recruitment

Description

Plot Recruitment

Usage

plot_recruitment(
  dat,
  unit_label = NULL,
  scale_amount = 1,
  era = NULL,
  group = NULL,
  facet = NULL,
  interactive = TRUE,
  module = NULL,
  model = NULL,
  make_rda = FALSE,
  figures_dir = getwd()
)

Arguments

dat

Data frame or list. A tibble or named list of tibbles (input as list()) returned from convert_output.

If inputting a list of tibbles, the first tibble's reference point defined in ref_line is used to plot a reference line or calculate relative spawning biomass.

unit_label

String. Units for recruitment

Default: NULL

scale_amount

Number. A number to scale the y-axis values. If > 1, the magnitude of the scale amount will be added to the unit label (e.g. scale_amount = 1000 with a unit label of "1000s of lbs" will result in "thousands of 1000s of lbs")

Default: 1

era

String. Era of data.

Default: "time"

Options: "early", "time", "fore" (forecast), or NULL (all data)

group

String. Single column that groups the data.

Set group = "none" to summarize data over all indexing values.

Default: NULL Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

facet

Character vector. Column name or names used for faceting.

Default: NULL

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

module

Character vector. (Optional) Module name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

model

Character vector. (Optional) Model name found in dat$model. If selecting >1 model, place them in a vector like c("model1", "model2").

Default: NULL

If the interactive and >1 model is found, user will select the model in the console. @seealso filter_data()

make_rda

Logical. TRUE/FALSE; indicate whether to save the object and make an automated caption and alternative text in the form of an rda object. If TRUE, the rda will be exported to the folder indicated in the argument "figures_dir".

Default: FALSE.

figures_dir

Path. Path to the "figures" folder.

Default: getwd()

The folder is created within the path if it does not exist.

Details

The input is from an assessment model output file translated to a standardized output (convert_output). There are options to return a ggplot2 object or export an .rda object containing associated caption and alternative text for the figure.

Value

A plot showing recruitment over time.

See Also

convert_output(), filter_data(), process_data(), plot_timeseries(), export_kqs(), insert_kqs(), create_rda()

Examples

plot_recruitment(
  dat = stockplotr::example_data,
  unit_label = "metric tons",
  scale_amount = 100,
  interactive = TRUE,
  module = "TIME_SERIES",
  make_rda = FALSE
)
plot_recruitment(
  dat = stockplotr::example_data,
  era = "fore",
  unit_label = "kg",
  module = "TIME_SERIES",
  make_rda = FALSE
)

Plot recruitment deviations

Description

Plot recruitment deviations

Usage

plot_recruitment_deviations(
  dat,
  module = NULL,
  model = NULL,
  era = NULL,
  interactive = TRUE,
  make_rda = FALSE,
  figures_dir = getwd(),
  ...
)

Arguments

dat

Data frame or list. A tibble or named list of tibbles (input as list()) returned from convert_output.

If inputting a list of tibbles, the first tibble's reference point defined in ref_line is used to plot a reference line or calculate relative spawning biomass.

module

Character vector. (Optional) Module name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

model

Character vector. (Optional) Model name found in dat$model. If selecting >1 model, place them in a vector like c("model1", "model2").

Default: NULL

If the interactive and >1 model is found, user will select the model in the console. @seealso filter_data()

era

String. Era of data.

Default: "time"

Options: "early", "time", "fore" (forecast), or NULL (all data)

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

make_rda

Logical. TRUE/FALSE; indicate whether to save the object and make an automated caption and alternative text in the form of an rda object. If TRUE, the rda will be exported to the folder indicated in the argument "figures_dir".

Default: FALSE.

figures_dir

Path. Path to the "figures" folder.

Default: getwd()

The folder is created within the path if it does not exist.

...

Arguments called from geom_line or geom_point

Details

The input is from an assessment model output file translated to a standardized output (convert_output). There are options to return a ggplot2 object or export an .rda object containing associated caption and alternative text for the figure.

Value

A plot showing recruitment deviations relative to one, over time.

Note

All plotting functions automatically recognize indexing variables and will use them in groupings and/or facetting.

See Also

convert_output(), plot_error(), filter_data(), process_data(), export_kqs(), insert_kqs(), create_rda()

Examples

plot_recruitment_deviations(
  dat = stockplotr:::example_data,
  interactive = FALSE,
  size = 1.5
)
plot_recruitment_deviations(
  dat = stockplotr:::example_data,
  era = "early",
  interactive = FALSE,
  shape = 2
)

Plot retrospective peels

Description

Plot a given quantity across multiple models with differing end years, so as to plot retrospective peels.

Usage

plot_retrospective(
  dat,
  end_years = NULL,
  quantity = "spawning_biomass",
  show_end_year_points = TRUE,
  mohns_rho = NULL,
  group = "model",
  make_rda = FALSE,
  figures_dir = getwd(),
  ...
)

Arguments

dat

Data frame or list. A tibble or named list of tibbles (input as list()) returned from convert_output.

If inputting a list of tibbles, the first tibble's reference point defined in ref_line is used to plot a reference line or calculate relative spawning biomass.

end_years

Integer. vector of what year, relative to the maximum year present in dat, should be treated as the final year for each model. Should be <= 0.

Default: 0

quantity

String. Assessment quantity to plot (e.g., spawning biomass, biomass, recruitment, etc.). Should correspond to an existing ⁠plot_*⁠ function.

Default: "spawning_biomass"

show_end_year_points

Logical. Whether to add points at the terminal year for each model peel.

Default: TRUE

mohns_rho

Numeric. Externally calculated value(s) of Mohn's rho. Should be either a single value or of length end_years-1. Value of NULL disables reporting Mohn's rho statistic on plot. If vector, names of vector entries should match with model names.

Default: NULL

group

String. Single column that groups the data.

Default: "model"

make_rda

Logical. TRUE/FALSE; indicate whether to save the object and make an automated caption and alternative text in the form of an rda object. If TRUE, the rda will be exported to the folder indicated in the argument "figures_dir".

Default: FALSE.

figures_dir

Path. Path to the "figures" folder.

Default: getwd()

The folder is created within the path if it does not exist.

...

Arguments called from geom_line or geom_point

Details

The input is from an assessment model output file translated to a standardized output (convert_output). There are options to return a ggplot2 object or export an .rda object containing associated caption and alternative text for the figure.

Value

A plot showing values of an assessment quantity across different retrospective peels.

Note

All plotting functions automatically recognize indexing variables and will use them in groupings and/or facetting, but will prioritize the defined group or facet by the function arguments. @seealso process_data().

See Also

convert_output(), plot_timeseries(), calculate_reference_point(), reference_line(), filter_data(), process_data(), export_kqs(), insert_kqs(), create_rda()

Examples

plot_retrospective(
  dat = ss3_simple,
  end_years = 0:-5,
  quantity = "spawning_biomass",
  show_end_year_points = TRUE
)
plot_retrospective(
  dat = ss3_simple,
  end_years = 0:-5,
  quantity = "spr",
  show_end_year_points = TRUE,
  interactive = FALSE,
  module = "derived_quants"
)
plot_retrospective(
  dat = ss3_simple,
  end_years = 0:-5,
  quantity = "spr",
  show_end_year_points = TRUE,
  mohns_rho = c(0.023, 0.01, 1.25, 0.845, 0.068),
  interactive = FALSE,
  module = "derived_quants"
)

Plot residual runs tests for indices of abundance

Description

Plot the residuals of the fit to each index over time with three-sigma control limits and a runs test for non-random residuals (Carvalho et al. 2017), as in JABBA and ss3diags (SSplotRunstest()).

Usage

plot_runs_test(
  dat,
  fleet = NULL,
  module = NULL,
  interactive = TRUE,
  ncol = NULL,
  make_rda = FALSE,
  figures_dir = getwd()
)

Arguments

dat

A tibble from convert_output() with labels "index_observed" and "index_predicted".

fleet

Character vector. Fleet(s) to plot. Default: NULL (all fleets)

module

Character vector. (Optional) Module name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

ncol

Number. Number of columns of panels. Default: NULL

make_rda

Logical. TRUE/FALSE; indicate whether to save the object and make an automated caption and alternative text in the form of an rda object. If TRUE, the rda will be exported to the folder indicated in the argument "figures_dir".

Default: FALSE.

figures_dir

Path. Path to the "figures" folder.

Default: getwd()

The folder is created within the path if it does not exist.

Details

Residuals are log⁡(o)−log⁡(p)\log(o) - \log(p) for observed oo and predicted pp, assuming lognormal errors. The one-sided runs test checks whether residual signs are random over time (normal approximation, as in ss3diags). The shaded band spans the three-sigma limits, with sigma from the average moving range; it is green when the test passes (p >= 0.05) and red when it fails. Residuals outside the limits are filled red.

No observations are dropped silently: a fleet observed in more than one area, season, subseason, month, or sex becomes separate series (e.g., "Survey (season 2)"), observations without a positive observed and predicted value are reported in a message, and output from more than one model or with values that cannot be told apart is an error. Years with no observed index (BAM reports every year) are not observations.

Value

A ggplot2 object.

References

Carvalho, F., et al. 2017. Can diagnostic tests help identify model misspecification in integrated stock assessments? Fisheries Research 192: 28-40.

See Also

plot_index(), convert_output()

Examples

plot_runs_test(stockplotr::example_data, interactive = FALSE)

Plot selectivity

Description

Plot selectivity

Usage

plot_selectivity(
  dat,
  unit_label = NULL,
  group = NULL,
  facet = NULL,
  interactive = TRUE,
  module = NULL,
  model = NULL,
  make_rda = FALSE,
  figures_dir = getwd(),
  ...
)

Arguments

dat

Data frame or list. A tibble or named list of tibbles (input as list()) returned from convert_output.

If inputting a list of tibbles, the first tibble's reference point defined in ref_line is used to plot a reference line or calculate relative spawning biomass.

unit_label

units for length-based selectivity.

Default: NULL

group

String. Single column that groups the data.

Set group = "none" to summarize data over all indexing values.

Default: NULL Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

facet

Character vector. Column name or names used for faceting.

Default: NULL

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

module

Character vector. (Optional) Module name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

model

Character vector. (Optional) Model name found in dat$model. If selecting >1 model, place them in a vector like c("model1", "model2").

Default: NULL

If the interactive and >1 model is found, user will select the model in the console. @seealso filter_data()

make_rda

Logical. TRUE/FALSE; indicate whether to save the object and make an automated caption and alternative text in the form of an rda object. If TRUE, the rda will be exported to the folder indicated in the argument "figures_dir".

Default: FALSE.

figures_dir

Path. Path to the "figures" folder.

Default: getwd()

The folder is created within the path if it does not exist.

...

Arguments called from geom_line or geom_point

Details

The input is from an assessment model output file translated to a standardized output (convert_output). There are options to return a ggplot2 object or export an .rda object containing associated caption and alternative text for the figure.

Value

A plot showing selectivity by age or length.

See Also

convert_output(), filter_data(), process_data(), plot_timeseries(), export_kqs(), insert_kqs(), create_rda()

Examples

plot_selectivity(
  dat = stockplotr::example_data,
  interactive = TRUE,
  module = "AGE_SELEX",
  make_rda = FALSE
)
plot_selectivity(
  dat = stockplotr::example_data,
  module = "LEN_SELEX",
  unit_label = "cm",
  make_rda = FALSE
)

Plot spawning biomass (SB)

Description

Plot spawning biomass with a reference line as a dashed line. The figure can also be made relative to this reference line rather than in absolute units.

Usage

plot_spawning_biomass(
  dat,
  geom = "line",
  group = NULL,
  facet = NULL,
  ref_line = "msy",
  unit_label = NULL,
  era = NULL,
  lbs = lifecycle::deprecated(),
  module = NULL,
  model = NULL,
  scale_amount = 1,
  relative = FALSE,
  make_rda = FALSE,
  figures_dir = getwd(),
  interactive = TRUE,
  ...
)

Arguments

dat

Data frame or list. A tibble or named list of tibbles (input as list()) returned from convert_output.

If inputting a list of tibbles, the first tibble's reference point defined in ref_line is used to plot a reference line or calculate relative spawning biomass.

geom

String. Geom used for the plot.

Default: "line".

Options: "line", "point", or "area"

group

String. Single column that groups the data.

Set group = "none" to summarize data over all indexing values.

Default: NULL Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

facet

Character vector. Column name or names used for faceting.

Default: NULL

ref_line

String or named vector. Reference point name (and value if custom). When multiple models are being compared, a reference line for each model will appear, if desired. The following options can be used to customize the reference line:

  1. all lines are comparing same ref_line = "msy", ref_line = "target", ref_line = "unfished", etc

  2. custom input vector - ref_line = c("sable23_msy"=30, "sable25_msy"=40) – user must indicate which model in label otherwise it will assign in order of dat

  3. input vector of labels - ref_line = c("msy", "target")

Default: "msy"

Options: (including, but not limited to) "target", "msy", and "unfished" If the reference point is not found in the data, set ref_line = c("name" = value).

unit_label

String. Spawning biomass unit as indicated from the data. When setting a unit of pounds please use one of the following keywords: "lbs", "pounds", "lb". For example "1000s of lbs" would still be recognized as pounds. Do not set unit_label to the desired order of magnitude, rather the unit label reflected in the data. Please refer to the argument scale_amount.

Default: NULL

era

String. Era of data.

Default: "time"

Options: "early", "time", "fore" (forecast), or NULL (all data)

lbs

[Deprecated] Logical. TRUE/FALSE; indicate whether to convert the y-axis values from kilograms to pounds. The default units match the default in the unit_label argument - 'mt'. – Deprecate

Default: FALSE

module

Character vector. (Optional) Module name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

model

Character vector. (Optional) Model name found in dat$model. If selecting >1 model, place them in a vector like c("model1", "model2").

Default: NULL

If the interactive and >1 model is found, user will select the model in the console. @seealso filter_data()

scale_amount

Number. A number to scale the y-axis values. If > 1, the magnitude of the scale amount will be added to the unit label (e.g. scale_amount = 1000 with a unit label of "1000s of lbs" will result in "thousands of 1000s of lbs")

Default: 1

relative

Logical. TRUE/FALSE; specify whether to set y-axis values relative to the ref_line value.

Default: FALSE

make_rda

Logical. TRUE/FALSE; indicate whether to save the object and make an automated caption and alternative text in the form of an rda object. If TRUE, the rda will be exported to the folder indicated in the argument "figures_dir".

Default: FALSE.

figures_dir

Path. Path to the "figures" folder.

Default: getwd()

The folder is created within the path if it does not exist.

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

...

Arguments called from geom_line or geom_point

Details

The input is from an assessment model output file translated to a standardized output (convert_output). There are options to return a ggplot2 object or export an .rda object containing associated caption and alternative text for the figure.

Value

A plot showing spawning biomass over time.

Note

All plotting functions automatically recognize indexing variables and will use them in groupings and/or facetting. @seealso process_data().

See Also

convert_output(), plot_timeseries(), calculate_reference_point(), reference_line(), filter_data(), process_data(), export_kqs(), insert_kqs(), create_rda()

Examples

plot_spawning_biomass(
  dat = stockplotr::example_data,
  geom = "line",
  ref_line = "msy",
  unit_label = "mt",
  scale_amount = 1000,
  interactive = FALSE,
  module = "TIME_SERIES",
  linewidth = 1.5
)
plot_spawning_biomass(
  dat = stockplotr::example_data,
  ref_line = c("target" = 10),
  interactive = FALSE,
  module = "TIME_SERIES"
)
## Not run: 
plot_spawning_biomass(
  dat = list("2023" = model1, "2025" = model2),
  ref_line = c("SBF30" = 1500, "SBF40" = 2300)
)

## End(Not run)

Plot spawning potential ratio (SPR)

Description

Plot spawning potential ratio (SPR)

Usage

plot_spr(
  dat,
  geom = "line",
  group = NULL,
  facet = NULL,
  ref_line = "target",
  era = NULL,
  module = NULL,
  model = NULL,
  interactive = TRUE,
  make_rda = FALSE,
  figures_dir = getwd(),
  ylab = NULL,
  ...
)

Arguments

dat

Data frame or list. A tibble or named list of tibbles (input as list()) returned from convert_output.

If inputting a list of tibbles, the first tibble's reference point defined in ref_line is used to plot a reference line or calculate relative spawning biomass.

geom

String. Geom used for the plot.

Default: "line".

Options: "line", "point", or "area"

group

String. Single column that groups the data.

Set group = "none" to summarize data over all indexing values.

Default: NULL Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

facet

Character vector. Column name or names used for faceting.

Default: NULL

ref_line

String or named vector. Reference point name (and value if custom). When multiple models are being compared, a reference line for each model will appear, if desired. The following options can be used to customize the reference line:

  1. all lines are comparing same ref_line = "msy", ref_line = "target", ref_line = "unfished", etc

  2. custom input vector - ref_line = c("sable23_msy"=30, "sable25_msy"=40) – user must indicate which model in label otherwise it will assign in order of dat

  3. input vector of labels - ref_line = c("msy", "target")

Default: "msy"

Options: (including, but not limited to) "target", "msy", and "unfished" If the reference point is not found in the data, set ref_line = c("name" = value).

era

String. Era of data.

Default: "time"

Options: "early", "time", "fore" (forecast), or NULL (all data)

module

Character vector. (Optional) Module name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

model

Character vector. (Optional) Model name found in dat$model. If selecting >1 model, place them in a vector like c("model1", "model2").

Default: NULL

If the interactive and >1 model is found, user will select the model in the console. @seealso filter_data()

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

make_rda

Logical. TRUE/FALSE; indicate whether to save the object and make an automated caption and alternative text in the form of an rda object. If TRUE, the rda will be exported to the folder indicated in the argument "figures_dir".

Default: FALSE.

figures_dir

Path. Path to the "figures" folder.

Default: getwd()

The folder is created within the path if it does not exist.

ylab

String. Y-axis label to show.

...

Arguments called from geom_line or geom_point

Details

The input is from an assessment model output file translated to a standardized output (convert_output). There are options to return a ggplot2 object or export an .rda object containing associated caption and alternative text for the figure.

Value

A plot showing spawning potential ratio (SPR).

See Also

convert_output(), filter_data(), process_data(), plot_timeseries(), export_kqs(), insert_kqs(), create_rda()

Examples

plot_spr(
  dat = stockplotr:::example_data,
  unit_label = "metric tons",
  group = NULL,
  interactive = FALSE,
  make_rda = FALSE,
  ylab = "SPR"
)
plot_spr(
  dat = stockplotr:::example_data,
  unit_label = "metric tons",
  facet = NULL,
  module = "DERIVED_QUANTITIES",
  interactive = FALSE,
  make_rda = FALSE,
  ylab = "(1-SPR)/(1-SPR_ref)"
)

Plot Stock Recruit Relationship

Description

Plot Stock Recruit Relationship

Usage

plot_stock_recruitment(
  dat,
  spawning_biomass_label = NULL,
  recruitment_label = NULL,
  interactive = TRUE,
  era = NULL,
  module = NULL,
  model = NULL,
  scale_amount = 1,
  make_rda = FALSE,
  figures_dir = getwd()
)

Arguments

dat

Data frame or list. A tibble or named list of tibbles (input as list()) returned from convert_output.

If inputting a list of tibbles, the first tibble's reference point defined in ref_line is used to plot a reference line or calculate relative spawning biomass.

spawning_biomass_label

String. Units for spawning biomass

Default: NULL

recruitment_label

String. Units for recruitment

Default: NULL

interactive

Logical. TRUE/FALSE; indicate whether the environment the plot is being made in is interactive. By default, this is set to false. If true, dependent on your data, a option menu will pop-up.

Default: TRUE

era

String. Era of data.

Default: "time"

Options: "early", "time", "fore" (forecast), or NULL (all data)

module

Character vector. (Optional) Module name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

model

Character vector. (Optional) Model name found in dat$model. If selecting >1 model, place them in a vector like c("model1", "model2").

Default: NULL

If the interactive and >1 model is found, user will select the model in the console. @seealso filter_data()

scale_amount

Number. A number to scale the y-axis values. If > 1, the magnitude of the scale amount will be added to the unit label (e.g. scale_amount = 1000 with a unit label of "1000s of lbs" will result in "thousands of 1000s of lbs")

Default: 1

make_rda

Logical. TRUE/FALSE; indicate whether to save the object and make an automated caption and alternative text in the form of an rda object. If TRUE, the rda will be exported to the folder indicated in the argument "figures_dir".

Default: FALSE.

figures_dir

Path. Path to the "figures" folder.

Default: getwd()

The folder is created within the path if it does not exist.

Details

The input is from an assessment model output file translated to a standardized output (convert_output). There are options to return a ggplot2 object or export an .rda object containing associated caption and alternative text for the figure.

Value

A plot showing the stock recruitment relationship.

See Also

convert_output(), filter_data(), process_data(), plot_timeseries(), export_kqs(), insert_kqs(), create_rda()

Examples

plot_stock_recruitment(
  dat = stockplotr:::example_data,
  interactive = FALSE,
  spawning_biomass_label = "metric tons",
  recruitment_label = "metric tons",
  module = "DERIVED_QUANTITIES"
)

Plot time series trends

Description

Plot time series trends

Usage

plot_timeseries(
  dat,
  x = "year",
  y = "estimate",
  geom = "line",
  xlab = "Year",
  ylab = NULL,
  group = NULL,
  facet = NULL,
  ...
)

Arguments

dat

Data frame. Filtered data frame from standard output file(s) preformatted for the target label from filter_data

x

String. Column name of data used to plot on the x-axis

Default: "year"

y

String. Column name of data used to plot on the y-axis

Default: "estimate"

geom

String. Type of geom to use for plotting found in ggplot2 (e.g. "point", "line", etc.).

Default: "line"

Options: "point" and "area"

xlab

String. X-axis label

Default: "Year"

ylab

String. Y-axis label. If NULL, it will be set to the name of y.

Default: NULL

group

String. Single column that groups the data. Currently can only have one level of grouping.

Default: NULL Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

facet

Character vector. Column name or names used for faceting (e.g. "year", "area", etc.)

Default: NULL

...

Inherited arguments from internal functions from ggplot2::geom_xx

Details

The user can create a line, point, or area plot, where the x-axis is year and y can vary for any time series quantity. Currently, grouping is restricted to one group where faceting can be any number of facets.

Value

Create a time series plot for a stock assessment report.

Examples

## Not run: 
plot_timeseries(dat,
  x = "year",
  y = "estimate",
  geom = "line",
  xlab = "Year",
  ylab = "Biomass",
  group = "fleet",
  facet = "area"
)

## End(Not run)

2018 Gulf of Alaska Pollock stock assessment output

Description

Output of the 2018 Gulf of Alaska Pollock stock assessment produced from Rceattle, standardized using stockplotr::convert_output(). The example can be found and run from the Rceattle repository.

Usage

data(pollock)

Format

A tibble (tbl_df, tbl, data.frame) with 9,983 rows and 35 variables:

label

Standard name for estimate or value name

estimate

Actual value of the label

year

Annual indexing value

fleet

Names of fleets or surveys indexed by the data

sex

Native reference to male, female, unknown, or none

area

Specified areas by the model

growth_pattern

Indexing column of data

uncertainty

Value of uncertainty associated with the label column

uncertainty_label

Uncertainty label or name associated with the label columns

module_name

Name of keyword (SS3) or list indexing in the original model output for tracking purposes

time

Time sometimes referenced in decimals to the year and month

era

"time" for current time series in model; "fore" representing the projected or forecasted years of the model

month

Month factor

season

Season usually associated with year

subseason

Subseason when used

birthseas

Birthseason found in SS3

initial

Initial input value in the model when available associated with the label column

likelihood

Likelihood value for the data point

platoon

Platoon also an SS3 indexing value

age

Age of fish

bio_pattern

Indexing column of data

settlement

Indexing column of data

morph

Indexing column of data

type

Indexing column of data

factor

Indexing column of data

part

Indexing column of data

kind

Indexing column of data

nsim

Indexing column of data

bin

Indexing column of data

age_a

Alternative age column

length_bins

Length bins for composition or other length based data

count

Indexing column of data

block

Indexing column of data

Source

Rceattle Example

References

Adams, G. D., Holsman, K. K., Barbeaux, S. J., Dorn, M. W., Ianelli, J. N., Spies, I., … Punt, A. E. (2022) (doi:10.1016/j.fishres.2022.106303)

Examples

data(pollock)
head(pollock)
unique(pollock$label)

Prepare composition data for plotting

Description

Reshape age or length composition data (observed and, optionally, expected proportions) from convert_output() into the tidy format used by the composition plotting functions (plot_composition_distribution(), plot_composition_bubble(), plot_composition_residuals(), plot_composition_sexratio(), plot_composition_francis(), plot_composition_samples(), plot_composition_residual_distribution(), plot_composition_residual_pattern(), and plot_composition_andre()). Each of these functions calls prepare_composition_data() itself, so it only needs to be called directly to inspect or modify the data.

Usage

prepare_composition_data(
  dat,
  comp_type = NULL,
  fleet = NULL,
  normalize = TRUE,
  conditional = FALSE
)

Arguments

dat

A tibble returned from convert_output() (see bigskate_lencomp). Compositions are the rows whose label contains "composition", for example:

Stock Synthesis (from an r4ss::SS_output() list)

"length_composition_observed", "length_composition_predicted", "length_composition_pearson_residual", and "length_composition_sample_size" (and the "age_" equivalents), with conditional age-at-length data labeled "conditional_age_composition_*".

FIMS

"age_composition_proportion" and "age_composition_expected" (and the "length_" equivalents).

BAM and Rceattle

"age_composition_observed" and "age_composition_predicted", or "composition_observed" and "composition_predicted".

Bins are taken from the age or length_bins column, and partitions from the part column. Other formats are also recognized:

Tidy composition data

Columns year, bin, and observed, with optional columns fleet, sex, part (partition: 0 = whole catch, 1 = discard, 2 = retained), expected, n (input or adjusted sample size), pearson, comp_type, and length_bin (for conditional age-at-length data).

FIMS estimates

Output from FIMS::get_estimates() that contains observed and expected columns. Rows whose label contains "comp" are kept and the bin is taken from the age or length column.

r4ss output

A list returned by r4ss::SS_output() (length and age compositions are combined and fleet names are added) or its lendbase or agedbase elements (columns Yr, Fleet, Sex, Bin, Obs, Exp, Pearson, Nsamp_adj, ...). Conditional age-at-length rows are dropped from agedbase so that only marginal age compositions remain, unless conditional = TRUE.

For conditional age-at-length data (conditional = TRUE), see bigskate_caal.

comp_type

String. Type of composition to keep when dat contains more than one. Options: "age", "length", or NULL (keep all). Default: NULL

fleet

Character or numeric vector. Fleet(s) to keep, matching either the fleet name (e.g., "Fishery_current") or the fleet name with its partition (e.g., "Fishery_current (retained)"). NULL keeps all fleets. Default: NULL

normalize

Logical. TRUE/FALSE; rescale observed and expected values so that they sum to one within each year, fleet, and composition type (and length bin for conditional data). Sex-specific compositions are normalized jointly across sexes, unless each sex already sums to one on its own (single-sex compositions). Use TRUE when dat contains counts rather than proportions. Default: TRUE

conditional

Logical. TRUE/FALSE; keep conditional age-at-length data instead of marginal compositions. Conditional compositions are normalized within each length bin. Used by plot_composition_andre() and plot_composition_bubble(). Default: FALSE

Details

When Pearson residuals are not supplied, they are calculated assuming a multinomial distribution as

r=(o−e)/e(1−e)/Nr = (o - e) / \sqrt{e (1 - e) / N}

where oo and ee are the observed and expected proportions and NN is the sample size in the n column. If n is not available, residuals are left as NA.

Value

A tibble with one row per year, fleet, sex, and bin and columns comp_type, fleet, year, sex, bin, observed, expected, n, and pearson (plus length_bin when conditional = TRUE). Columns that cannot be determined from dat are NA.

See Also

plot_composition_distribution(), plot_composition_bubble(), plot_composition_residuals(), plot_composition_sexratio(), plot_composition_francis()

Examples

comps <- prepare_composition_data(bigskate_lencomp, fleet = "WCGBTS")
head(comps)

# Conditional age-at-length data
prepare_composition_data(bigskate_caal, conditional = TRUE)

# Data in the stockplotr long format are reshaped automatically
long <- data.frame(
  label = rep(c("age_composition_proportion", "age_composition_expected"), each = 3),
  year = 2020,
  fleet = "fleet1",
  age = rep(1:3, 2),
  estimate = c(0.2, 0.5, 0.3, 0.25, 0.45, 0.3)
)
prepare_composition_data(long)

Processing for figures

Description

Processing for figures

Usage

process_data(dat, group = NULL, facet = NULL, lbs = FALSE)

Arguments

dat

Data frame. Pre-filtered data from filter_data following a long format data.

group

String. Indexing variable of the data. To remove any groups and summarize data across all factors, set group = "none". Setting group = NULL will keep any grouping variables identified in the data by the function.

Default: NULL

Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

facet

Character vector. Faceting variable(s) of the data.

Default: NULL

lbs

Logical. TRUE/FALSE; indicate whether to convert the y-axis values from kilograms to pounds. The default units match the default in the unit_label argument - 'metric tons'.

Default: FALSE

Details

Automatically detects potential grouping and faceting data from a dataframe output from filter_data.

Value

List of 3 objects:

data

A data frame of the processed data ready for plotting.

group

Grouping variable of the data. If NULL, no grouping variable is identified. If not NULL, the function will verify that the data is indexed by this variables, otherwise it will overwrite it to a different, valid indexed variable or NULL.

facet

Faceting variable(s) identifying the variable(s) of the data. If NULL, no faceting variable is identified. Any identified indexed variables found in this function will be added to facet.

Examples

{
  filtered <- stockplotr::filter_data(
    dat = stockplotr:::example_data,
    label_name = "fishing_mortality$",
    geom = "line",
    module = "TIME_SERIES"
  )
  process_data(dat = filtered)
}

Processing for tables

Description

Processing for tables

Usage

process_table(dat, group = NULL, method = "sum", label = NULL, digits = 2)

Arguments

dat

Data frame. Pre-filtered data from filter_data following a long format data.

group

String. Indexing variable of the data. To remove any groups and summarize data across all factors, set group = "none". Setting group = NULL will keep any grouping variables identified in the data by the function.

Default: NULL

Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

method

String. Method for summarizing data when group is set to "none".

Default: "sum"

Options: "sum" or "mean"

label

String. Label value or values used to filter the data.

Default: NULL

digits

Number. Numeric value indicating the number of rounding digits.

Default: 2

Details

Input is an object created with filter_data.

Value

A dataframe of processed data ready for formatting into a table.

Examples

{
  filtered <- filter_data(
    dat = stockplotr:::example_data,
    label = "landings",
    geom = "line",
    era = "time"
  )
  process_table(dat = filtered, method = "sum")
}

Preformatted reference line

Description

Preformatted reference line

Usage

reference_line(
  label_name,
  ref_line,
  scale_amount = 1,
  model_name = "1",
  direction = "h"
)

Arguments

label_name

String. Name of the quantity that users want to extract the reference point from

ref_line

String. Reference point(s)

scale_amount

Number. A number to scale the y-axis values. If > 1, the magnitude of the scale amount will be added to the unit label (e.g. scale_amount = 1000 with a unit label of "1000s of lbs" will result in "thousands of 1000s of lbs")

Default: 1

model_name

String. Name of the model that will be present in the legend.

direction

String. Direction of reference line (either 'h' for horizontal or 'v' for vertical)

Options: Including, but not limited to: "msy", "unfished", "target"

Value

A ggplot2 geom_hline object for a reference point that can be added to a plot

Examples

## Not run: 
reference_line(dat, "biomass", "msy")

## End(Not run)

Export all figures and tables

Description

Export all figures and tables to Rda files within one function. This primary purpose of this function is to quickly export all available figures and tables. We recommend running individual plotting functions for greater customization of figures and tables.

Usage

save_all_plots(
  dat,
  interactive = FALSE,
  figures_tables_dir = getwd(),
  plot_recruitment_options = list(module = "TIME_SERIES"),
  plot_natural_mortality_options = list(module = "Natural_Mortality"),
  table_total_catch_options = list(module = "TIME_SERIES"),
  ...
)

Arguments

dat

Data frame or list. A tibble or named list of tibbles (input as list()) returned from convert_output.

If inputting a list of tibbles, the first tibble's reference point defined in ref_line is used to plot a reference line or calculate relative spawning biomass.

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

figures_tables_dir

Path. Directory where the rda files are saved, in "figures" and "tables" folders that are created if needed.

Default: the working directory (getwd())

plot_recruitment_options

List. List object of parameter values to pass directly to the plot_recruitment function. All default parameters for the plot_recruitment function, except for dat, can be overridden with this list object.

Default: list(module = "TIME_SERIES")

plot_natural_mortality_options

List. List object of parameter values to pass directly to the plot_natural_mortality_options function. All default parameters for the plot_natural_mortality_options function, except for dat, can be overridden with this list object.

Default: list(module = "Natural_Mortality")

table_total_catch_options

List. List object of parameter values to pass directly to the table_total_catch_options function. All default parameters for the table_total_catch_options function, except for dat, can be overridden with this list object.

Default: list(module = "TIME_SERIES")

... Additional list objects of parameter values to pass directly to corresponding plot or table functions. Parameter names should follow the naming convention ⁠{function_name}_options⁠. All default parameters, except for dat, of this function can be overridden with this list object. See example.

...

Arguments called from geom_line or geom_point

Details

The input is from an assessment model output file translated to a standardized output (convert_output).

Value

Rda files for each figure/table.

See Also

convert_output(), create_rda()

Examples

## Not run: 
save_all_plots(
  dat = example_data,
  plot_spawning_biomass_options = list(
    ref_line = "unfished"
  ),
  plot_abundance_at_age_options = list(
    scale_amount = 1,
    proportional = FALSE
  )
)

## End(Not run)
## Not run: 
save_all_plots(
   dat = example_data,
   figures_tables_dir = fs::path("outputs/figures"),
   plot_recruitment_options = list(
     module = "TIME_SERIES",
     unit_label = "mt"
   ),
   plot_spawning_biomass_options = list(
     ref_line = "unfished"     # customize reference line for spawning biomass plot
   ),
   plot_abundance_at_age_options = list(
     scale_amount = 1,         # custom scale for abundance-at-age plot
     proportional = FALSE      # don't proportionalize abundance-at-age
   ),
   plot_spr_options = list(
     ylab = "Fishing Intensity (1-SPR)/(1-SPR_ref)" # custom Y label for SPR plot
   ),
   plot_fishing_mortality_options = list(
     facet = "fleet",    # facet fishing mortality plot by "fleet"
     group = "fleet"     # group fishing mortality plot by "fleet"
   )
)

## End(Not run)

SS3 Simple stock assessment output

Description

Standardized output of a generic simple example of SS3 found from the r4ss repository examples. The raw output is converted to an R readable object using r4ss::ss_output then standardized using stockplotr::convert_output().

Usage

data(ss3_simple)

Format

A tibble (tbl_df, tbl, data.frame) with 38,195 rows and 35 variables:

label

Standard name for estimate or value name

estimate

Actual value of the label

year

Annual indexing value

fleet

Names of fleets or surveys indexed by the data

sex

Native reference to male, female, unknown, or none

area

Specified areas by the model

growth_pattern

Indexing column of data

uncertainty

Value of uncertainty associated with the label column

uncertainty_label

Uncertainty label or name associated with the label columns

module_name

Name of keyword (SS3) or list indexing in the original model output for tracking purposes

time

Time sometimes referenced in decimals to the year and month

era

"time" for current time series in model; "fore" representing the projected or forecasted years of the model

month

Month factor

season

Season usually associated with year

subseason

Subseason when used

birthseas

Birthseason found in SS3

initial

Initial input value in the model when available associated with the label column

likelihood

Likelihood value for the data point

platoon

Platoon also an SS3 indexing value

age

Age of fish

bio_pattern

Indexing column of data

settlement

Indexing column of data

morph

Indexing column of data

type

Indexing column of data

factor

Indexing column of data

part

Indexing column of data

kind

Indexing column of data

nsim

Indexing column of data

bin

Indexing column of data

age_a

Alternative age column

length_bins

Length bins for composition or other length based data

count

Indexing column of data

block

Indexing column of data

Source

r4ss Repository

Examples

data(ss3_simple)
head(ss3_simple)
unique(ss3_simple$label)

Biomass, abundance, and catch time series table

Description

Biomass, abundance, and catch time series table

Usage

table_biomass_abundance_catch(
  dat,
  biomass_label = NULL,
  abundance_label = NULL,
  catch_label = NULL,
  era = NULL,
  interactive = TRUE,
  group = NULL,
  method = "sum",
  module = NULL,
  label = NULL,
  model = NULL,
  make_rda = FALSE,
  tables_dir = getwd()
)

Arguments

dat

Data frame or list. A tibble or named list of tibbles (input as list()) returned from convert_output.

If inputting a list of tibbles, the first tibble's reference point defined in ref_line is used to plot a reference line or calculate relative spawning biomass.

biomass_label

String. Units for biomass

Default: NULL

abundance_label

String. Units for abundance

Default: NULL

catch_label

String. Units for catch

Default: NULL

era

String. Era of data.

Default: "time"

Options: "early", "time", "fore" (forecast), or NULL (all data)

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

group

A string of a single column that groups the data.

Set group = "none" to summarize data over all indexing values.

Default: NULL Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

method

A string describing the method of summarizing data when group is set to "none".

Default: "sum"

Options: "sum" or "mean"

module

Character vector. (Optional) Module name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

label

The label that will be chosen from the input file. If unspecified, the function will search the "label" column and use the first matching label in this ordered list: "landings_weight", "landings_numbers", "landings_expected", "landings_predicted", "landings".

Default: NULL

model

Character vector. (Optional) Model name found in dat$model. If selecting >1 model, place them in a vector like c("model1", "model2").

Default: NULL

If the interactive and >1 model is found, user will select the model in the console. @seealso filter_data()

make_rda

Logical. TRUE/FALSE; indicate whether to save the object and make an automated caption and alternative text in the form of an rda object. If TRUE, the rda will be exported to the folder indicated in the argument "figures_dir".

Default: FALSE.

tables_dir

The location of the folder containing the table rda files ("tables") that will be created if the argument make_rda = TRUE. Default: the working directory (getwd())

Details

There are options to return a gt::gt() object or export an rda object containing a gt-based table, caption, and LaTeX-based table.

Value

A table of biomass, abundance, catch, and spawning biomass.

See Also

convert_output(), filter_data(), process_table(), export_kqs(), insert_kqs(), create_rda()

Examples

table_biomass_abundance_catch(stockplotr::example_data)

table_biomass_abundance_catch(stockplotr::example_data,
  biomass_label = "kg",
  abundance_label = "eggs",
  catch_label = "kg",
  module = c("TIME_SERIES", "CATCH", "TIME_SERIES"),
  interactive = FALSE
)

Index of abundance table

Description

Index of abundance table

Usage

table_index(
  dat,
  era = NULL,
  interactive = TRUE,
  group = NULL,
  method = "sum",
  module = NULL,
  model = NULL,
  label = NULL,
  digits = 2,
  make_rda = FALSE,
  tables_dir = getwd()
)

Arguments

dat

Data frame or list. A tibble or named list of tibbles (input as list()) returned from convert_output.

If inputting a list of tibbles, the first tibble's reference point defined in ref_line is used to plot a reference line or calculate relative spawning biomass.

era

String. Era of data.

Default: "time"

Options: "early", "time", "fore" (forecast), or NULL (all data)

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

group

String. Single column that groups the data.

Set group = "none" to summarize data over all indexing values.

Default: NULL Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

method

String. Method for summarizing data when group is set to "none".

Default: "sum"

Options: "sum" or "mean"

module

Character vector. (Optional) Module name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

model

Character vector. (Optional) Model name found in dat$model. If selecting >1 model, place them in a vector like c("model1", "model2").

Default: NULL

If the interactive and >1 model is found, user will select the model in the console. @seealso filter_data()

label

String. The label that will be chosen from the input file. If unspecified, the function will search the "label" column and use the first matching label in this ordered list: "index_weight", "index_numbers", "index_expected", "index_predicted", "index".

Default: NULL

digits

Number. Numeric value indicating the number of digits values in the table will be rounded to.

Default: 2

make_rda

Logical. TRUE/FALSE; indicate whether to save the object and make an automated caption and alternative text in the form of an rda object. If TRUE, the rda will be exported to the folder indicated in the argument "figures_dir".

Default: FALSE.

tables_dir

Path. The location of the folder containing the generated table rda files ("tables") that will be created if the argument make_rda = TRUE.

Default: the working directory (getwd())

Details

The input is from an assessment model output file translated to a standardized output (convert_output). There are options to return a gt::gt() object or export an rda object containing a gt-based table, caption, and LaTeX-based table.

Value

A table of observed annual index of abundance plus error, stratified by fleet.

See Also

convert_output(), filter_data(), process_table(), export_kqs(), insert_kqs(), create_rda()

Examples

## Not run: 
table_index(dat)

table_index(
  dat,
  make_rda = TRUE,
  tables_dir = getwd()
)

## End(Not run)

Landed catch by fleet and year table

Description

Landed catch by fleet and year table

Usage

table_landings(
  dat,
  unit_label = NULL,
  era = NULL,
  interactive = TRUE,
  group = NULL,
  method = "sum",
  module = NULL,
  model = NULL,
  label = NULL,
  digits = 2,
  scale_amount = 1,
  make_rda = FALSE,
  tables_dir = getwd()
)

Arguments

dat

Data frame or list. A tibble or named list of tibbles (input as list()) returned from convert_output.

If inputting a list of tibbles, the first tibble's reference point defined in ref_line is used to plot a reference line or calculate relative spawning biomass.

unit_label

String. Abbreviated landings units

Default: NULL

era

String. Era of data.

Default: "time"

Options: "early", "time", "fore" (forecast), or NULL (all data)

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

group

String. Single column that groups the data.

Set group = "none" to summarize data over all indexing values.

Default: NULL Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL

method

String. Method for summarizing data when group is set to "none".

Default: "sum"

Options: "sum" or "mean"

module

Character vector. (Optional) Module name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

model

Character vector. (Optional) Model name found in dat$model. If selecting >1 model, place them in a vector like c("model1", "model2").

Default: NULL

If the interactive and >1 model is found, user will select the model in the console. @seealso filter_data()

label

String or vector of strings. The labels in the "label" column of dat to tabulate (e.g., "landings_predicted_weight"). If unspecified, the observed landings are used: the first of "landings_observed", "landings_observed_weight", "landings_observed_numbers", or "catch" (when dat also has "catch_predicted"), as in plot_landings(). When dat has none of these, the first label containing "landings" is used, with a message.

Default: NULL

digits

Number. Numeric value indicating the number of digits values in the table will be rounded to.

Default: 2

scale_amount

Number. A number to scale the y-axis values. If > 1, the magnitude of the scale amount will be added to the unit label (e.g. scale_amount = 1000 with a unit label of "1000s of lbs" will result in "thousands of 1000s of lbs")

Default: 1

make_rda

Logical. TRUE/FALSE; indicate whether to save the object and make an automated caption and alternative text in the form of an rda object. If TRUE, the rda will be exported to the folder indicated in the argument "figures_dir".

Default: FALSE.

tables_dir

Path. The location of the folder containing the generated table rda files ("tables") that will be created if the argument make_rda = TRUE.

Default: the working directory (getwd())

Details

The input is from an assessment model output file translated to a standardized output (convert_output). There are options to return a gt::gt() object or export an rda object containing a gt-based table, caption, and LaTeX-based table.

Value

A table ready of landed catch by fleet and year.

See Also

convert_output(), filter_data(), process_table(), export_kqs(), insert_kqs(), create_rda()

Examples

table_landings(stockplotr::example_data,
  interactive = FALSE
)

table_landings(
  stockplotr::example_data,
  unit_label = "kg",
  group = "fleet"
)

Create Projection Summary Table

Description

Generates a table showing assumed and projected years of Catch, SB, and F.

Usage

table_projections(
  dat,
  catch_label = NULL,
  spawning_biomass_label = NULL,
  interactive = TRUE,
  module = NULL,
  model = NULL,
  make_rda = FALSE,
  tables_dir = getwd()
)

Arguments

dat

Data frame or list. A tibble or named list of tibbles (input as list()) returned from convert_output.

If inputting a list of tibbles, the first tibble's reference point defined in ref_line is used to plot a reference line or calculate relative spawning biomass.

catch_label

String. Units for catch

Default: NULL

spawning_biomass_label

String. Units for spawning biomass

Default: NULL

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

module

Character vector. (Optional) Module name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

model

Character vector. (Optional) Model name found in dat$model. If selecting >1 model, place them in a vector like c("model1", "model2").

Default: NULL

If the interactive and >1 model is found, user will select the model in the console. @seealso filter_data()

make_rda

Logical. TRUE/FALSE; indicate whether to save the object and make an automated caption and alternative text in the form of an rda object. If TRUE, the rda will be exported to the folder indicated in the argument "figures_dir".

Default: FALSE.

tables_dir

Path. The location of the folder containing the generated table rda files ("tables") that will be created if the argument make_rda = TRUE.

Default: the working directory (getwd())

Details

We would like to thank Dan Hennen for sharing his projections table function code, which served as the foundation for this function.

Value

A formatted gt table object.

Examples

table_projections(
  dat = stockplotr::example_data,
  interactive = FALSE,
  module = "DERIVED_QUANTITIES"
)

table_projections(
  dat = stockplotr::example_data,
  interactive = FALSE,
  catch_label = "kg",
  spawning_biomass_label = "kg",
  module = c(NULL, "DERIVED_QUANTITIES", "DERIVED_QUANTITIES")
)

Catch (table) by fleet, gear type, sector

Description

Catch (table) by fleet, gear type, sector

Usage

table_total_catch(
  dat,
  unit_label = NULL,
  era = NULL,
  interactive = TRUE,
  module = NULL,
  model = NULL,
  scale_amount = 1,
  digits = 2,
  make_rda = FALSE,
  tables_dir = getwd()
)

Arguments

dat

Data frame or list. A tibble or named list of tibbles (input as list()) returned from convert_output.

If inputting a list of tibbles, the first tibble's reference point defined in ref_line is used to plot a reference line or calculate relative spawning biomass.

unit_label

String. Abbreviated catch units

Default: NULL

era

String. Era of data.

Default: "time"

Options: "early", "time", "fore" (forecast), or NULL (all data)

interactive

Logical. TRUE/FALSE; indicate whether the environment is interactive.

Default: FALSE

module

Character vector. (Optional) Module name found in dat$module_name. If selecting >1 module, place them in a vector like c("module1", "module2").

Default: NULL

If the interactive and >1 module_name is found, user will select the module_name in the console. @seealso filter_data()

model

Character vector. (Optional) Model name found in dat$model. If selecting >1 model, place them in a vector like c("model1", "model2").

Default: NULL

If the interactive and >1 model is found, user will select the model in the console. @seealso filter_data()

scale_amount

Number. A number to scale the y-axis values. If > 1, the magnitude of the scale amount will be added to the unit label (e.g. scale_amount = 1000 with a unit label of "1000s of lbs" will result in "thousands of 1000s of lbs")

Default: 1

digits

Number. Numeric value indicating the number of digits catch values in the table will be rounded to.

Default: 2

make_rda

Logical. TRUE/FALSE; indicate whether to save the object and make an automated caption and alternative text in the form of an rda object. If TRUE, the rda will be exported to the folder indicated in the argument "figures_dir".

Default: FALSE.

tables_dir

Path. The location of the folder containing the generated table rda files ("tables") that will be created if the argument make_rda = TRUE.

Default: the working directory (getwd())

Details

The input is from an assessment model output file translated to a standardized output (convert_output). There are options to return a gt::gt() object or export an rda object containing a gt-based table, caption, and LaTeX-based table.

Value

A table ready of landed catch by fleet and year.

See Also

convert_output(), filter_data(), process_table(), export_kqs(), insert_kqs(), create_rda()

Examples

table_total_catch(
  stockplotr::example_data,
  module = "TIME_SERIES"
)

table_total_catch(
  stockplotr::example_data,
  unit_label = "lbs",
  module = "TIME_SERIES",
  digits = 4,
  scale_amount = 100
)

Add NOAA theming to ggplot2 object

Description

The palette is from the 'viridis' package, which contains palettes distinguishable by those with color vision deficiency.

Usage

theme_noaa(discrete = TRUE, ...)

Arguments

discrete

Logical. TRUE/FALSE; indicate whether the color or fill aesthetic is discrete.

Default: TRUE

...

Arguments passed to ggplot2::theme().

Value

A list applying a theme to a ggplot2 object.

Examples

ggplot2::ggplot(
  data = OrchardSprays,
  ggplot2::aes(
    x = rowpos,
    y = decrease,
    color = treatment
  )
) +
  ggplot2::geom_point() +
  theme_noaa()

ggplot2::ggplot(
  data = OrchardSprays,
  ggplot2::aes(
    x = rowpos,
    y = decrease,
    color = decrease
  )
) +
  ggplot2::geom_point() +
  theme_noaa(discrete = FALSE)
## Not run: 
ggplot2::theme_set(stockplotr::theme_noaa())

## End(Not run)

Add NOAA formatting to a table

Description

Add NOAA formatting to a table

Usage

theme_table(x)

Arguments

x

Object. Table from gt, flextable, or kableExtra

Details

Currently, the function can format table objects from: flextable (flextable package, when installed), gt (gt), and kableExtra (kableExtra).

Value

Add the standard formatting for stock assessment reports for any table.

Examples

theme_table(cars |> gt::gt())
theme_table(cars |> kableExtra::kable())

SEDAR 55 South Atlantic Vermilion Snapper

Description

Standardized output of the 2018 South Atlantic Vermilion Snapper stock assessment produced from the Beaufort Assessment Model (BAM).

Usage

data(vermilion_snapper)

Format

A tibble (tbl_df, tbl, data.frame) with 35,881 rows and 35 variables:

label

Standard name for estimate or value name

estimate

Actual value of the label

year

Annual indexing value

fleet

Names of fleets or surveys indexed by the data

sex

Native reference to male, female, unknown, or none

area

Specified areas by the model

growth_pattern

Indexing column of data

uncertainty

Value of uncertainty associated with the label column

uncertainty_label

Uncertainty label or name associated with the label columns

module_name

Name of keyword (SS3) or list indexing in the original model output for tracking purposes

time

Time sometimes referenced in decimals to the year and month

era

"time" for current time series in model; "fore" representing the projected or forecasted years of the model

month

Month factor

season

Season usually associated with year

subseason

Subseason when used

birthseas

Birthseason found in SS3

initial

Initial input value in the model when available associated with the label column

likelihood

Likelihood value for the data point

platoon

Platoon also an SS3 indexing value

age

Age of fish

bio_pattern

Indexing column of data

settlement

Indexing column of data

morph

Indexing column of data

type

Indexing column of data

factor

Indexing column of data

part

Indexing column of data

kind

Indexing column of data

nsim

Indexing column of data

bin

Indexing column of data

age_a

Alternative age column

length_bins

Length bins for composition or other length based data

count

Indexing column of data

block

Indexing column of data

References

SEDAR (2018) (https://sedarweb.org/documents/sedar-55-stock-assessment-report-south-atlantic-vermilion-snapper/)

Examples

data(vermilion_snapper)
head(vermilion_snapper)
unique(vermilion_snapper$label)