Skip to content
Prev 332561 / 398506 Next

Package(s) for making waffle plot-like figures?

On 11/02/2013 10:35 AM, Zhao Jin wrote:
Hi Zhao,
By beginning with a 10x10 matrix of NA values and then replacing some of 
them with a color, I think you can do what you want. First you need a 
function to fill one corner of your matrix with values, leaving the rest 
uncolored (i.e. NA):

fill.corner<-function(x,nrow,ncol) {
  xlen<-length(x)
  if(nrow*ncol > xlen) {
   newmat<-matrix(NA,nrow=nrow,ncol=ncol)
   xside<-1
   while(xside*xside < xlen) xside<-xside+1
   row=1
   col=1
   for(xindex in 1:xlen) {
    newmat[row,col]<-x[xindex]
    if(row == xside) {
     col<-col+1
     row<-1
    }
    else row<-row+1
   }
   return(newmat)
  }
  cat("Too many values in x for",xrow,"by",xcol,"\n")
}

Then you have to massage your data frame into 37 smaller data frames, 
create matrices with the values and colors to display on your 37 waffle 
plots:

library(plotrix)
# get an "alphabet" of colors
alphacol<-rainbow(18)
# the actual values in the plotted matrix don't matter
fakemat<-matrix(1:100,nrow=10)
# pick off the positions one by one
for(pos in 1:37) {
  posdf<-zjdat[zjdat$position == pos,]
  for(res in 1:dim(posdf)[1]) {
   if(res == 1)
    rescol<-rep(alphacol[as.numeric(posdf$residue[res])],
    posdf$ratio[res])
   else
    rescol<-c(rescol,rep(alphacol[as.numeric(posdf$residue[res])],
    posdf$ratio[res]))
  }
  if(!is.null(resmat<-fill.corner(rescol,10,10)))
   color2D.matplot(fakemat,border="lightgray",cellcolors=resmat,
    yrev=FALSE,main=c(pos,length(resmat)))
}

That might get you started. In fact, I might even write a waffle plot 
function for plotrix.

Jim