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

Jim Lemon jim at bitwrit.com.au
Mon Feb 8 07:09:34 CET 2010

On 02/08/2010 08:57 AM, 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?
Hi Kerim,
You can do this with color2D.matplot (plotrix) as well as with image or 
heatmap. Just pass the desired color vector as the "cellcolors" argument.


More information about the R-help mailing list