2d color gradient plot in R

后端 未结 4 522
既然无缘
既然无缘 2020-12-09 20:25

I want to produce a 2d color gradient rectangle like the ones in the picture below on the right hand side. How can I do this in R? Using colorRamp or RCol

4条回答
  •  被撕碎了的回忆
    2020-12-09 20:52

    Thanks for commenting on my post - I'm glad it generated some discussion. Here's a minimal code to achieve the plots on the upper right - I'm sure there's other more efficient ways to do it... But this works without need for other libraries, and should be easy enough to follow... you can change saturation and alpha blending by playing with the max_sat and alpha_default variables...

    #define extremes of the color ramps
    rampk2r <- colorRampPalette(c(rgb(  0/255,   0/255,   0/255), rgb(218/255,   0/255,   0/255)))
    rampk2g <- colorRampPalette(c(rgb(  0/255,   0/255,   0/255), rgb(  0/255, 218/255,   0/255)))
    
    # stupid function to reduce every span of numbers to the 0,1 interval
    prop <- function(x, lo=0, hi=100) {
        if (is.na(x)) {NA}
        else{
            min(lo,hi)+x*(max(lo,hi)-min(lo,hi))
        }
    }
    
    rangepropCA<-c(0,20)
    rangepropCB<-c(0,20)
    
    # define some default variables
    if (!exists('alpha_default')) {alpha_default<-1} # opaque colors by default
    if (!exists('palette_l')) {palette_l<-50} # how many steps in the palette
    if (!exists('max_sat')) {max_sat<-200} # maximum saturation
    colorpalette<-0:palette_l*(max_sat/255)/palette_l # her's finally the palette...
    
    # first of all make an empy plot
    plot(NULL, xlim=rangepropCA, ylim=rangepropCB, log='', xaxt='n', yaxt='n', xlab='prop A', ylab='prop B', bty='n', main='color field');
    # then fill it up with rectangles each colored differently
    for (m in 1:palette_l) {
        for (n in 1:palette_l) {
            rgbcol<-rgb(colorpalette[n],colorpalette[m],0, alpha_default);
            rect(xleft= prop(x=(n-1)/(palette_l),rangepropCA[1],rangepropCA[2]) 
                ,xright= prop(x=(n)/(palette_l),rangepropCA[1],rangepropCA[2])
                ,ytop= prop(x=(m-1)/(palette_l),rangepropCB[1],rangepropCB[2]) 
                ,ybottom= prop(x=(m)/(palette_l),rangepropCB[1],rangepropCB[2])
                ,col=rgbcol
                ,border="transparent"
            )
        }
    }
    # done!
    

提交回复
热议问题