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

后端 未结 4 658
刺人心
刺人心 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.

    0 讨论(0)
  • 2021-02-15 14:22

    The simplest thing I can think of is discretizing your variable x with cut and then using the resultant factor to index a color Palettes like heat.colors or cm.colors

    f <- function(x,n=10){
        heat.colors(n)[cut(x,n)]
    }
    

    see ?heat.colors for more details of Palettes.

    This function will give you are color vector corresponding to x of varying granularity proportional to n.

    0 讨论(0)
  • 2021-02-15 14:30

    My colourscheme package on R-Forge does that:

    https://r-forge.r-project.org/projects/colourscheme/

    its primary purpose is to create functions that map numeric values (not just integer colour numbers) to colours. The vignette is the best documentation once you've got it installed.

    0 讨论(0)
  • 2021-02-15 14:31

    You can try

    > colorRampPalette(c('blue', 'red'))(length(x))[rank(x)]
    [1] "#0000FF" "#FF0000" "#CC0032" "#3300CC" "#660099" "#990065"
    
    0 讨论(0)
提交回复
热议问题