R/plotProfileDendrogram.R

Defines functions plotProfileDendrogram

## TODO: sanity checking and debug mode
## TODO: move more hard-coded geom elements to arguments / heuristics
## NOTE: distance matrix should be scaled to approximately {0,1}
# x: SPC object
# clust: a hierachical clustering object from cluster package agnes() or diana()
plotProfileDendrogram <- function(x, clust, scaling.factor=0.01, width=0.1, y.offset=0.1, dend.y.scale= max(clust, na.rm=TRUE) * 2, debug=FALSE, ...) {
  
  # sanity check: must be either agnes or diana object
  if(! inherits(clust, c('agnes','diana')))
    stop('clust must be an object generated by diana() or agnes()')
  
  # sanity check: length and contents of individual names in d should match ids in x
  d.ids <- dimnames(as.matrix(d))[[1]]
  x.ids <- profile_id(x)
  if( (length(d.ids) != length(x.ids)) | ! all(d.ids == x.ids) )
    stop('inconsistent SoilProfileCollection and distance matrix!')
  
  # debugging information
  if(debug) {
    par(mar=c(5,5,5,5))
    print(data.frame(d=d.ids, x=x.ids))
  }
  
  # convert to hclust, then phylo object
  d.hclust <- as.hclust(clust)
  dend <- as.phylo(d.hclust)
  
  # setup plot and add dendrogram
  plot(dend, cex=0.8, direction='up', y.lim=c(dend.y.scale, 0), x.lim=c(0.5, length(x)+1), show.tip.label=FALSE)
  
  # get the last plot geometry
  lastPP <- get("last_plot.phylo", envir = .PlotPhyloEnv)
  
  # vector of indices for plotting soil profiles below leaves of dendrogram
  new_order <- d.hclust$order
  
  # plot the profiles, in the ordering defined by the dendrogram
  # with a couple fudge factors to make them fit
  plot(x, plot.order=new_order, add=TRUE, width=width, scaling.factor=scaling.factor, y.offset=max(lastPP$yy) + y.offset, ...)
  
  if(debug) {
    grid()
    axis(1, las=1, at=1:length(x))
    axis(2, las=1)
    # abline(h=max(lastPP$yy) + y.offset, col='red')
  }
  
}

Try the sharpshootR package in your browser

Any scripts or data that you put into this service are public.

sharpshootR documentation built on May 2, 2019, 4:46 p.m.