Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
575 views
in Technique[技术] by (71.8m points)

r - Colorbar from custom colorRampPalette

I have defined a colorRampPalette:

my.colors = colorRampPalette(c("light green", "yellow", "orange", "red"))

How can I plot a colorbar "legend" item for it, preferably using only the base packages? I am after a rectangle filled with that color gradient.

What I am really after is a way to produce the same type of legend (color bar) that is plotted with a "raster" raster:

require(raster)
plot(raster("myfile.tif"), legend=T)

I need to be able to place this on top of another plot.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I made a nice flexible function awhile ago to do this.

# Function to plot color bar
color.bar <- function(lut, min, max=-min, nticks=11, ticks=seq(min, max, len=nticks), title='') {
    scale = (length(lut)-1)/(max-min)

    dev.new(width=1.75, height=5)
    plot(c(0,10), c(min,max), type='n', bty='n', xaxt='n', xlab='', yaxt='n', ylab='', main=title)
    axis(2, ticks, las=1)
    for (i in 1:(length(lut)-1)) {
     y = (i-1)/scale + min
     rect(0,y,10,y+1/scale, col=lut[i], border=NA)
    }
}

Then you can do something like:

> color.bar(colorRampPalette(c("light green", "yellow", "orange", "red"))(100), -1)

enter image description here

More examples at: http://www.colbyimaging.com/wiki/statistics/color-bars


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...