Samuel
Samuel

Reputation: 441

Creating Treemap with distinct colors using hctreemap2 in R

I am trying to produce an interactive treemap in R using the highcharter-package (I love the package btw). It shall look like this (I don't even need the different levels)

https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/treemap-with-levels/

Sample code:

df <- data.frame(name = c("john", "jane", "herbert", "peter"),
                    bananas = c(10, 14, 6, 3))

hctreemap2(df, 
           group_vars = "name",
           size_var = "bananas")

I don't want the boxes to have gradient colors, but distinct, say red, yellow, green and blue. I'm getting better in understanding the highcharts-API and "translate" it to R-Code, but this really gives me a hard time.

I already found a work-arround, but I am looking for a better solution, as hc_add_series_treemap is deprecated.

p <- treemap(df,
             index="name",
             vSize="bananas",
             type="index")

highchart() %>%
    hc_add_series_treemap(p, 
                          layoutAlgorithm = "squarified")

So thanks for your help :)

Upvotes: 5

Views: 1262

Answers (1)

Samuel
Samuel

Reputation: 441

After spending an entire morning (I need this at my job) without finding a solution, coming to the end of finally posting this question here, only 10 minutes after asking it, I found a solution myself, trying something that just popped up in my head ^^

So here it goes:

hctreemap2(df, 
           group_vars = "name",
           size_var = "bananas") %>%
    hc_plotOptions(treemap = list(colorByPoint = TRUE)) %>%        #allows points in the same serie to have different colors
    hc_colors(c("#FFFF00", "#FF0000", "#0000FF", "#00AA00")) %>%   #with this we can set the colors, note: 1st color is given to first row in the data frame (not necessarily the biggest box)
    hc_colorAxis(dataClasses = color_classes(df$name)) %>%         #defines acc. to which variable, a box gets a distinct color
    hc_legend(enabled = FALSE)                                     #suppresses legend

It gives this: enter image description here We need three additional functions of the highcharter-package, but it works quite well!

Upvotes: 5

Related Questions