Is there's a way to redefine or add named colors in a project?

I'm working on graphs for a manuscript. I like to use my own custom color palette which is a mix between my own custom colors and colors used by The Economist. I usually store these colors in a list and extract the value with $ or a custom function. E.g.:

.colors = list(
  opal = "#e64e53",
  azure = "#3d89c3"
)
    
get_colors <- function(...) {
  unname(.colors[c(...)])
}

# get the colors

.colors$opal

get_colors("opal", "azure")

Instead of doing it like this, I'm wondering if there's a way to redefine or add named colors (as the ones returned by colors()) locally in a project so that typing "opal" returns "#e64e53" directly.

The main advantages would be a bit less typing and have the actual color being displayed as a background for the name, which can be quite convenient to experiment with different color combinations by simply typing their name side by side.

I looked at colors() definition

colors
function (distinct = FALSE) 
{
    c <- .Call(C_colors)
    if (distinct) 
        c[!duplicated(t(col2rgb(c)))]
    else c
}

so its driven by compiled C code; therefore I'd expect a change would require changes to base R source code; This is probably unlikely to happen, though technically R is open source and you can compile your own version; but I wouldnt go that route.

Its a compromise but a path of least resistance to use a tool to find the nearest built-in color and simply adopt that instead ? plotrix::color.id() does that and told me that your opal and azure are closest to "tomato2" and "steelblue" ; the azure match I think is indistinguishable, the opal is a slight shade off but perhaps close enough for you.

1 Like

Thanks. Too bad there's no easy way to redefine colors. I like your suggestion to find the closest colors to the ones I use. I might not be able to do that for all my colors but probably for the main ones.

Since it's RStudio and not R that allows you to preview colors in the editor, there may be a way to have RStudio allow the kind of customization you ask about. This approach wouldn't allow the direct use of a user-defined name in R code, but you could use .colors["opal"] instead of just "opal" and still see the corresponding color. I'm curious about this myself, so I opened a feature request here:

2 Likes