###################################################################################################################
# This R script creates figure 4 from Berner and Law (2015)
# Author: Logan Berner, OSU
# Date: Nov 4th, 2015
###################################################################################################################
rm(list=ls())
setwd('')
require(lattice)
require(latticeExtra)
require(RColorBrewer)
load('workspaces/rw_climate_cors.1994.2013.RDATA')

# set stip to light gray
sb <- trellis.par.get("strip.background") 
sb[["col"]][1] <- "lightgray"
trellis.par.set("strip.background", sb) 

#rw.cmi.frac.cors$month <- factor(rw.cmi.frac.cors$month, labels=month.abb)
rw.clim.species.cor.cnt$species <- factor(rw.clim.species.cor.cnt$species, levels=sp.oi, labels = c('Western juniper','Ponderosa pine','Grand fir'))
rw.cmi.frac.cors <- subset(rw.clim.species.cor.cnt, cor.cat=='pos' & clim.par=='cmi')
rw.cmi.frac.cors <- droplevels(rw.cmi.frac.cors)

my.cols <- c(brewer.pal(9, "PuBu"), "black")

#my.cols <- c(brewer.pal(9, "PuBu"), "black")
my.cols <- c('white','gray90','gray85','gray80','gray70','gray60','gray50','gray40','gray30','gray20',"black")
#pdf('figures/fig4_rw_cmi_cor_frac_species.pdf', width = 3.15, height =6)
jpeg('figures/fig5_rw_cmi_cor_frac_species.jpg', width = 3.15, height = 6, units='in', res=600)
levelplot(cor.pcnt.avg~lag+month|species, rw.cmi.frac.cors, layout=c(1,3,1), 
          #col.regions = rev(terrain.colors(20)), 
          at= do.breaks(c(-0.5,100),10),
          col.regions=my.cols,
          colorkey=list(space='top'),
          #panel=panel.2dsmoother, args=list(span=0.13),
          panel=panel.2dsmoother, args=list(span=0.10),
          main=list('% of trees with positive \n RWI-CMI correlation (1964-2013)', cex=1),
          scales=list(x=list(at=c(1,seq(6,36,6)),rot=90), y=list(at=seq(1,12,2), labels=month.abb[seq(1,12,2)]), alternating=F),
          ylab="Month",
          xlab="Time lag (number of months)",
          par.settings = list(strip.background=list(col="lightgrey"))
)
dev.off()
# 
# pdf('figures/fig4_rw_cmi_cor_frac_species.pdf', width = 6.65, height = 9)
# #jpeg('figures/fig5_rw_cmi_cor_frac_species.jpg', width = 6, height = 9, units='in', res=600)
# levelplot(cor.pcnt.avg~lag+month|species, rw.cmi.frac.cors, layout=c(1,3,1), 
#           #col.regions = rev(terrain.colors(20)), 
#           at= do.breaks(c(-0.5,100),10),
#           col.regions=my.cols,
#           colorkey=list(space='top'),
#           panel=panel.2dsmoother, args=list(span=0.13),
#           main='% of trees with positive RWI-CMI correlation (1964-2013)',
#           scales=list(x=list(at=seq(1,36,3)), y=list(at=1:12, labels=month.abb)),
#           ylab="Month",
#           xlab="Time lag (number of months)",
#           par.settings = list(strip.background=list(col="lightgrey"))
# )
# dev.off()
