如何在Python的Plotly Sankey图链接上显示数值
Plotly Sankey图链接显示数值的实现方案
问题描述
使用Plotly绘制Sankey图时,无法在链接上直接显示数值(仅能在悬浮工具框中查看),尝试参考R语言方案但无法在Python中复现,期望像Sunburst图那样通过简单参数设置实现数值显示。
示例代码:
import plotly.graph_objects as go fig = go.Figure(data=[go.Sankey( node = dict( pad = 15, thickness = 20, line = dict(color = "black", width = 0.5), label = ["A1", "A2", "B1", "B2", "C1", "C2"], color = "blue" ), link = dict( source = [0, 1, 0, 2, 3, 3], # indices correspond to labels, eg A1, A2, A1, B1, ... target = [2, 3, 3, 4, 4, 5], value = [8, 4, 2, 8, 4, 2] ))]) fig.update_layout(title_text="Basic Sankey Diagram", font_size=10) fig.show()
原本期望类似Sunburst图的实现方式:
fig.update_traces(textinfo="label+value", selector=dict(type='sunburst'))
解决方案
Plotly的Sankey组件目前没有像Sunburst那样的textinfo参数直接显示链接数值,需要通过**手动添加注释(annotations)**来实现。核心思路是计算每个链接的中心坐标,在对应位置添加数值文本。
修改后的完整代码:
import plotly.graph_objects as go # 定义Sankey节点与链接数据 nodes = dict( pad=15, thickness=20, line=dict(color="black", width=0.5), label=["A1", "A2", "B1", "B2", "C1", "C2"], color="blue" ) links = dict( source=[0, 1, 0, 2, 3, 3], target=[2, 3, 3, 4, 4, 5], value=[8, 4, 2, 8, 4, 2] ) # 初始化Sankey图 fig = go.Figure(data=[go.Sankey(node=nodes, link=links)]) # 遍历所有链接,添加数值注释 for i in range(len(links['source'])): # 获取源节点和目标节点的坐标 source_x, source_y = fig.data[0].node['x'][links['source'][i]], fig.data[0].node['y'][links['source'][i]] target_x, target_y = fig.data[0].node['x'][links['target'][i]], fig.data[0].node['y'][links['target'][i]] # 计算链接的中心坐标 mid_x = (source_x + target_x) / 2 mid_y = (source_y + target_y) / 2 # 添加数值文本注释 fig.add_annotation( x=mid_x, y=mid_y, text=str(links['value'][i]), showarrow=False, font=dict(size=10, color="white") ) fig.update_layout(title_text="Sankey Diagram with Link Values", font_size=10) fig.show()
关键说明
- 通过遍历每个链接,计算源节点与目标节点的坐标中点,作为数值文本的显示位置
- 注释设置为无箭头、白色字体(与深色链接形成清晰对比),可根据需求调整字体大小和颜色
- 若拖拽节点改变布局,注释不会自动跟随,需重新运行坐标计算代码更新注释
内容的提问来源于stack exchange,提问作者Vincent ROGER
相关产品推荐
相关产品推荐

