[R] specifying colors in a heatmap/image -like plot

David Winsemius dwinsemius at comcast.net
Mon Feb 8 00:13:11 CET 2010

On Feb 7, 2010, at 4:57 PM, kerimcan wrote:

> Hi,
> I have searched for a solution but I failed to find an answer. I am  
> hoping
> you may be able to help me.
> I have a data set where I have observations for a number of units (n  
> =~40)
> over a period of time (t =~100) and I have a variable (Z) that codes a
> categorical variable for each observation. I want to produce a 2D  
> plot where
> time is on the x-axis and units are on the y-axis. Then each block  
> on the
> 2-d plot should take a color depending on variable Z. Z is not  
> ordered so
> using a scale (like in heatmaps) does not make sense. In fact the  
> values of
> Z have meanings that are intuitively related to colors (e.g. Z=3 means
> involvement by the "United Nations" so I want its color to be  
> "blue"). Below
> is some code that gives an example of what I am aiming to do and why
> "heatmap" and "image" functions don't work for me. Thanks in advance  
> for
> your help.
> # Example: Suppose Z had 3 values (0,1,2) and I had 8 observations.
> hitmep <- matrix(c(0,2,1,0,2,1,1,0),2,4)
> # Graph 1:
> heatmap(hitmep2, Rowv =NA, Colv =NA, labrow =NULL, scale ="none")
> # Graph 2:
> image(t(hitmep2), axes =FALSE)
> # I like the layout of the plots. My problem with these is that I  
> don't want
> Z's values (0,1,2) to have colors on a scale. I want to specify, for
> example, 1="blue", 2="yellow" and 3="green". Do you know how to do  
> this?

Well, if you fix the name of your data vector and add the glaringly  
obvious color argument, it seems to "work":

hitmep2 <- matrix(c(0,2,1,0,2,1,1,0),2,4)

# Graph 1:
heatmap(hitmep2, col=c("red", "green", "blue"),Rowv =NA, Colv =NA,  
labrow =NULL, scale ="none")
# Graph 2:
image(t(hitmep2), col=c("red", "green", "blue"), axes =FALSE)

Unless I don't understand what you wanted... always a possibility.

David Winsemius, MD
Heritage Laboratories
West Hartford, CT

More information about the R-help mailing list