R/plots.R

Defines functions topSpecies vComTop vComSide vComTime

Documented in topSpecies vComSide vComTime vComTop

#' Create Bird's Eye View of Community
#'
#' Determine which species has the highest population size in every subpatch.
#' @param n A \code{S}x\code{L}x\code{W} array of population sizes over species, location, and subpatch.
#' @return A \code{L}x\code{W} matrix with the species ID of the highest population size in all subpatches.
#' @export
topSpecies <- function(n){
  L<-nrow(n[1,,]) # Length (number of patches)
  W<-ncol(n[1,,]) # Width (number of subpatches per patch)
  S<-nrow(n[,,1]) # Number of species
  tSpec <- matrix(NA,L,W) # Output matrix
  for(i in 1:L){
    for(j in 1:W){
      nij <- n[,i,j] # All species' populations in the subpatch
      if(sum(nij)>0){
        nij<-nij+runif(S,0,0.001) # Add a small amount of randomness to break ties
        tSpec[i,j]<-which.max(nij) # Which species has the highest population size
      }
    }
  }
  return(tSpec)
}

#' View Bird's Eye Plot of Community
#'
#' Create a heatmap that shows which species has the highest population size in all subpatches.
#' Each color represents a different species.
#' Species that are not highest in any spot will not show up.
#' @param n A \code{S}x\code{L}x\code{W} array of population sizes over species, location, and subpatch
#'
#' @export
vComTop<- function(n){
  tSpec<-topSpecies(n) # Create top view matrix
  S<-length(unique(c(tSpec[!is.na(tSpec)]))) # We only need colors for species that are represented
  image(tSpec,col=rainbow(S))
}

#' View Side Plot of Community
#'
#' Flatten all subpatches into a single patches and view population size of all species over space.
#' @param n A \code{S}x\code{L}x\code{W} array of population sizes over species, location, and subpatch
#' @param lwd Line width in plot
#'
#' @export
vComSide<-function(n,lwd=2){
  S<-nrow(n[,,1]) # All species with a row are represented
  nFlat<-sapply(1:S, function(s) rowSums(n[s,,])) # Flatten the subpatches in the community
  matplot(nFlat,type="l",lwd=lwd,lty=1,ylim=c(0,max(nFlat)),col=rainbow(S))
}

#' View Population Sizes over Time
#'
#' Plot all species' population sizes over a range of times.
#' @param N A \code{S}x\code{Y} matrix of population sizes over time
#' @param year1 Lower limit of time
#' @param year2 Upper limit of time
#' @param yearAd Adjust the year that is represented in the figure
#'
#' @export
vComTime <- function(N,year1=2,year2=NULL,yearAd=0){
  S<-nrow(N) # Number of species
  if(is.null(year2)){
    year2<-ncol(N) # If year2 is not specified, it is determined by the size of the matrix
  }
  matplot((1:(year2-year1+1)),t(N[,year1:year2]),type="l",lwd=2,lty=1,ylim=c(0,max(N)),col=rainbow(S))
}
gabackus/rcomms documentation built on Nov. 4, 2019, 1 p.m.