R/lsat_plot_trend_hist.R

Defines functions lsat_plot_trend_hist

Documented in lsat_plot_trend_hist

#' Create a histogram summarizing relative temporal changes in a spectral index
#' across all sample sites.   
#'
#' @param dt A data.table output from lsat_calc_trend()
#' @param xlim Numeric vector specifying the minimum and maximum values for the
#' histogram x-axis. 
#'
#' @return A histogram generated by ggplot2
#' @export lsat_plot_trend_hist
#'
#' @examples
#' data(lsat.example.dt)
#' lsat.dt <- lsat_format_data(lsat.example.dt)
#' lsat.dt <- lsat_clean_data(lsat.dt)
#' lsat.dt <- lsat_calc_spectral_index(lsat.dt, 'ndvi')
#' # lsat.dt <- lsat_calibrate_rf(lsat.dt, band.or.si = 'ndvi', write.output = F)
#' lsat.pheno.dt <- lsat_fit_phenological_curves(lsat.dt, si = 'ndvi') 
#' lsat.gs.dt <- lsat_summarize_growing_seasons(lsat.pheno.dt, si = 'ndvi')
#' lsat.trend.dt <- lsat_calc_trend(lsat.gs.dt, si = 'ndvi.max', yrs = 2000:2020)
#' lsat_plot_trend_hist(lsat.trend.dt)

lsat_plot_trend_hist <- function(dt, xlim = c(-30,30)){
  
  dt <- data.table::data.table(dt)
  si <- first(dt$si)
  period <- unlist(strsplit(dt$trend.period, split = 'to')[1])
  first.yr <- period[1]
  last.yr <-  period[2]
  
  # histogram of vegetation greenness trends
  hist <- ggplot2::ggplot(dt, ggplot2::aes(total.change.pcnt, fill=ggplot2::after_stat(x))) +
  ggplot2::geom_histogram(bins = 50, size = 0.25, color = 'gray20') +
  ggplot2::scale_fill_gradient2(low="darkgoldenrod4", mid='white', high="darkgreen", 
                                limits = xlim, midpoint = 0) +
  ggplot2::labs(y = 'Number of sample sites', 
                x = paste0("Relative change in Landsat ", 
                           gsub('.MAX', 'max', toupper(si)),
                           ' from ', first.yr, ' to ', last.yr, ' (%)')) +
  ggplot2::theme_bw() + 
  ggplot2::theme(legend.position = 'none', 
                 axis.text=ggplot2::element_text(size=12), 
                 axis.title=ggplot2::element_text(size=14)) + 
  ggplot2::xlim(xlim[1], xlim[2])

  hist

}
logan-berner/lsatTS documentation built on Oct. 21, 2024, 12:23 a.m.