4

I am struggling to figure how to customise colors. Here is an example :

vtree(mtcars, "cyl am",rootfillcolor="yellow")

How to customise colors of "cyl" and am.

I want to cyl : 4="blue", 6="green",8="yellow"

and to am 0="pink" and 1="brown"

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Nic
  • 143
  • 5

1 Answers1

2

You could specify the sorted colors:

library(vtree)
vtree(mtcars, "cyl am", rootfillcolor = "yellow",
      specfill = list(
          cyl = c("blue", "green", "yellow"),
          am = c("pink", "brown")
          )
     )

enter image description here

Or if you need a proper mapping, you could use something like this:

helper <- function(x, colmap) {
 if (!all(x %in% names(colmap))) {
   stop("you did not map all values to colors")
 }
  colmap[as.character(sort(unique(x)))]
}

amcol <- c("0" = "pink", "1" = "brown")
amcol2 <- c("1" = "brown", "0" = "pink")
cylcol <- c("4" = "blue", "6" = "green", "8" = "yellow") 

vtree(mtcars, "cyl am", rootfillcolor = "yellow", 
      specfill = list(cyl = helper(mtcars$cyl, cylcol),
                      am = helper(mtcars$am, amcol)))

vtree(mtcars, "cyl am", rootfillcolor = "yellow", 
      specfill = list(cyl = helper(mtcars$cyl, cylcol), 
                      am = helper(mtcars$am, amcol2)))

Of course this could be further improved so that mtcars$cyl and mtcars$am are automatically derived.

Johannes Titz
  • 972
  • 6
  • 11
  • 1
    great but it doesn't seem to take values into account but order. When I change order like `am = list("1" = "brown","0" = "pink") ` 0 become "brown". – Nic Apr 18 '23 at 15:03
  • Oh sorry, I did not realize this. I modified the answer and included a helper function to handle the mapping. – Johannes Titz Apr 19 '23 at 11:13