Colorbar from custom colorRampPalette

后端 未结 4 2037
南旧
南旧 2020-11-30 03:59

I have defined a colorRampPalette:

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

How can I plot a color

相关标签:
4条回答
  • 2020-11-30 04:38

    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

    0 讨论(0)
  • 2020-11-30 04:45

    Make a matrix, use image with some axes parameters...

    my.colors = colorRampPalette(c("light green", "yellow", "orange", "red"))
    z=matrix(1:100,nrow=1)
    x=1
    y=seq(3,2345,len=100) # supposing 3 and 2345 are the range of your data
    image(x,y,z,col=my.colors(100),axes=FALSE,xlab="",ylab="")
    axis(2)
    

    image legend

    0 讨论(0)
  • 2020-11-30 04:51

    I know this is a very old question, and the answers are all great. I just wanted to point out that you could just smooth the color bar from levelplot.

    Make some fake data and a color gradient

    mat = matrix(rnorm(400,1,1), ncol=20)
    grad = rev(rainbow(1000, start=rgb2hsv(col2rgb('green'))[1], 
           end=rgb2hsv(col2rgb('blue'))[1]))
    

    Make the plot and specify breaks in the color bar

    levelplot(mat, col.regions=grad, colorkey = list(at=seq(0,max(mat),length.out=400)))
    

    This functionality to levelplot may have been added long after all you folks came up with sweet workaround solutions.

    0 讨论(0)
  • 2020-11-30 05:01

    colorbar.plot() from the fields package is a standard solution. Many folks will be looking here for solutions that place the legend outside of the standard plot area or the original x/y range. This limitation of colorbar.plot() is easily overcome by:

    1. plotting your image(),
    2. expanding the size of the plot device with par(pin = c(width, length))
    3. calling colorbar.plot() using original x and y values

    Because the area of the plot device is now expanded, the legend will appear outside of the original image() plot. Experimenting with x and y values lands the legend anywhere you wish. The gradient legend can be horizontal or vertical using standard argument options.

    0 讨论(0)
提交回复
热议问题