Mode
Dark | Light
Email Me , μBlog me
or follow the feed  

Find a Color R

I always find difficult to pick up the right color in R. A good place to start is to call the demo for colors

demo(colors)

The demo defin a function called plotCol that is really handy to look for a color. The source code originally from Marius Hofert is

##' @title Comparing Colors
##' @param col
##' @param nrow
##' @param ncol
##' @param txt.col
##' @return the grid layout, invisibly
##' @author Marius Hofert, originally
plotCol <- function(col, nrow=1, ncol=ceiling(length(col) / nrow),
                    txt.col="black") {
    stopifnot(nrow >= 1, ncol >= 1)
    if(length(col) > nrow*ncol)
        warning("some colors will not be shown")
    require(grid)
    grid.newpage()
    gl <- grid.layout(nrow, ncol)
    pushViewport(viewport(layout=gl))
    ic <- 1
    for(i in 1:nrow) {
        for(j in 1:ncol) {
            pushViewport(viewport(layout.pos.row=i, layout.pos.col=j))
            grid.rect(gp= gpar(fill=col[ic]))
            grid.text(col[ic], gp=gpar(col=txt.col))
            upViewport()
            ic <- ic+1
        }
    }
    upViewport()
    invisible(gl)
}

After having call demo(colors) you can reuse it with your own arguments, and for example using grep on the built-in color names:

plotCol(colors()[grep("blue",colors())], nrow = 11)
## Loading required package: grid

plot of chunk bluecolors

Now you can pick the blue you prefer. That’s it!