Search code examples
rplotlytreemap

Treemap plot with plotly in R


I'm having issues doing a treemap with plotly in R. This is my data :

structure(list(items = c("Actifs", "Inactifs", "En emploi", "Chômeurs", 
"Halo du chômage", "Hors halo du chômage", "Recherche un emploi sans être disponible", 
"Ne recherche pas d'emploi mais est disponible", "Ne recherche pas d'emploi et n'est pas disponible"
), parents = c("", "", "Actifs", "Actifs", "Inactifs", "Inactifs", 
"Halo du chômage", "Halo du chômage", "Halo du chômage"), size = c("60", 
"40", "40", "20", "10", "30", "2", "5", "3")), row.names = c(NA, 
-9L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x000002129c6c1ef0>)

This is my code :

g4EMP <- plot_ly(
  data = data,
  type = "treemap",
  labels = ~items,
  values = ~size,
  parents = ~parents)

And this is the plot : enter image description here

As the items added are 100% of their parents, I don't understand why it's not using the full parent's square. Per example 'En emploi' + 'Chômeurs' = 'Actifs'. Both squares of the item 'Actifs' are using the full length but not the full width. For the item 'Inactif' the behaviour is reversed : squares takes the full width but not the full length.

How can I make the treemap squares use the full space ?

Thanks a lot in advance.


Solution

  • Here are a couple of options to achieve what you're looking for. I've added stringr::str_wrap to the objects so that they would string wrap, instead of shrinking the text. Depending on what you'll do with your map, you may want to increase, decrease or remove this part of the code.

    For your initial version of this plot, the reason that it doesn't fill is that you haven't told it to. You need the parameter branchvalues.

    (g4EMP <- plot_ly(
      data = df1,
      type = "treemap",
      labels = ~items %>% stringr::str_wrap(width = 15),
      branchvalues = "total",
      values = ~size,
      parents = ~parents)) 
    

    enter image description here

    If the values were just there to fill space, you may find this works better. You can actually read the text here. When you add value that sets the font size, as well.

    (g4EMP <- plot_ly(
      data = df1,
      type = "treemap",
      labels = ~items %>% stringr::str_wrap(width = 15),
      #values = ~size,
      parents = ~parents)) %>% 
      layout(uniformtext = list(minsize = 10))
    

    enter image description here

    Of course, since you can select any element of the treemap to get a closer look, you may not be worried about string wrapping or font size.

    enter image description here