[R] Adding legend

David Winsemius dwinsemius at comcast.net
Wed Jun 3 21:34:36 CEST 2015


On Jun 3, 2015, at 9:39 AM, John Wasige wrote:

> ​Hello community,
> 
> Could somebody help on how I can
> ​add ​
> a legend to my heatmap plot. I need to know what values from the data do
> colours ( "red","yellow", "yellowgreen","lightblue4") represent from the
> data. The script is here below and attached is the test dataset. Thanks for
> your help.
> 

No data available but for your question refer first to ?heatmap where you are told that the col argument gets passed to `image`. In ?image you are told (in the zlim section of Details) that:

zlim	
the minimum and maximum z values for which colors should be plotted, defaulting to the range of the finite values of z. Each of the given colors will be used to color an equispaced interval of this range. The midpoints of the intervals cover the range, so that values just outside the range will be plotted.

You can, of course, look at the code for an example of how to reliably build such a mapping of a range to the number of colors. The Details section also has advice for the col parameter if you wanted a wider range of colors.

The gplots::heatmap.2 function is used widely and has legend (where it is called color key) settings.
-- 
David.

> Hohn
> 
> ########## script
>> 
> ​library(wq)
> 
> setwd("D:/data")
> Pmid <- read.csv('D:/data/MyData1.csv')
> 
> Pmid.ts = ts(Pmid,start=c(1981,1),end=c(1995,12),frequency = 12)
> 
> # convert time series into vector
> Pmid.ts.df = ts2df(Pmid.ts, mon1 = 1, addYr = F, omit = FALSE)
> # convert vector into data matrix
> Pmid.ts.dm = data.matrix(Pmid.ts.df)
> # covnert data matrix into heatmap
> Pmid_heatmap <- heatmap(Pmid.ts.dm, Rowv=NA, Colv=NA, col =
> c("red","yellow", "yellowgreen","lightblue4"), scale="row")
> # you can transpose the dataframe if you want to flip the image
> Pmid_heatmap <- heatmap(t(Pmid.ts.dm), Rowv=NA, Colv=NA, col =
> c("red","yellow", "yellowgreen","lightblue4"), scale="column")
> 
> ##############
> 
> # example plot
> jpeg(filename = "heatMap01.jpg",
>     width = 800, height = 400, units = "px", pointsize = 6,
>     quality = 100, bg = "white", res = 144, type = "cairo")
> heatmap(t(Pmid.ts.dm), Rowv=NA, Colv=NA, col = c("red","yellow",
> "yellowgreen","lightblue4"), scale="column", legend(40,
> 2,legend=c("Title","","Group1","Group2"), fill=c("white", "white",
> "green","black"), border=FALSE, bty="n", y.intersp = 0.7, cex=0.7))
> dev.off()​
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list