Search code examples
rplotcluster-analysis

Plot clprofiles function without hitting enter each time


I'm looking for a way to get all plots of the variables without hitting enter each time. if you're familiar with this function clprofiles of Kprototype, you know this message Hit <Return> to see next plot:, i want to see all plots of the variables at once. Now i've tried doing a 'for loop' after the instruction clprofiles(kpres, df) :

    clprofiles(kpres, df)
for (i in 1:length(t)) {
  print("
        ")

}

But it's useless. Thanks for your help.


Solution

  • In that case, you will have to override the default behaviour of clprofiles. Add this new function my.clprofiles to your script:

    my.clprofiles <- function(object, x, vars = NULL, col = NULL){
      library(RColorBrewer)
      if(length(object$cluster) != nrow(x)) stop("Size of x does not match cluster result!")
      if(is.null(vars)) vars <- 1:ncol(x)
      if(!is.numeric(vars)) vars <- sapply(vars, function(z) return(which(colnames(x)==z)))
      if(length(vars) < 1) stop("Specified variable names do not match x!")
      if(is.null(col)){
        k <- max(unique(object$cluster))
        if(k > 2)  col <- brewer.pal(k, "Set3")
        if(k == 2) col <- c("lightblue","orange")
        if(k == 1) col <- "lightblue"
      }
      clusids <- sort(unique(object$cluster)) 
      if(length(col) != max(clusids)) warning("Length of col should match number of clusters!")
    
      #REMOVE PROMPT
      #par(ask=TRUE)
    
      par(mfrow=c(2,2))
    
      for(i in vars){
        if(is.numeric(x[,i])){
          boxplot(x[,i]~object$cluster, col = col, main = colnames(x)[i])
          legend("topright", legend=clusids, fill = col)
        } 
        if(is.factor(x[,i])){
          tab <- table(x[,i], object$cluster)
          for(j in 1:length(object$size)) tab[,j] <- tab[,j]/object$size[j]
          barplot(t(tab), beside = TRUE, main = colnames(x)[i], col = col)
        } 
      }
      invisible()
    }
    

    And then you can call it once without having to hit Enter:

    my.clprofiles(kpres,x)
    

    which produces the same plot as in the first answer.