boxmoe_header_banner_img

Hello! 欢迎来到悠悠畅享网!

文章导读

使用 Plotly.js 创建 Treemap 图:理解层级结构的配置


avatar
作者 2025年9月8日 10

使用 Plotly.js 创建 Treemap 图:理解层级结构的配置

本文旨在帮助开发者理解并掌握如何使用 plotly.js 库创建 Treemap 图,重点讲解如何通过 labels 和 parents 数组配置 Treemap 的层级结构。通过清晰的示例代码和详细的解释,读者将能够轻松地创建自定义的 Treemap 图,并根据需求调整其层级关系。

理解 Plotly.JS Treemap 的数据结构

Plotly.js 的 Treemap 图使用一种特定的数据结构来定义层级关系。这种结构依赖于两个关键的数组:labels 和 parents。labels 数组包含了 Treemap 中所有节点的名称,而 parents 数组则定义了每个节点的父节点。理解这两个数组之间的关系是创建自定义 Treemap 的关键。

labels 数组:定义所有节点

labels 数组是一个字符串数组,它包含了 Treemap 中所有需要显示的节点名称。节点的顺序并不重要,重要的是 parents 数组中与之对应的元素能够正确地指向其父节点。

例如,如果我们想要创建一个包含 “root”、”topItem”、”one”、”two”、”three”、”something”、”thing” 和 “whatever” 这些节点的 Treemap,labels 数组应该如下所示:

labels: ["root", "topItem", "one", "two", "three", "something", "thing", "whatever"]

parents 数组:定义层级关系

parents 数组与 labels 数组一一对应,用于定义每个节点的父节点。parents 数组中的每个元素都是一个字符串,表示对应 labels 数组中节点的父节点名称。对于根节点(没有父节点),parents 数组中对应的元素应该为空字符串 “”。

继续上面的例子,如果我们想要构建以下层级关系:

  • “root” 是根节点
  • “topItem” 是 “root” 的子节点
  • “one”、”two” 和 “three” 是 “topItem” 的子节点
  • “something” 是 “one” 的子节点
  • “thing” 和 “whatever” 是 “two” 的子节点

那么 parents 数组应该如下所示:

parents: ["", "root", "topItem", "topItem", "topItem", "one", "two", "two"]

注意:

使用 Plotly.js 创建 Treemap 图:理解层级结构的配置

Check for AI

在论文、电子邮件等中检测AI书写的文本

使用 Plotly.js 创建 Treemap 图:理解层级结构的配置85

查看详情 使用 Plotly.js 创建 Treemap 图:理解层级结构的配置

  • parents[0] 是 “”,因为 “root” 是根节点。
  • parents[1] 是 “root”,因为 “topItem” 的父节点是 “root”。
  • parents[2]、parents[3] 和 parents[4] 都是 “topItem”,因为 “one”、”two” 和 “three” 的父节点都是 “topItem”。
  • parents[5] 是 “one”,因为 “something” 的父节点是 “one”。
  • parents[6] 和 parents[7] 都是 “two”,因为 “thing” 和 “whatever” 的父节点都是 “two”。

完整示例代码

将 labels 和 parents 数组组合在一起,就可以创建一个完整的 Plotly.js Treemap 图:

<!DOCTYPE html> <html> <head>   <title>Plotly Treemap Example</title>   <script src="https://cdn.plot.ly/plotly-2.20.0.min.js"></script> </head> <body>    <div id='chart'></div>    <script>     const data = [{       type: "treemap",       labels: ["root", "topItem", "one", "two", "three", "something", "thing", "whatever"],       parents: ["", "root", "topItem", "topItem", "topItem", "one", "two", "two"]     }];      Plotly.newPlot('chart', data);   </script>  </body> </html>

将以上代码保存为 HTML 文件并在浏览器中打开,就可以看到生成的 Treemap 图。

添加数值信息

除了层级结构,Treemap 图通常还需要显示每个节点对应的数值信息。这可以通过 values 数组来实现。values 数组与 labels 数组一一对应,表示每个节点的值。

例如,我们可以为上面的例子添加一些随机的数值:

const data = [{   type: "treemap",   labels: ["root", "topItem", "one", "two", "three", "something", "thing", "whatever"],   parents: ["", "root", "topItem", "topItem", "topItem", "one", "two", "two"],   values: [0, 10, 5, 7, 3, 6, 4, 2] // 假设的数值 }];

注意:根节点的数值通常设置为 0。

总结

通过 labels 和 parents 数组,我们可以灵活地定义 Plotly.js Treemap 图的层级结构。结合 values 数组,我们可以展示每个节点的数值信息,从而创建更丰富、更有意义的 Treemap 图。理解这两个数组的含义以及它们之间的关系,是使用 Plotly.js 创建自定义 Treemap 图的关键。在实际应用中,可以根据具体的数据结构和可视化需求,调整 labels、parents 和 values 数组,从而创建出满足特定需求的 Treemap 图。

以上就是使用 Plotly.html js 浏览器 字符串数组 html plotly 字符串 数据结构 JS



评论(已关闭)

评论已关闭