Search code examples
rgradient

Gradient of n colors ranging from color 1 and color 2


I often work with ggplot2 that makes gradients nice (click here for an example). I have a need to work in base and I think scales can be used there to create color gradients as well but I'm severely off the mark on how. The basic goal is generate a palette of n colors that ranges from x color to y color. The solution needs to work in base though. This was a starting point but there's no place to input an n.

 scale_colour_gradientn(colours=c("red", "blue"))

I am well aware of:

brewer.pal(8, "Spectral") 

from RColorBrewer. I'm looking more for the approach similar to how ggplot2 handles gradients that says I have these two colors and I want 15 colors along the way. How can I do that?


Solution

  • colorRampPalette could be your friend here:

    colfunc <- colorRampPalette(c("black", "white"))
    colfunc(10)
    # [1] "#000000" "#1C1C1C" "#383838" "#555555" "#717171" "#8D8D8D" "#AAAAAA"
    # [8] "#C6C6C6" "#E2E2E2" "#FFFFFF"
    

    And just to show it works:

    plot(rep(1,10),col=colfunc(10),pch=19,cex=3)
    

    enter image description here