如何在 Plotly 中以编程方式定义 sankey 标签

问题描述 投票:0回答:1

我创建了一种方法,以编程方式从字典列表开始,以编程方式定义桑基图的源、目标和值列表。

但是,我一直在寻找一种使用类似方法定义标签的方法。

my_data = [
{'src':'wages','dst':'budget', 'value':1500},
{'src':'other','dst':'budget', 'value':250},
{'src':'budget','dst':'taxes', 'value':450},
{'src':'budget','dst':'housing', 'value':420},
{'src':'budget','dst':'food', 'value':400},
{'src':'budget','dst':'transportation', 'value':295},
{'src':'budget','dst':'savings', 'value':25},
{'src':'budget','dst':'other necessities', 'value':160},
]

i = 0 
node_names = []
my_data2 = []
for row in my_data:
    key_src = row['src']
    if (key_src not in node_names):
        node_names.append(key_src)
        i = i + 1
    row['src_id'] = i
    my_data2.append(row)

for row in my_data:
    key_dst = row['dst']
    if (key_dst not in node_names):
        node_names.append(key_dst)
        i = i + 1
    row['dst_id'] = i
    my_data2.append(row)
    
del node_names 

my_data2 = [dict(t) for t in {tuple(d.items()) for d in my_data2}] # Remove duplicates 


source = []
target = []
value = []

for row in my_data2:
    source.append(row['src_id'])
    target.append(row['dst_id'])
    value.append(row['value'])
    

print(source)
print(target)
print(value)


import plotly.graph_objects as go

link = dict(source = source, target = target, value = value)
data = go.Sankey(link = link)


# data
label = ["ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE"]
# data to dict, dict to sankey
link = dict(source = source, target = target, value = value)
node = dict(label = label, pad=50, thickness=5)
data = go.Sankey(link = link, node=node)
# plot
fig = go.Figure(data)
fig.show()
python python-3.x plotly plotly-dash
1个回答
1
投票

这可能是限制您的数据的一种方式。我们提出了使用原始字典格式数据作为数据框来创建标签的想法。您将获得起点的唯一字符串列表和终点的唯一字符串列表,并将这些列表连接在一起。重叠的字符串是中心点的标签。我们使用 set() 来解决这种重复问题,并且仍然保持原始列表顺序。最后在开头插入一个空字符串。

import pandas as pd

df = pd.DataFrame.from_dict(my_data)
df

    src     dst     value   src_id  dst_id
0   wages   budget  1500    1   3
1   other   budget  250     2   3
2   budget  taxes   450     3   4
3   budget  housing     420     3   5
4   budget  food    400     3   6
5   budget  transportation  295     3   7
6   budget  savings     25  3   8
7   budget  other necessities   160     3   9


src_dst = list(df['src'].unique()) + list(df['dst'].unique())
labels = sorted(set(src_dst), key=src.index)
labels.insert(0,'')

labels
['',
 'wages',
 'other',
 'budget',
 'taxes',
 'housing',
 'food',
 'transportation',
 'savings',
 'other necessities']

import plotly.graph_objects as go

link = dict(source = source, target = target, value = value)
data = go.Sankey(link = link)
    
# data
#label = ["ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE"]
label = labels
# data to dict, dict to sankey
link = dict(source = source, target = target, value = value)
node = dict(label = label, pad=50, thickness=5)
data = go.Sankey(link = link, node=node)
# plot
fig = go.Figure(data)
fig.show()

© www.soinside.com 2019 - 2024. All rights reserved.