如何从 plotly sunburst 图表中检索值?

how to retrieve values from plotly sunburst chart?

Plotly sunburst charts 非常适合可视化分层数据。是否可以将图表中显示的值检索到字典、数组或其他东西中?

具体来说,假设以下数据框:

Att1   Att2
A      C
A      D
B      D
B      D
B      C

px.sunburst(data, ['Att1', 'Att2']) 将生成一个图表,在最内环中,A 的值为 2,B 的值为 3。那么对于A,就会表示有1个C和1个D。同样,对于 B,它将指示 2 D 和 1 C。所有这些数字都是我要检索的数字。 plotly 有这样的功能吗?还是我最好的选择是迭代使用 data.groupby

可以访问图中的基础数据,可以找到详细信息here at plotly并总结如下...

Viewing the underlying data structure for any plotly.graph_objects.Figure object, including those returned by Plotly Express, can be done via print(fig) or, in JupyterLab, with the special fig.show("json") renderer. Figures also support fig.to_dict() and fig.to_json() methods. print()ing the figure will result in the often-verbose layout.template key being represented as ellipses '...' for brevity.

有几个选项可用...

  • fig.show("json") 如果你在笔记本里就很方便了
  • print(fig) 是我的方法

所以对于这个情节示例:

import plotly.express as px
data = dict(
    character=["Eve", "Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura"],
    parent=["", "Eve", "Eve", "Seth", "Seth", "Eve", "Eve", "Awan", "Eve" ],
    value=[10, 14, 12, 10, 2, 6, 6, 4, 4])

fig = px.sunburst(
    data,
    names='character',
    parents='parent',
    # values='value',
)
fig.show()

print(fig) 将 return:

Figure({
    'data': [{'domain': {'x': [0.0, 1.0], 'y': [0.0, 1.0]},
              'hovertemplate': 'character=%{label}<br>parent=%{parent}<extra></extra>',
              'labels': array(['Eve', 'Cain', 'Seth', 'Enos', 'Noam', 'Abel', 'Awan', 'Enoch', 'Azura'],
                              dtype=object),
              'name': '',
              'parents': array(['', 'Eve', 'Eve', 'Seth', 'Seth', 'Eve', 'Eve', 'Awan', 'Eve'],
                               dtype=object),
              'type': 'sunburst'}],
    'layout': {'legend': {'tracegroupgap': 0}, 'margin': {'t': 60}, 'template': '...'}
})

然后通过对元组的一些了解,您可以提取一些信息,例如...

print(fig.data[0].labels) 将 return:

['Eve' 'Cain' 'Seth' 'Enos' 'Noam' 'Abel' 'Awan' 'Enoch' 'Azura']