#This software is in the public domain because it contains materials that originally came from the U.S. Geological Survey, an agency of the #United States Department of Interior. For more information, see the official USGS copyright policy #Although this software program has been used by the U.S. Geological Survey (USGS), no warranty, expressed or implied, is made by the USGS #or the U.S. Government as to the accuracy and functioning of the program and related program material nor shall the fact of distribution #constitute any such warranty, and no responsibility is assumed by the USGS in connection therewith. #This software is provided "AS IS." ###The Libraries require(ggplot2) require(colorspace) require(gridExtra) require(ggthemes) require(RColorBrewer) require(dplyr) require(reshape) require(tibble) require(pls) require(calibrate) require(plsdepot) require(MuMIn) require(AICcmodavg) require(corrplot) require(sinkr) require(tidyverse) require(earlywarnings) require(nlme) require(car) require(sem) require(ape) require(caper) require(nlme) require(lavaan) require(piecewiseSEM) require(corrgram) require(relations) require(ellipse) require(QuantPsyc) require(effects) require(semPlot) ######The Data Threats <- read.csv("//Igsarfebfslacr3/Users/wthogmartin/My Documents/wet_migration/Monarch/Threats/FullThreatsData.csv") plot(Threats$year, Threats$area_pva, xlab="Year", ylab="log(Population Size (ha))", cex=3, ylim=c(0, 2.8)) ##data preparation, imputing missing values, example, not all imputations shown here MBBRmatrix <- as.matrix(Threats[,64:67]) # dput(MBBRmatrix) # dim(MBBRmatrix) pal <- colorRampPalette(c("blue", "cyan", "yellow", "red")) image(scale(MBBRmatrix), col=pal(100)) result_dineof <- dineof(scale(MBBRmatrix)) Xa <- result_dineof$Xa image(Xa, col=pal(100)) MBBRmatrix[22,2] sweep(result_dineof$Xa,MARGIN=2,attr(result_dineof$Xa, 'scaled:scale'),`*`) + sweep(result_dineof$Xa,MARGIN=2,attr(result_dineof$Xa, 'scaled:center'),"+") image(MBBRmatrix, col=pal(100)) pred <- sweep(result_dineof$Xa,MARGIN=2,attr(result_dineof$Xa, 'scaled:scale'),`*`) + sweep(result_dineof$Xa,MARGIN=2,attr(result_dineof$Xa, 'scaled:center'),"+") image(pred, col=pal(100)) ###If interested in global climate processes ENSO_DJF <- c(0.1, 0.9, -0.9, -0.5, 2.1, -1.4, -1.6, -0.7, -0.2, 0.9, 0.3, 0.7, -0.7, 0.7, -1.4, -0.7, 1.3, -1.3, -0.7, -0.4, -0.5, 0.6) #The first in the series is Dec '93 and Jan-Feb '94 ENSO_NDJ <- c(0.1, 1.0, -0.9, -0.5, 2.3, -1.4, -1.6, -0.8, -0.3, 1.1, 0.3, 0.7, -0.7, 0.9, -1.3, -0.7, 1.3, -1.4, -0.9, -0.2, -0.3, 0.6) #Data from http://www.cpc.ncep.noaa.gov/products/analysis_monitoring/ensostuff/ensoyears.shtml ENSO <- as.data.frame(cbind(1993:2014, ENSO_DJF, ENSO_NDJ)) colnames(ENSO)[1] <- "year" TolucaWeather <- merge(Threats[,68-79], ENSO, by="year", all.x=TRUE) str(TolucaWeather) MexW <- cor(TolucaWeather, use="pairwise.complete.obs") corrplot(MexW, type="upper", tl.cex = 0.75, tl.col="black", tl.srt = 45) ggplot(TolucaWeather,aes(x = year,y = OWmean_min_temp)) + xlim(1993,2014) + geom_point(colour="blue") + geom_path(colour="blue") + ylab("Mean minimum temperature (C)") Threats <- merge(Threats,TolucaWeather,by="year") str(Threats) Threats <- subset(Threats, select=-c(Month,Day)) ########### Start from here given the data associated with the paper Threats <- FullThreats <- read.csv("//Igsarfebfslacr3/Users/wthogmartin/My Documents/wet_migration/Monarch/Threats/FullThreatsData.csv") plot(Threats$year, Threats$area_pva, xlab="Year", ylab="log(Population Size (ha))", cex=3, ylim=c(0, 2.8)) Threatscorr <- cor(Threats) #with diff #corrplot(Threatscorr, method="ellipse") corrplot(Threatscorr[c(2,64:81),c(2,64:81)], method="ellipse") corrplot(Threatscorr[c(2,3:15),c(2,3:15)], method="ellipse") corrplot(Threatscorr[c(2,16:25),c(2,16:25)], method="ellipse") corrplot(Threatscorr[c(2,26:41),c(2,26:41)], method="ellipse") corrplot(Threatscorr[c(2,42:52),c(2,42:52)], method="ellipse") corrplot(Threatscorr[c(2,53:63),c(2,53:63)], method="ellipse") #############Partial Least Squares, Population Size head(Threats) str(Threats) ThreatsOrdered2 = Threats[ ,c(3,5:79, 2)] str(ThreatsOrdered2) ######### pls10 = plsreg1(ThreatsOrdered2[, 1:76], ThreatsOrdered2[, 77, drop = FALSE], crosval = TRUE) pls10$R2 plot(pls10, ylab="Component 2", xlab="Component 1", main="Trend") sum(pls10$R2) pls10$x.scores pls10$reg.coefs pls10$Q2 pls10$x.scores # X-scores (T-components) pls10$x.loads # X-loadings pls10$y.scores # Y-scores (U-components) pls10$y.loads # Y-loadings pls10$cor.xyt # score correlations pls10$raw.wgs # raw weights pls10$mod.wgs # modified weights pls10$std.coefs # standard coefficients pls10$reg.coefs # regular coefficients sum(pls10$R2) # R-squared pls10$R2 pls10$R2[1]/pls10$R2[2] pls10$R2Xy # explained variance of X-y by T pls10$y.pred # y-predicted pls10$resid # residuals pls10$T2 # T2 hotelling pls10$Q2 # Q2 cross validation; PRESS predicted residual sum of squares pls10$Q2[1,3]+pls10$Q2[2,3] pls10$x.loads[ order( pls10$x.loads[,1], pls10$x.loads[,2] ), ] pls10$x.loads[ order( pls10$x.loads[,2], pls10$x.loads[,1] ), ] plot(Threats$year, Threats$area_pva, xlab="Year", ylab="log(Population Size (ha))", cex=3, ylim=c(0, 2.8)) points(Threats$year, pls10$y.pred, cex=2, pch=19) #pls10$y.pred calculated below # Prepare file for export and minor manipulation in Excel # y2yloads10 <- data.frame(pls10$x.loads) # y2yloads10 <- rownames_to_column(y2yloads10, "VALUE") # colnames(y2yloads10)[1] <- "Variable" # y2yloadsmelt10 <- melt(y2yloads10) # colnames(y2yloadsmelt10)[2] <- "Component" # write.table(y2yloadsmelt10, file="//.../y2yloadsmelt10.csv") #Import component loadings file component_loadings <- read.csv("//Igsarfebfslacr3/Users/wthogmartin/My Documents/wet_migration/Monarch/Threats/component_loadings.csv") ####Added, in Excel, groups; winnowed to set of variables with >|0.15| in p1 or p2 component_loadings$Component <- as.character(component_loadings$Component) component_loadings$Component <- replace(component_loadings$Component, component_loadings$Component=="p1", "Component 1") component_loadings$Component <- replace(component_loadings$Component, component_loadings$Component=="p2", "Component 2") color_palette <- colorRampPalette(c("#3794bf", "#FFFFFF", "#df8640")) ggplot(component_loadings, aes(y=reorder(Variable, ID), x=Loading, fill=Component)) + geom_vline(xintercept=0, linetype=2, size=2, color="red") + geom_point(aes(colour = Group, size=abs(Loading))) + theme_light() + scale_colour_brewer(type = "qual", palette = 3, direction = -1) + #aes(y=reorder(Variable, abs(value)) theme(axis.text.x = element_text(angle=90, size = 14, vjust=0.5), legend.background = element_rect(fill = "white"), axis.title.y=element_text(margin=margin(0,20,0,0), size = 20), axis.title.x=element_text(margin=margin(20,0,0,0), size = 20), legend.text=element_text(size=15), strip.text.x = element_text(size=16), legend.key = element_blank(), plot.title = element_text(hjust = 0, vjust=2.12, size=20) ) + facet_grid(.~Component) + labs(y="Variable", x="Loading", size="Magnitude", colour="Type") + guides(fill=FALSE, colour = guide_legend(override.aes = list(size=5))) + ggtitle("Annual Population Size (ha)") ####circle of correlations explvar(pls10) plot(pls10, plottype = "scores", comps = 1:3, cex=0.5) ###Select subset with loadings |>0.15| plot(pls10$x.loads[,1], cex=2) text(pls10$x.loads[,1], rownames(pls10$x.loads), cex=0.6, pos=4, col="red") abline(h = c(-0.15, 0.15)) plot(pls10$x.loads[,2], cex=2) text(pls10$x.loads[,2], rownames(pls10$x.loads), cex=0.6, pos=4, col="blue") abline(h = c(-0.15, 0.15)) #######Relative Importance # require(AICcmodavg) # require(MuMIn) cor(Threats$glycum_N, Threats$glycum_S) cor(Threats$totalneon_N, Threats$totalneon_S) cor(Threats$TminJu_NC, Threats$TminJl_NC) cor(Threats$T70p4sum_NE, Threats$Tempp4avg_NE) cor(Threats$T70p4sum_NC, Threats$T70p4sum_NE) cor(Threats$Tempp4avg_NE, Threats$Tempp4avg_NC) cor(Threats$Ramirez.cumul, Threats$Vidal.cumul) BestSubset <- as.data.frame(cbind(Threats$Ramirez.cumul, Threats$glycum_N, Threats$totalneon_N, Threats$DC_S, Threats$apva_1yr, # Threats$Tempp4avg_NE, #Basically the same variable as T70p4sum_NE Threats$GDD_NC, Threats$T70p1sum_NC, Threats$T70p4sum_NE, Threats$TminAug_NC, Threats$MeanJ_NC, Threats$TminJu_NC)) BestSubsetcorr <- cor(BestSubset) #with diff corrplot(BestSubsetcorr, method="ellipse") BestSubsetscale <- data.frame(lapply(BestSubset, function(x) scale(x, center = TRUE, scale = TRUE))) colnames(BestSubsetscale) <- c("Ramirez.cumul" , "glycum_N" , "totalneon_N" , "DC_S" , "apva_1yr" , "GDD_NC" , "T70p1sum_NC" , "T70p4sum_NE" , "TminAug_NC" , "MeanJ_NC" , "TminJu_NC") BestSubsetscale["year"] <- c(1993:2014) str(BestSubsetscale) BestSubsetscale["area_pva"] <- Threats$area_pva GlobMod.FullNorth <- gls(area_pva ~ Ramirez.cumul + glycum_N + totalneon_N + DC_S + apva_1yr + GDD_NC + T70p1sum_NC + T70p4sum_NE + TminAug_NC + MeanJ_NC + TminJu_NC, na.action = na.fail, correlation=corAR1(form= ~year), data=BestSubsetscale) acf(GlobMod.FullNorth$res) summary(GlobMod.FullNorth) GlobMod.FullNorthLM <- lm(area_pva ~ Ramirez.cumul + glycum_N + totalneon_N + DC_S + apva_1yr + GDD_NC + T70p1sum_NC + T70p4sum_NE + TminAug_NC + MeanJ_NC + TminJu_NC, na.action = na.fail, data=BestSubsetscale) acf(GlobMod.FullNorthLM$res) autoregressivetest <- gls(area_pva ~ TminAug_NC , na.action = na.fail, correlation=corAR1(form= ~year), data=Threats) ModSetRes.FullNorthLM <- dredge(GlobMod.FullNorthLM, m.lim=c(0,3), extra = "R^2", rank = "BIC") AvgModSetRes.FullNorthLM <- model.avg(ModSetRes.FullNorthLM) AvgModSetRes.FullNorthLM$coefficients varlistNorth <- c( "Ramirez.cumul" , "glycum_N" , "totalneon_N" , "DC_S" , "apva_1yr" , "GDD_NC" , "T70p1sum_NC" , "T70p4sum_NE" , "TminAug_NC" , "MeanJ_NC" , "TminJu_NC") sort(varlistNorth) options(scipen=999) wt.Full_NorthLM <- summary(AvgModSetRes.FullNorthLM)$importance[c("Ramirez.cumul" , "glycum_N" , "totalneon_N" , "DC_S" , "apva_1yr" , "GDD_NC" , "T70p1sum_NC" , "T70p4sum_NE" , "TminAug_NC" , "MeanJ_NC" , "TminJu_NC")] subset(ModSetRes.FullNorthLM, delta <2) subset(ModSetRes.FullNorthLM, 1/8 < weight/max(ModSetRes.FullNorthLM$weight)) subset(ModSetRes.FullNorthLM, cumsum(ModSetRes.FullNorthLM$weight) <= .95) ModSetRes.FullNorthLM[1:3] pred.parms <- get.models(ModSetRes.FullNorthLM, subset= delta < 2) # predict values using each model, here were just using the # the example dataset, you could use a new dataset model.preds = sapply(pred.parms, predict, newdata = Threats) ModSetRes.FullNorthLM[1] bestmodel <- lm(area_pva ~ glycum_N + T70p1sum_NC + TminAug_NC, data = Threats, na.action = na.fail) summary(bestmodel) confint(bestmodel) outlierTest(bestmodel) # Bonferonni p-value for most extreme obs qqPlot(bestmodel, main="QQ Plot") #qq plot for studentized resid leveragePlots(bestmodel) #############Confounding Confounding <- lm(area_pva ~ Ramirez.cumul + glycum_N + totalneon_N + DC_S + apva_1yr + T70p1sum_NC + TminAug_NC, na.action = na.fail, data=BestSubsetscale) Confounding.dredge <- dredge(Confounding, m.lim=c(0,3), extra = "R^2", rank = "BIC") Confounding.average <- model.avg(Confounding.dredge) Confound.overwinter <- lm(area_pva ~ Ramirez.cumul + glycum_N + T70p1sum_NC + TminAug_NC, na.action = na.fail, data=Threats) Confound.neon <- lm(area_pva ~ glycum_N + totalneon_N + T70p1sum_NC + TminAug_NC, na.action = na.fail, data=Threats) Confound.dicamba <- lm(area_pva ~ glycum_N + DC_S + T70p1sum_NC + TminAug_NC, na.action = na.fail, data=Threats) Confound.density <- lm(area_pva ~ glycum_N + apva_1yr + T70p1sum_NC + TminAug_NC, na.action = na.fail, data=Threats) Confound.MT70P1 <- lm(area_pva ~ glycum_N + TminAug_NC, na.action = na.fail, data=Threats) Confound.MTminAug <- lm(area_pva ~ glycum_N + T70p1sum_NC, na.action = na.fail, data=Threats) con.overwinter <- lm(area_pva ~ Ramirez.cumul + T70p1sum_NC + TminAug_NC, na.action = na.fail, data=Threats) con.neon <- lm(area_pva ~ totalneon_N + T70p1sum_NC + TminAug_NC, na.action = na.fail, data=Threats) con.dicamba <- lm(area_pva ~ DC_S + T70p1sum_NC + TminAug_NC, na.action = na.fail, data=Threats) con.density <- lm(area_pva ~ apva_1yr + T70p1sum_NC + TminAug_NC, na.action = na.fail, data=Threats) summary(bestmodel) summary(Confound.overwinter) summary(Confound.neon) summary(Confound.dicamba) summary(Confound.density) beta <- as.data.frame(c(bestmodel$coefficients[2], Confound.overwinter$coefficients[3], Confound.neon$coefficients[2], Confound.dicamba$coefficients[2], Confound.density$coefficients[2])) rownames(beta) <- c("Best Model","w/ Overwinter\nForest Loss","w/ Neonicotinoids","w/ Dicamba", "w/ Previous Year's\n Abundance") colnames(beta) <- "slope" ggplot(mapping=aes(x="", y=beta$slope, label=rownames(beta))) + theme_bw() + geom_point(size=3)+geom_text(hjust=0, vjust=1.1) + xlab("Model") + ylab("Slope") + theme(panel.border = element_blank(),aspect.ratio=6/3) (bestmodel$coefficients[2]-Confound.overwinter$coefficients[3])/bestmodel$coefficients[2] (bestmodel$coefficients[2]-Confound.neon$coefficients[2])/bestmodel$coefficients[2] (bestmodel$coefficients[2]-Confound.dicamba$coefficients[2])/bestmodel$coefficients[2] (bestmodel$coefficients[2]-Confound.density$coefficients[2])/bestmodel$coefficients[2] (con.overwinter$coefficients[2]-Confound.overwinter$coefficients[2])/con.overwinter$coefficients[2] (con.neon$coefficients[2]-Confound.neon$coefficients[3])/con.neon$coefficients[2] (con.dicamba$coefficients[2]-Confound.dicamba$coefficients[3])/con.dicamba$coefficients[2] (con.density$coefficients[2]-Confound.density$coefficients[3])/con.density$coefficients[2] con.year <- lm(area_pva ~ year + T70p1sum_NC + TminAug_NC, data = Threats, na.action = na.fail) summary(con.year) plot(resid(con.year)~Threats$glycum_N) abline(lm(resid(con.year)~Threats$glycum_N), col="red") # regression line (y~x) lines(lowess(resid(con.year),Threats$glycum_N), col="blue") # lowess line (x,y) ############### # Influential Observations # Cook's D plot # identify D values > 4/(n-k-1) cutoff <- 4/((nrow(Threats)-length(bestmodel$coefficients)-2)) plot(bestmodel, which=4, cook.levels=cutoff) # Influence Plot #influencePlot(bestmodel, id.method="identify", main="Influence Plot", sub="Circle size is proportial to Cook's Distance" ) bestpred.parms <- get.models(ModSetRes.FullNorthLM, subset= delta < 2) bestmodel.preds = sapply(bestpred.parms, predict, newdata = BestSubsetscale) ####Figure 4 plot(0,0,xlim = c(1992,2015),ylim = c(0,2.7), xlab="Year", ylab="log(Population Size (ha))") points(Threats$year, bestmodel.preds, cex=2, pch=21, col="red", bg="red") #Reduced Model 1 # points(Threats$year, model.preds[,2], cex=2, pch=24, col="green", bg="green", type="o") #Reduced Model 2 # points(Threats$year, model.preds[,3], cex=2, pch=25, col="tan", bg="tan", type="o") #Reduced Model 3 points(Threats$year, pls10$y.pred, cex=2, pch=19) #PLSR predicted points(Threats$year, Threats$area_pva, cex=3, type="o") #Observed points(2005, 2.45, cex=3, type="o") points(2005, 2.3, cex=2, pch=19) points(2005, 2.15, cex=2, pch=21, col="red", bg="red") text(2007.12, 2.45, "Observed") text(2010.7, 2.3, "Partial Least Squares Prediction") text(2010.28, 2.15, "Best Subset Model Prediction") cor(Threats$area_pva,bestmodel.preds) cor(Threats$area_pva,pls10$y.pred) Threats$area_pva - bestmodel.preds sum(Threats$area_pva - bestmodel.preds) max(abs(Threats$area_pva - bestmodel.preds)) Threats$area_pva - pls10$y.pred sum(Threats$area_pva - pls10$y.pred) max(abs(Threats$area_pva - pls10$y.pred)) obspred <- cbind(Threats$area_pva, Threats$year, bestmodel.preds, pls10$y.pred) colnames(obspred) <- c("Observed", "Year", "Reduced 1", "Full 1") cormatrix1 <- cor(obspred) corrgram(obspred) corrplot(cormatrix1, method="ellipse") plotcorr(cormatrix1, type = "lower") cor.mtest <- function(mat, ...) { mat <- as.matrix(mat) n <- ncol(mat) p.mat<- matrix(NA, n, n) diag(p.mat) <- 0 for (i in 1:(n - 1)) { for (j in (i + 1):n) { tmp <- cor.test(mat[, i], mat[, j], ...) p.mat[i, j] <- p.mat[j, i] <- tmp$p.value } } colnames(p.mat) <- rownames(p.mat) <- colnames(mat) p.mat } # matrix of the p-value of the correlation p.mat <- cor.mtest(obspred) head(p.mat[, 1:4]) ############### coef_lmbeta <- lm.beta(bestmodel) BIC(bestmodel) gls1 <- gls(area_pva ~ glycum_N + T70p1sum_NC + TminAug_NC, correlation=corAR1(form= ~year), data=Threats) summary(gls1) intervals(gls1) BIC(gls1) acf(bestmodel$res) efflm1 <- allEffects(bestmodel) efflm1GLY <- effect("glycum_N", bestmodel) efflm1T70 <- effect("T70p1sum_NC", bestmodel) efflm1Tmin <- effect("TminAug_NC", bestmodel) plot(allEffects(bestmodel),"glycum_N", xlab="Cumulative Total Glyphosate Application (kg)", ylab="log(Winter Population Size (ha))", main="", rug=FALSE) plot(allEffects(bestmodel),"T70p1sum_NC", xlab="Total Number of Days in Period 1 >21"~degree~C, ylab="log(Winter Population Size (ha))", main="", rug=FALSE) plot(allEffects(bestmodel),"TminAug_NC", xlab="August Minimum Temperature"~degree~C, ylab="log(Winter Population Size (ha))", main="", rug=FALSE) fancy_scientific <- function(l) { # turn in to character string in scientific notation l <- format(l, scientific = TRUE) # quote the part before the exponent to keep all the digits l <- gsub("^(.*)e", "'\\1'e", l) # turn the 'e+' into plotmath format l <- gsub("e", "%*%10^", l) # return this as an expression parse(text=l) } ## Change effect object to dataframe efflm1GLY_df <- data.frame(efflm1GLY) efflm1T70_df <- data.frame(efflm1T70) efflm1Tmin_df <- data.frame(efflm1Tmin) ## Figure 3 ggplot(data=efflm1GLY_df) + geom_line(aes(glycum_N,fit), size=2, color="black") + theme_bw() + xlab("Cumulative Total Glyphosate Application (kg)") + ylab("log(Winter Population Size (ha))") + coord_cartesian(ylim=c(0, 2.5)) + theme(legend.position="bottom") + geom_ribbon(aes(ymin=lower, ymax=upper, x=glycum_N), alpha=0.3) + scale_x_continuous(labels=fancy_scientific) ggplot(data=efflm1T70_df) + geom_line(aes(T70p1sum_NC,fit), size=2, color="black") + theme_bw()+ xlab(expression("Total Number of Days in Period 1 >21"*~degree*"C")) + ylab("log(Winter Population Size (ha))") + coord_cartesian(ylim=c(0, 2.5)) + theme(legend.position="bottom") + geom_ribbon(aes(ymin=lower, ymax=upper, x=T70p1sum_NC), alpha=0.3) + scale_x_continuous(labels=fancy_scientific) ggplot(efflm1Tmin_df) + geom_line(aes(TminAug_NC,fit), size=2, color="black") + theme_bw()+ xlab(expression("August Minimum Temperature"*~degree*"C")) + ylab("log(Winter Population Size (ha))") + coord_cartesian(ylim=c(0, 2.5)) + theme(legend.position="bottom") + geom_ribbon(aes(ymin=lower, ymax=upper, x=TminAug_NC), alpha=0.3) ####With lines instead of ribbons ggplot(data=efflm1GLY_df) + geom_line(aes(glycum_N,fit), size=2, color="black") + theme_bw() + xlab("Cumulative Total Glyphosate Application (kg)") + ylab("log(Winter Population Size (ha))") + coord_cartesian(ylim=c(0, 2.5)) + theme(legend.position="bottom") + geom_line(aes(glycum_N,lower),linetype=1.5, size=2, color="dark gray") + geom_line(aes(glycum_N,upper),linetype=1.5, size=2, color="dark gray") + scale_x_continuous(labels=fancy_scientific) ggplot(data=efflm1T70_df) + geom_line(aes(T70p1sum_NC,fit), size=2, color="black") + theme_bw()+ xlab(expression("Total Number of Days in Period 1 >21"*~degree*"C")) + ylab("log(Winter Population Size (ha))") + coord_cartesian(ylim=c(0, 2.5)) + theme(legend.position="bottom") + geom_line(aes(T70p1sum_NC,lower),linetype=1.5, size=2, color="dark gray") + geom_line(aes(T70p1sum_NC,upper),linetype=1.5, size=2, color="dark gray") + scale_x_continuous(labels=fancy_scientific) ggplot(efflm1Tmin_df) + geom_line(aes(TminAug_NC,fit), size=2, color="black") + theme_bw()+ xlab(expression("August Minimum Temperature"*~degree*"C")) + ylab("log(Winter Population Size (ha))") + coord_cartesian(ylim=c(0, 2.5)) + theme(legend.position="bottom") + geom_line(aes(TminAug_NC,lower),linetype=1.5, size=2, color="dark gray") + geom_line(aes(TminAug_NC,upper),linetype=1.5, size=2, color="dark gray") require(scales) require(grid) require(gridExtra) require(gtable) require(cowplot) Figa <- ggplot(efflm1GLY_df)+geom_line(aes(glycum_N,fit),size=2, color="black") + theme_bw()+ xlab("Cumulative Total\nGlyphosate Application (kg)") + ylab("Winter Population Size (ha)") + coord_cartesian(ylim=c(0, 2.5)) + theme(legend.position="bottom",plot.margin=unit(c(1,1,2,0),"cm")) + geom_line(aes(glycum_N,lower),linetype=1.5, size=2, color="dark gray") + geom_line(aes(glycum_N,upper),linetype=1.5, size=2, color="dark gray") + scale_x_continuous(labels=fancy_scientific) Figb <- ggplot(efflm1T70_df)+geom_line(aes(T70p1sum_NC,fit),size=2, color="black") + theme_bw()+ xlab(expression("Total Number of Days\nin Period 1 >21"*~degree*"C")) + ylab("") + coord_cartesian(ylim=c(0, 2.5)) + theme(legend.position="bottom",plot.margin=unit(c(1,1,2,0),"cm"),axis.title.x = element_text(vjust=-0.5)) + geom_line(aes(T70p1sum_NC,lower),linetype=1.5, size=2, color="dark gray") + geom_line(aes(T70p1sum_NC,upper),linetype=1.5, size=2, color="dark gray") + scale_x_continuous(labels=fancy_scientific) Figc <- ggplot(efflm1Tmin_df)+geom_line(aes(TminAug_NC,fit),size=2, color="black") + theme_bw()+ xlab(expression("August Minimum\nTemperature"*~degree*"C")) + ylab("") + coord_cartesian(ylim=c(0, 2.5)) + theme(legend.position="bottom",plot.margin=unit(c(1,1,2,0),"cm")) + geom_line(aes(TminAug_NC,lower),linetype=1.5, size=2, color="dark gray") + geom_line(aes(TminAug_NC,upper),linetype=1.5, size=2, color="dark gray") Figag <- ggplotGrob(Figa) Figbg <- ggplotGrob(Figb) Figcg <- ggplotGrob(Figc) title.groba <- textGrob( label = "a", x = unit(0, "lines"), y = unit(0, "lines"), hjust = -6, vjust = 0, gp = gpar(fontsize = 16)) p1a <- arrangeGrob(Figag, top = title.groba) grid.arrange(p1a) title.grobb <- textGrob( label = "b", x = unit(0, "lines"), y = unit(0, "lines"), hjust = -6, vjust = 0, gp = gpar(fontsize = 16)) p1b <- arrangeGrob(Figbg, top = title.grobb) grid.arrange(p1b) title.grobc <- textGrob( label = "c", x = unit(0, "lines"), y = unit(0, "lines"), hjust = -6, vjust = 0, gp = gpar(fontsize = 16)) p1c <- arrangeGrob(Figcg, top = title.grobc) grid.arrange(p1c) #plot_grid(Figa, Figb, Figc, align = "v", ncol = 3, rel_heights = c(1/3, 1/3, 1/3)) grid.arrange(p1a, p1b, p1c, ncol=3) ###############Replace glyphosate with milkweed availability cor(x=Threats$glycum_N,y=Threats$milkweed.resource) cor(x=Threats$glycum_N,y=Threats$log.milkweed.resource) cor(x=Threats$glysum_N,y=Threats$milkweed.resource) cor(x=Threats$glysum_N,y=Threats$log.milkweed.resource) cor(x=Threats$year,y=Threats$milkweed.resource) cor(x=Threats$year,y=Threats$log.milkweed.resource) cor(x=Threats$glysum_N,y=Threats$area_pva) cor(x=Threats$glysum_N,y=Threatsw$apva_1yr) cor(y=Threats$area_pva,x=Threats$milkweed.resource) cor(y=Threats$area_pva,x=Threats$log.milkweed.resource) par(mfrow=c(2,2)) plot(log(Threats$glycum_N), log(Threats$milkweed.resource), ylab="log(Milkweed Resource)", xlab="log(Cumulative Glyphosate)", cex=3, cex.axis=1.5, cex.lab=1.5) plot(Threats$year, log(Threats$milkweed.resource), xlab="Year", ylab="log(Milkweed Resource)", cex=3, cex.axis=1.5, cex.lab=1.5) plot(x=log(Threats$milkweed.resource), y=Threats$area_pva, xlab="log(Milkweed Resource)", ylab="log(Overwinter Area (ha))", cex=3, cex.axis=1.5, cex.lab=1.5, ylim=c(0,3)) text(x=log(Threats$milkweed.resource), y=Threats$area_pva, labels=Threats$year, cex= 1, pos=3) plot(Threats$year, log(Threats$glycum_N), xlab="Year", ylab="log(Cumulative Glyphosate)", cex=3, cex.axis=1.5, cex.lab=1.5, ylim=c(min(log(Threats$glycum_N)),max(log(Threats$glycum_N)))) par(mfrow=c(1,1)) #Structural Equation Model semdata <- as.data.frame(cbind(Threats$area_pva,Threats$log.milkweed.resource,Threats$glycum_N)) colnames(semdata) <- c("area_pva", "milkweed.resource", "glycum_N") mod.sem2 = 'area_pva ~ milkweed.resource milkweed.resource ~ glycum_N' #options(scipen=999) options(scipen=0) model.sem2 = sem(mod.sem2, semdata, estimator = "MLM") parTable(model.sem2) summary(model.sem2, standardize=TRUE) summary(model.sem2, fit.measures = TRUE) parameterEstimates(model.sem2) coef(model.sem2) fitted(model.sem2) summary(model.sem2, standardize=FALSE) inspect(model.sem2, "rsquare") semPaths(model.sem2, intercepts = FALSE) mod.sem3 = 'area_pva ~ milkweed.resource + glycum_N milkweed.resource ~ glycum_N' model.sem3 = sem(mod.sem3, semdata, estimator = "MLM") parTable(model.sem3) summary(model.sem3, standardize=TRUE) #summary(model.sem2, standardize=FALSE) sem.model.fits(model.sem3) inspect(model.sem3, "rsquare") mod.sem4 = 'area_pva ~ milkweed.resource milkweed.resource ~ glycum_N + glycum_N^2' model.sem4 = sem(mod.sem4, semdata, estimator = "MLM") parTable(model.sem4) summary(model.sem4, standardize=TRUE) summary(model.sem4, fit.measures = TRUE) parameterEstimates(model.sem4) coef(model.sem4) fitted(model.sem4) summary(model.sem4, standardize=FALSE) inspect(model.sem4, "rsquare") semdata.l <- as.data.frame(cbind(Threats$area_pva,Threats$log.milkweed.resource,log(Threats$glycum_N))) colnames(semdata.l) <- c("area_pva", "milkweed.resource", "glycum_N") model.sem5 = sem(mod.sem2, semdata.l, estimator = "MLM") parTable(model.sem5) summary(model.sem5, standardize=TRUE) summary(model.sem5, fit.measures = TRUE) parameterEstimates(model.sem5) coef(model.sem5) fitted(model.sem5) summary(model.sem5, standardize=FALSE) inspect(model.sem5, "rsquare") mod.cfa2 <- cfa(mod.sem2, data=semdata) parTable(mod.cfa2) summary(mod.cfa2) corsem <- cor(semdata) plotcorr(corsem) summary(lm(semdata$milkweed.resource~semdata$glycum_N)) semdata2 <- as.data.frame(cbind(Threats$area_pva,Threats$log.milkweed.resource,Threats$glycum_N, Threats$Ramirez.cumul)) colnames(semdata2) <- c("area_pva", "milkweed.resource", "glycum_N", "Ramirez.cumul") mod2.sem = 'area_pva ~ milkweed.resource milkweed.resource ~ glycum_N area_pva ~ Ramirez.cumul' model2.sem = sem(mod2.sem, semdata2, estimator = "MLM") parTable(model2.sem) summary(model2.sem, standardize=TRUE) summary(model2.sem, fit.measures = TRUE) parameterEstimates(model2.sem) coef(model2.sem) fitted(model2.sem) summary(model2.sem, standardize=FALSE) inspect(model2.sem, "rsquare") semPaths(model2.sem, intercepts = FALSE)