# ============================================================ # Tutorial on drawing a CCA plot using ggplot2 # by Umer Zeeshan Ijaz (http://userweb.eng.gla.ac.uk/umer.ijaz) # ============================================================= abund_table<-read.csv("SPE_pitlatrine.csv",row.names=1,check.names=FALSE) #Transpose the data to have sample names on rows abund_table<-t(abund_table) meta_table<-read.csv("ENV_pitlatrine.csv",row.names=1,check.names=FALSE) #Just a check to ensure that the samples in meta_table are in the same order as in abund_table meta_table<-meta_table[rownames(abund_table),] library(vegan) sol<-cca(abund_table ~ ., data=meta_table) scrs<-scores(sol,display=c("sp","wa","lc","bp","cn")) #Check the attributes # > attributes(scrs) # $names # [1] "species" "sites" "constraints" "biplot" # [5] "centroids" #Extract site data first df_sites<-data.frame(scrs$sites,t(as.data.frame(strsplit(rownames(scrs$sites),"_")))) colnames(df_sites)<-c("x","y","Country","Latrine","Depth") #Draw sites p<-ggplot() p<-p+geom_point(data=df_sites,aes(x,y,colour=Country)) #Draw biplots multiplier <- vegan:::ordiArrowMul(scrs$biplot) # Reference: http://www.inside-r.org/packages/cran/vegan/docs/envfit # The printed output of continuous variables (vectors) gives the direction cosines # which are the coordinates of the heads of unit length vectors. In plot these are # scaled by their correlation (square root of the column r2) so that “weak” predictors # have shorter arrows than “strong” predictors. You can see the scaled relative lengths # using command scores. The plotted (and scaled) arrows are further adjusted to the # current graph using a constant multiplier: this will keep the relative r2-scaled # lengths of the arrows but tries to fill the current plot. You can see the multiplier # using vegan:::ordiArrowMul(result_of_envfit), and set it with the argument arrow.mul. df_arrows<- scrs$biplot*multiplier colnames(df_arrows)<-c("x","y") df_arrows=as.data.frame(df_arrows) p<-p+geom_segment(data=df_arrows, aes(x = 0, y = 0, xend = x, yend = y), arrow = arrow(length = unit(0.2, "cm"))) p<-p+geom_text(data=as.data.frame(df_arrows*1.1),aes(x, y, label = rownames(df_arrows))) # Draw species df_species<- as.data.frame(scrs$species) colnames(df_species)<-c("x","y") # Either choose text or points # p<-p+geom_text(data=df_species,aes(x,y,label=rownames(df_species))) p<-p+geom_point(data=df_species,aes(x,y,shape="Species"))+scale_shape_manual("",values=2) p<-p+theme_bw() pdf("CCA.pdf") print(p) dev.off()