[R] add a color band

Jim Lemon jim at bitwrit.com.au
Mon Nov 4 11:55:17 CET 2013


On 11/04/2013 08:09 PM, Alaios wrote:
> Hi Jim Lemon,
> thanks for the help, I appreciate this.
>
> right now my code looks like.
>
>
> par(mar=c(5,4,4,5))
> color2D.matplot(data,1,c(0,1),0,xlab="",ylab="Spans",
> main="color.scale",xrange=c(-110,-50),border=NA,axes=F)
> color.legend(357,30,370,100,seq(-110,-50,length.out=13),
> align="rb",rect.col=color.scale(1:13,1,c(0,1),0),
> gradient="y")
>
>
> my major problem now is that the
> a. text in the color bar is squeezed so -50 overlaps with -60 and so on
> b. for some reason the color bar sometimes (the same code is called for
> all the data matrices I have) is misaligned in different positions each time
>
> Could you please also help me with those two?
>
Hi Alex,
For your first question, I would simply extend the color legend vertically:

color.legend(357,30,370,150,seq(-110,-50,length.out=13),
  align="rb",rect.col=color.scale(1:13,1,c(0,1),0),
  gradient="y")

For the second one, you obviously have different dimensions for the data 
matrices. So, let's step through a method for getting the legend 
position and size from the plot itself. As I have written a few times 
previously, par("usr") gives you the dimensions of the plot in user 
units. For the example above, the dimensions were:

x - 0->351
y - 0->200

With a bit of arithmetic, you can work out that the legend positions in 
the above are:

xylim<-par("usr")
# x position of lower left corner of legend
xl<-xylim[2]+diff(xylim[1:2])*0.017
# y position of lower left corner
yb<-xylim[3]+diff(xylim[3:4])*0.15
# x position of upper right corner of legend
xr<-xylim[2]+diff(xylim[1:2])*0.054
# y position of upper right corner
yt<-xylim[3]+diff(xylim[3:4])*0.75

Having these lines means that you can get the position and size of the 
legend about right from the information provided by par("usr") even if 
you change the number of cells in the matrix passed to color2D.matplot. 
Then you would call:

color.legend(xl,yb,xr,yt,seq(-110,-50,length.out=13),
  align="rb",rect.col=color.scale(1:13,1,c(0,1),0),
  gradient="y")

unless of course you wanted to change the values in the scale markings. 
I'll leave that for you to work out.

Jim



More information about the R-help mailing list