怎么用Python绘制多层桑基图
时间: 2023-10-09 20:12:26 浏览: 350
要使用Python绘制多层桑基图,可以使用Python的matplotlib库和pandas库。下面是一些基本的步骤:
1. 导入需要的库:
```
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.sankey import Sankey
```
2. 创建数据集:
```
data = {'A': [100, 50, 75], 'B': [20, 10, 30], 'C': [60, 70, 80], 'D': [30, 20, 10]}
df = pd.DataFrame(data, index=['2018', '2019', '2020'])
```
3. 创建桑基图:
```
fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[])
sankey = Sankey(ax=ax, head_angle=180, shoulder=0.2, unit='t', offset=0.2, scale=0.03, gap=0.5)
sankey.add(flows=df.iloc[0], labels=df.columns, orientations=[-1, 1, 0, 0])
sankey.add(flows=df.iloc[1], orientations=[-1, 1, 0, 0])
sankey.add(flows=df.iloc[2], orientations=[-1, 1, 0, 0])
sankey.finish()
```
其中,`flows`是一个包含流量数据的列表,`labels`是标签列表,`orientations`是桑基图的方向,`-1`表示左边,`1`表示右边,`0`表示上下。
4. 显示图形:
```
plt.show()
```
完整的代码示例:
```
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.sankey import Sankey
data = {'A': [100, 50, 75], 'B': [20, 10, 30], 'C': [60, 70, 80], 'D': [30, 20, 10]}
df = pd.DataFrame(data, index=['2018', '2019', '2020'])
fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[])
sankey = Sankey(ax=ax, head_angle=180, shoulder=0.2, unit='t', offset=0.2, scale=0.03, gap=0.5)
sankey.add(flows=df.iloc[0], labels=df.columns, orientations=[-1, 1, 0, 0])
sankey.add(flows=df.iloc[1], orientations=[-1, 1, 0, 0])
sankey.add(flows=df.iloc[2], orientations=[-1, 1, 0, 0])
sankey.finish()
plt.show()
```
阅读全文
相关推荐
















