用 matplotlib 库将数据集 links = [ {"source": "category1", "target": "category2", "value": 10}, {"source": "category2", "target": "category3", "value": 15}, {"source": "category3", "target": "category4", "value": 20}, {"source": "category5", "target": "category6", "value": 25}, ]绘制sankey图的程序
时间: 2023-06-29 08:15:35 浏览: 92
matplotlib库也可以绘制Sankey图。下面是一个示例程序,根据提供的数据集绘制Sankey图。
```
import matplotlib.pyplot as plt
from matplotlib.sankey import Sankey
# 数据集
links = [
{"source": "category1", "target": "category2", "value": 10},
{"source": "category2", "target": "category3", "value": 15},
{"source": "category3", "target": "category4", "value": 20},
{"source": "category5", "target": "category6", "value": 25},
]
# 定义节点和链接
node_labels = []
node_indices = {}
flows = []
for link in links:
source = link['source']
target = link['target']
value = link['value']
if source not in node_indices:
node_indices[source] = len(node_labels)
node_labels.append(source)
if target not in node_indices:
node_indices[target] = len(node_labels)
node_labels.append(target)
flows.append(value)
# 创建Sankey图
fig, ax = plt.subplots()
sankey = Sankey(ax=ax, scale=0.1, offset=0.3)
sankey.add(flows=flows,
labels=node_labels,
orientations=[1, -1, 0, 1],
pathlengths=[0.05, 0.05, 0.2, 0.2],
trunklength=1.5,
facecolor='#37c959',
edgecolor='black',
lw=1)
sankey.finish()
# 显示图像
plt.show()
```
程序中使用matplotlib库中的Sankey类绘制图像,需要定义节点和链接的信息。首先遍历数据集,根据数据集中的源节点和目标节点构建节点列表,同时记录每个节点的索引。接着根据链接信息构建流量列表。最后使用Sankey类绘制图形。
Sankey类的构造函数需要传入画布和缩放比例等参数。调用add方法添加流量和节点标签等信息,可以设置流量的方向和长度等属性。最后调用finish方法完成Sankey图的绘制。
程序运行后会在浏览器中打开一个新的网页,展示绘制的Sankey图。
阅读全文