【问题标题】:python plotly Treemap ids format and how to display multiple duplicated labels in a treemap?python plotly Treemap ids格式以及如何在树图中显示多个重复的标签?
【发布时间】:2020-10-17 03:37:06
【问题描述】:

简述

我认为我的问题有两个部分:

  1. plotly 期望 ids 参数采用什么格式?
  2. 如何创建ids 以允许我创建带有重复标签的树形图?

更详细的

我正在尝试创建一个带有共享标签的嵌套树形图。例如,将其视为“其他”类别。
这里我使用的是 Python 3.8 Plotly 4.9.0

重新利用plotly 示例:

from plotly import graph_objects as go
labels = ["A1", "A2", "A3", "A4", "A5", "B1", "B2", "Other", "Other"]
parents = ["", "A1", "A2", "A3", "A4", "", "B1", "A1", "B1"]
ids = [f"{parents[i]}{'-' if parents[i] else ''}{labels[i]}" for i in range(0,len(labels))]
# ['A1', 'A1-A2', 'A2-A3', 'A3-A4', 'A4-A5', 'B1', 'B1-B2', 'A1-Other', 'B1-Other']

fig = go.Figure(go.Treemap(
    labels = labels,
    parents = parents,
    ids=ids # commenting this out displays something at least
))
fig.show()

上面给了我一个空白屏幕,但是如果我注释掉 ids 参数,它会忽略其中一个重复的标签:

我查看了plotly 文档的各个部分,看起来这个字符串列表应该可以按预期工作。

https://plotly.com/python/reference/treemap/中提取:

ID
类型:列表、numpy 数组或 Pandas 系列数字、字符串或 日期时间。

为每个数据分配 id 标签。这些用于对象恒定性的 id 动画期间的数据点。应该是一个字符串数组,而不是 数字或任何其他类型。

我尝试ids 的这种特定结构的原因是由于其他plotly 示例
例如https://plotly.com/python/treemaps/#controlling-text-fontsize-with-uniformtext

import plotly.graph_objects as go
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/718417069ead87650b90472464c7565dc8c2cb1c/sunburst-coffee-flavors-complete.csv')

fig = go.Figure(go.Treemap(
        ids = df.ids,
        labels = df.labels,
        parents = df.parents))
fig.update_layout(uniformtext=dict(minsize=10, mode='hide'))
fig.show()

# Above is exact example, below is df structure
df.head()
                       ids            labels parents
0                   Aromas            Aromas     NaN
1                   Tastes            Tastes     NaN
2         Aromas-Enzymatic         Enzymatic  Aromas
3    Aromas-Sugar Browning    Sugar Browning  Aromas
4  Aromas-Dry Distillation  Dry Distillation  Aromas

感谢您的宝贵时间!

【问题讨论】:

    标签: python plotly plotly-python


    【解决方案1】:

    Parent: 数据[type=treemap] 类型:列表、numpy 数组或 Pandas 系列数字、字符串或日期时间。 为每个扇区设置父扇区。空字符串项 '' 被理解为引用层次结构中的根节点。如果填充了ids,则parents 项目被理解为“ids”本身。当ids 未设置时,plotly 会尝试在labels 中查找匹配项,但请注意它们必须是唯一的。

    标签可以是你想要的任何东西,id 必须是唯一的,如果你使用 id,父级应该包含 id 而不是标签。 如果您不使用 ids,那么它会按照上述说明进行计算。

    示例代码:

    from plotly import graph_objects as go
    
    ids =    ["a1", "a2", "a3", "a4", "a5", "b1", "b2", "o_1", "o_2"]
    labels = ["A1", "A2", "A3", "A4", "A5", "B1", "B2", "Other", "Other"]
    parents = ["", "a1", "a2", "a3", "a4", "", "b1", "a1", "b1"]
    
    fig = go.Figure(go.Treemap(
        labels = labels,
        parents = parents,
        ids=ids
    ))
    fig.show()
    

    【讨论】:

      猜你喜欢
      • 2023-01-27
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多