Search code examples
rplot

Gradient legend in base


Earlier I asked about creating a gradient of n values in base graphics (LINK). Now I'd like to create a gradient legend that goes with it. My ideal would be something like ggplot2's gradient legends:

enter image description here

Here's some code similar to what I'm working with:

colfunc <- colorRampPalette(c("red", "blue"))
plot(1:20, 1:20, pch = 19, cex=2, col = colfunc(20))

enter image description here


Solution

  • Here is an example of how to build a legend from first principles using rasterImage from grDevices and layout to split the screen

    layout(matrix(1:2,ncol=2), width = c(2,1),height = c(1,1))
    plot(1:20, 1:20, pch = 19, cex=2, col = colfunc(20))
    
    legend_image <- as.raster(matrix(colfunc(20), ncol=1))
    plot(c(0,2),c(0,1),type = 'n', axes = F,xlab = '', ylab = '', main = 'legend title')
    text(x=1.5, y = seq(0,1,l=5), labels = seq(0,1,l=5))
    rasterImage(legend_image, 0, 0, 1,1)
    

    enter image description here