I create a palette with RColorBrewer
and want to set names for the colors from the ordered factor vector. I get variables from a data frame with variables <- unique(df$column)
so different columns give different number of variables
library(RColorBrewer)
variables <- c("PR", "PD", "C", "SD", "CR")#as example
variables <- ordered(variables, levels = c("C", "CR", "PR", "SD", "PD"))
test_pal <- brewer.pal(length(variables), "Accent"); names(test_pal) <- variables
and it assigns names to colors according to the 'original' sequence in the vector
> test_pal
PR PD C SD CR
"#7FC97F" "#BEAED4" "#FDC086" "#FFFF99" "#386CB0"
but I want in the order set, like this:
C CR PR SD PD
"#7FC97F" "#BEAED4" "#FDC086" "#FFFF99" "#386CB0"
CodePudding user response:
ordered
will create an ordered factor variable, but it does not order your vector (it only sets an order in the levels). You have to order
or sort
the factor (not just the levels) when you assign the new names:
names(test_pal) <- sort(variables)
#names(test_pal) <- variables[order(variables)]
# C CR PR SD PD
#"#7FC97F" "#BEAED4" "#FDC086" "#FFFF99" "#386CB0"