在 R 中绘制树状图

Treemap plot with plotly in R

我在 R 中使用 plotly 制作树状图时遇到问题。 这是我的数据:

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>)

这是我的代码:

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

这是情节:

由于添加的项目是其 parent 的 100%,我不明白为什么它没有使用完整的 parent 的方块。例如 'En emploi' + 'Chômeurs' = 'Actifs'。项目 'Actifs' 的两个正方形都使用全长而不是全宽。 对于项目 'Inactif',行为是相反的:正方形占据整个宽度而不是整个长度。

如何让树状图方块使用完整的 space?

非常感谢。

这里有几个选项可以满足您的需求。我已将 stringr::str_wrap 添加到对象中,以便它们进行字符串换行,而不是缩小文本。根据您要对地图执行的操作,您可能希望增加、减少或删除这部分代码。

对于这个情节的初始版本,它没有填满的原因是你没有告诉它填满。您需要参数 branchvalues.

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

如果这些值只是用来填充 space,您可能会发现这样效果更好。您实际上可以在此处阅读文本。当您添加设置字体大小的 value 时。

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

当然,由于您可以 select 树状图的任何元素来仔细查看,您可能不必担心字符串换行或字体大小。