python画桑基图代码
时间: 2023-10-12 14:14:54 浏览: 129
以下是使用Python的matplotlib库画桑基图的示例代码:
```python
import matplotlib.pyplot as plt
# 数据准备
labels = ['A', 'B', 'C', 'D', 'E', 'F']
values = [10, 15, 20, 25, 30, 35]
flows = [5, 10, -5, -15, 10, 10]
# 计算节点位置和大小
positions = range(len(labels))
sizes = [v/sum(values) for v in values]
# 绘制桑基图
fig, ax = plt.subplots()
ax.axis('off')
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
ax.invert_yaxis()
for i in positions:
ax.add_patch(plt.Circle((0, i), sizes[i], color='lightgrey'))
for i in range(len(flows)):
if flows[i] > 0:
ax.arrow(-0.1, i, 0.2, 0, head_width=0.05, head_length=0.1, fc='blue', ec='blue')
ax.arrow(0.1, i, 0.7, 0, head_width=0.05, head_length=0.1, fc='red', ec='red')
ax.text(0, i, str(flows[i]), ha='center', va='center', color='white')
elif flows[i] < 0:
ax.arrow(0.1, i, -0.2, 0, head_width=0.05, head_length=0.1, fc='blue', ec='blue')
ax.arrow(-0.1, i, -0.7, 0, head_width=0.05, head_length=0.1, fc='red', ec='red')
ax.text(0, i, str(-flows[i]), ha='center', va='center', color='white')
for i in positions:
ax.text(0, i, labels[i], ha='center', va='center')
plt.show()
```
这段代码将绘制一个包含6个节点和5个流量的桑基图。具体来说,每个节点由一个圆圈表示,圆圈的大小表示节点的权重,节点的标签显示在圆圈中心。流量由箭头表示,箭头的颜色表示流入或流出的方向,箭头的宽度和长度表示流量大小,流量大小显示在箭头中心。
阅读全文