How do I generate a mapping from numbers to colors in R?

后端 未结 4 657
刺人心
刺人心 2021-02-15 13:45

In R, I can easily generate a color ramp, for example colorRampPalette. The following produces a sequence of five colors, from blue to red:

> mypal <- colo         


        
4条回答
  •  囚心锁ツ
    2021-02-15 14:21

    Here's a map2color function:

    map2color<-function(x,pal,limits=NULL){
        if(is.null(limits)) limits=range(x)
        pal[findInterval(x,seq(limits[1],limits[2],length.out=length(pal)+1), all.inside=TRUE)]
    }
    
    
     map2color(0:11,rainbow(200),limits=c(1,10))
    [1] "#FF0000FF" "#FF0000FF" "#FFA800FF" "#ADFF00FF" "#05FF00FF" "#00FFA3FF"
    [7] "#00ABFFFF" "#0003FFFF" "#A600FFFF" "#FF00B0FF" "#FF0008FF" "#FF0008FF"
     map2color(0:11,rainbow(200))
    [1] "#FF0000FF" "#FF8A00FF" "#EBFF00FF" "#61FF00FF" "#00FF29FF" "#00FFB3FF"
    [7] "#00BAFFFF" "#0030FFFF" "#5900FFFF" "#E300FFFF" "#FF0091FF" "#FF0008FF"
    
    
    mypal <- colorRampPalette( c( "blue", "red" ) )( 5 )
    x <- c( 1, 9, 8.5, 3, 3.4, 6.2 )
    map2color(x,mypal)
    "#0000FF" "#FF0000" "#FF0000" "#3F00BF" "#3F00BF" "#BF003F"
    

    I needed something like this to create a colorramp that would be consistent across different samples of data, so I added an xlim parameter. Thanks for the reminder of the findInterval function in your question.

提交回复
热议问题