Question

I'm trying to use a named character vector to hold a custom color palette, so I can say, e.g. palette['red'] instead of repeating "#dc322f" all over the place.

However, I don't seem to be able to use an element of that vector as an argument to par() (though it can be used elsewhere).

Here's an example. It'll create a graph with green dots, but the par() call fails and the background is white. Note that I can set parameters using the palette vector from within the plot() call:

> palette <- c('#002b36','#dc322f','#859900')
> names(palette) <- c('black','red','green')
> par(bg=palette['red'])                                                                                                                                
Warning message:
In par(bg = palette["red"]) : "bg.red" is not a graphical parameter
> plot(1:10,1:10,col=palette['green'])
> # (White graph with green dots appears) 

When I use a named numeric vector, however, it works:

> palette <- 1:3                                                                                                                                          
> names(palette) <- c('black','red','green')                                                                                                              
> par(bg=palette['red'])                                                                                                                             
> # (no error here -- it worked.)
> plot(1:10,1:10,col=palette['green'])
> # (Red graph with green dots appears)

I am fairly new to R, and it seems that I might be missing something fundamental. Any idea what's happening here?

Was it helpful?

Solution

Use unname, so that the item passed to par is just the character vector defining the colour, not a named element

palette <- c('#002b36','#dc322f','#859900')
names(palette) <- c('black','red','green')
par(bg=unname(palette['red'])) 
plot(1:10,1:10,col=palette['green'])

enter image description here

As to why?

within par, if all the arguments are character vectors then

if (all(unlist(lapply(args, is.character)))) 
            args <- as.list(unlist(args))

The way as.list(unlist(args)) works if args is a named character vector is

args <- list(bg = palette['red'])
as.list(unlist(args))
$bg.red
[1] "#dc322f"

and bg.red is not a valid par.

if the line were something like

setNames(as.list(unlist(args, use.names = F)), names(args))

then it might work in some cases (although not if any of the named elements of arg had length >1)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top