Named character vectors and par () in R-graphics

I am trying to use a named character symbol to save a custom color palette, so I can say for example. the ['red'] palette instead of repeating "# dc322f" everywhere.

However, it seems that I cannot use an element of this vector as an argument for par() (although it can be used elsewhere).

Here is an example. It will create a graph with green dots, but the par () call will fail and the background will be white. Note that I can set the parameters using the palette vector from 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) 

However, when I use a named number vector, 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 new to R, and it seems like I can skip something fundamental. Any idea what is going on here?

+4
source share
1 answer

Use unname , so the element passed to par is just a character vector that defines color, 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

What up to what?

inside par , if all arguments are character vectors, then

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

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

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

and bg.red not valid par .

if the string was something like

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

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

+4
source

Source: https://habr.com/ru/post/1440664/


All Articles