用python写一个桑基图的代码
时间: 2023-12-17 12:05:21 浏览: 83
以下是一个简单的Python代码,用于绘制桑基图。这个代码使用了matplotlib库。
import matplotlib.pyplot as plt
import numpy as np
# 输入数据
labels = ['A', 'B', 'C', 'D'] # 类别标签
prev = [10, 20, 30, 40] # 上一年的数据
curr = [20, 30, 10, 50] # 当前年的数据
# 计算桑基图的宽度和高度
width = min(prev) / 4
height = len(labels)
# 绘制桑基图
fig, ax = plt.subplots(figsize=(10, 6))
ax.set_xlim(-width, sum(prev) + width)
ax.set_ylim(-height / 2, height / 2)
# 绘制上一年的数据
lefts = np.zeros(len(labels))
for i in range(len(labels)):
rect = plt.Rectangle((lefts[i], -height/2), prev[i], height, color='grey')
ax.add_patch(rect)
lefts[i] += prev[i]
# 绘制当前年的数据
for i in range(len(labels)):
rect = plt.Rectangle((lefts[i], -height/2), curr[i], height, color='blue')
ax.add_patch(rect)
lefts[i] += curr[i]
# 添加标签
ax.text(lefts[i] - curr[i] / 2, 0, labels[i], ha='center', va='center')
# 显示图形
plt.show()
这个代码会生成如下的桑基图:
阅读全文
相关推荐


















