Search code examples
rplotlytreemap

Treemap (plotly) color intensity according to a variable


I made a treemap using the treemap package, in which the area of each box is related to the Valor variable and the color of each box is related to the escala variable, which was created from the Nota variable. In red to gray scale, as shown below:

library(data.table)
library(tidyverse)
library(treemap)
url <- "https://raw.githack.com/fsbmat-ufv/stackExchange/main/df2.csv"
df <- fread(url)
df$scale <- scale(df$Nota)
treemap(df, index = "MUNICIPIO", vSize = "Valor", vColor = "scale",
        type = "value", palette = "-RdGy", lowerbound.cex.labels = 0.1,
        title = "Treemap Rio de Janeiro",
        overlap.labels=0.05)

insert image description here

I would like to create the same treemap with plotly, or a very similar one, such that the area of the boxes are related to the variable Valor and the color is in intensity related to the variable Nota or the variable escala. I created the code below but I was not successful. Does anyone have a suggestion?

color <- colorRamp(c("red", "gray"))
colorlist <- rgb(color((df$Nota)/max(df$Nota)), max = 255)
df %>%
  plotly::plot_ly(labels = ~ MUNICIPIO,
                  values = ~Valor,
                  parents = ~NA,
                  type = 'treemap',
                  hovertemplate = "City: %{label}<extra></extra>") %>%
  plotly::layout(title = "Patent scape",
                 colorway = colorlist)

insert image description here


Solution

  • As your code requires an external download I modified this example. Please check the following:

    library(datasets)
    library(plotly)
    library(data.table)
    
    DT <- data.table(labels = LETTERS,
                     values = 1:26)
    
    unique_values_count <- length(unique(DT$values))
    
    palette <- colorRampPalette(c("red", "gray"), alpha = TRUE)(unique_values_count)
    assigned_colors <- c(palette[cut(DT$values, unique_values_count)])
    
    fig <- plot_ly(
      data = DT,
      type = "treemap",
      labels =  ~ labels,
      parents = ~ NA,
      values =  ~ values,
      marker = list(colors = assigned_colors)
    )
    fig
    

    result

    Also check my related post here.