#' @import graphics
NULL

#' Default plot function for `pm` objects.
#'
#' Data are plotted with blue dots and fitted values with red dot.
#' A black arrow links a fitted value to its corresponding original value.
#' A barplot on the right side indicates the relative part of the global
#' variance affected to each factor.
#'
#' @author Eric Coissac
#' @author Christelle Gonindard-Melodelima
#' @export
plot.pm = function(x,
                   points.cex=0.6,
                   labels.cex=0.6,
                   arrow.length=0.05,
                   asp=1,
                   ...) {

  if (is.null(x$y))
    stop("Cannot plot procrust model without the y values")

  layout(matrix(c(1,1,1,1,2,3),nrow = 2))

  xlim = c(min(x$y[,1],x$fitted.values[,1]),
           max(x$y[,1],x$fitted.values[,1])
  )
  ylim = c(min(x$y[,2],x$fitted.values[,2]),
           max(x$y[,2],x$fitted.values[,2])
  )

  centers = (x$y + x$fitted.values)/2

  plot(x$y[,1:2],
       xlim=xlim,ylim=ylim,
       cex=points.cex,
       col="blue",
       asp=asp)

  points(x$fitted.values[,1:2],
         xlim=xlim,ylim=ylim,
         cex=points.cex,
         col="red")

  arrows(x$fitted.values[,1],m$fitted.values[,2],
         x$y[,1],m$y[,2],
         length = arrow.length,
         col="black")

  text(centers[,1],centers[,2],
       rownames(x$fitted.values),
       xlim=xlim,ylim=ylim,
       cex=labels.cex,
       col="black",
       pos=3)

  v = c(as.numeric(x$varpart),1-sum(x$varpart))
  names(v) = c(rownames(x$cov)[-1],"Residuals")
  barplot(v, las = 2)
}
