python plotly Treemap ids 格式以及如何在树图中显示多个重复的标签?

python plotly Treemap ids format and how to display multiple duplicated labels in a treemap?

简述

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

  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/

ids
Type: list, numpy array, or Pandas series of numbers, strings, or datetimes.

Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type.

我尝试 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

感谢您的宝贵时间!

Parent: data[type=treemap] Type: list, numpy array, or Pandas series of numbers, strings, or datetimes. Sets the parent sectors for each of the sectors. Empty string items '' are understood to reference the root node in the hierarchy. If ids is filled, parents items are understood to be "ids" themselves. When ids is not set, plotly attempts to find matching items in labels, but beware they must be unique.

标签可以是你想要的任何东西,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()