R/plot_fits_sp.R

Defines functions plot_fits_sp

Documented in plot_fits_sp

#' Plot surplus production model fits
#'
#' This function plots surplus production model fits and exports to a PDF.
#'
#' @param output SP model output
#' @param plotdir Path for plot export
#' @param plotname Plot name (must end with ".pdf)
#' @return PDF with production model fits
#' @export
plot_fits_sp <- function(output, b_col, sp_col,
                         plotdir=getwd(), plotname="TMB_fits.pdf"){

  # Stocks do
  stocks_do <- sort(unique(output$data$stockid))

  # Data to plot
  data_plot <- output$data %>%
    # Rename columns
    rename("b_scaled"=b_col, "sp_scaled"=sp_col)

  # Build lines
  #############################

  # Params
  results <- splink::get_results(output)
  spfits <- results %>%
    select(stockid, param, est) %>%
    spread(key="param", value="est")

  # Create lines
  sp_lines <- purrr::map_df(1:nrow(spfits), function(x){

    # Parameters
    stockid <- spfits$stockid[x]
    r <- spfits$r[x]
    k <- spfits$B0[x]
    p <- 0.2

    # Simulate data
    b <- seq(0, 1, 0.01)
    sp <- r/p * b * (1-(b/k)^p)

    # Record production
    z <- data.frame(stockid=stockid,
                    b_scaled=b,
                    sp_scaled=sp)

  })

  # Plot data
  #############################

  # Base theme
  my_theme <-  theme(axis.text=element_text(size=6),
                     axis.title=element_text(size=8),
                     strip.text=element_text(size=6),
                     plot.title=element_blank(),
                     # Gridlines
                     panel.grid.major = element_blank(),
                     panel.grid.minor = element_blank(),
                     panel.background = element_blank(),
                     axis.line = element_line(colour = "black"))

  # Plot data
  g <- ggplot(data_plot, aes(x=b_scaled, y=sp_scaled)) +
    geom_point(pch=21, size=2, color="grey30") +
    # Line
    geom_line(data=sp_lines, mapping=aes(x=b_scaled, y=sp_scaled), color="black", size=0.7) +
    # Labels
    labs(x="Abundance (scaled)", y='Surplus production (scaled)') +
    # Horizontal guide
    geom_hline(yintercept=0, linetype="dotted", color="black") +
    # Theme
    theme_bw() + my_theme +
    # Paginate
    ggforce::facet_wrap_paginate(~stockid, scales="free_y", ncol = 4, nrow = 7, page=1)

  # Number of pages
  npages <- ggforce::n_pages(g)

  # Loop through pages
  pdf(file.path(plotdir, plotname), paper= "letter", width = 7.5, height=11)
  for(i in 1:npages){
    print(g + ggforce::facet_wrap_paginate(~stockid, scales="free_y", ncol = 4, nrow = 7, page=i))
  }
  dev.off()


}
cfree14/splink documentation built on Dec. 19, 2021, 2:57 p.m.