import plotly.graph_objects as go

# 假设这是你的 DataFrame
import pandas as pd
df = pd.DataFrame({
    'from': [0, 1, 2, 0],
    'to': [3, 4, 5, 6],
    'amount': [10, 15, 5, 20],
    'counts': [2, 3, 1, 4]
})

# labels 和节点数量
labels = list(set(df['from']).union(set(df['to'])))
source = df['from']
target = df['to']
value = df['amount']  # 或者 df['counts']，取决于你想展示哪个值

# 创建 Sankey 图
fig = go.Figure(data=[go.Sankey(
    node=dict(
        label=labels,
        pad=15,
        thickness=20,
        line=dict(color="black", width=0.5),
    ),
    link=dict(
        source=source,
        target=target,
        value=value,
        hovertemplate='Amount: %{value}<br>From: %{source.label}<br>To: %{target.label}<extra></extra>'  # 自定义悬停模板
    )
)])

# 更新布局
fig.update_layout(title_text="Custom Hover Information for Sankey Diagram", font_size=10)

# 显示图形
fig.show()
