[R] Colored boxes with values in the box

Jim Lemon jim at bitwrit.com.au
Sat Mar 24 07:39:07 CET 2007


Pappu, Kartik wrote:
> Hi all,
> 
> I have a x, y matrix of numbers (usually ranging from 0 to 40).  I need 
> to group these numbers and assign a color to each group (for example 0 
> to 15 - Blue, 16-30- Yellow, and 31-40- Red).  Then I need to draw a 
> rectangular matrix which contains X x Y boxes and each box has the  
> corresponding value from the input matrix and is also colored according 
> to which group (i.e red, yellow, or blue) that value falls into.
> 
> I have used the color2D.matplot function from the plotrix package, but 
> I cant quite figure out how to group the values to represent red blue 
> and yellow colors.
> 
Hi Kartik,
color2D.matplot isn't designed for this, but with a few tricks, I think 
you can get what you want. Try this:

xmat<-matrix(sample(0:40,100,TRUE),nrow=10)
# trick 1 - calculate values that give you the colors for ranges
color2D.matplot(floor(xmat/15+1),c(1,1,0),c(0,1,0),c(0,0,1))
# trick 2 - Use boxed.labels rather than the inbuild value display
boxed.labels(sort(rep(9.5:0.5,10)),rep(seq(9.5,0.5,by=-1),10),xmat)
# trick 3 - Use color.legend to show the group colors
color.legend(0,-2,3,-1.3,1:3,c("red","yellow","blue"))

You will have to wait until plotrix v2.2 is on CRAN as I am just 
submitting it, and the color.legend function, requested only a few weeks 
ago, is new to that version.

Jim



More information about the R-help mailing list