创建简单、漂亮的桑基图(Beta版本)
项目描述
pySankey
使用matplotlib创建只从左到右流动的简单 桑基图。
示例
使用fruits.txt
真实 | 预测 | |
---|---|---|
0 | 蓝莓 | 橙子 |
1 | 青柠 | 橙子 |
2 | 蓝莓 | 青柠 |
3 | 苹果 | 橙子 |
... | ... | ... |
996 | 青柠 | 橙子 |
997 | 蓝莓 | 橙子 |
998 | 橙子 | 香蕉 |
999 | 苹果 | 青柠 |
1000行 × 2列
您可以使用此代码生成桑基图
import pandas as pd
from pysankey import sankey
import matplotlib.pyplot as plt
df = pd.read_csv(
'pysankey/fruits.txt', sep=' ', names=['true', 'predicted']
)
colorDict = {
'apple':'#f71b1b',
'blueberry':'#1b7ef7',
'banana':'#f3f71b',
'lime':'#12e23f',
'orange':'#f78c1b',
'kiwi':'#9BD937'
}
ax = sankey(
df['true'], df['predicted'], aspect=20, colorDict=colorDict,
leftLabels=['banana','orange','blueberry','apple','lime'],
rightLabels=['orange','banana','blueberry','apple','lime','kiwi'],
fontsize=12
)
plt.show() # to display
plt.savefig('fruit.png', bbox_inches='tight') # to save
您还可以使用权重
,customer,good,revenue
0,John,fruit,5.5
1,Mike,meat,11.0
2,Betty,drinks,7.0
3,Ben,fruit,4.0
4,Betty,bread,2.0
5,John,bread,2.5
6,John,drinks,8.0
7,Ben,bread,2.0
8,Mike,bread,3.5
9,John,meat,13.0
import pandas as pd
from pysankey import sankey
import matplotlib.pyplot as plt
df = pd.read_csv(
'pysankey/customers-goods.csv', sep=',',
names=['id', 'customer', 'good', 'revenue']
)
weight = df['revenue'].values[1:].astype(float)
ax = sankey(
left=df['customer'].values[1:], right=df['good'].values[1:],
rightWeight=weight, leftWeight=weight, aspect=20, fontsize=20
)
plt.show() # to display
plt.savefig('customers-goods.png', bbox_inches='tight') # to save
类似于seaborn,您可以将matplotlib Axes
传递给sankey
函数
import pandas as pd
from pysankey import sankey
import matplotlib.pyplot as plt
df = pd.read_csv(
'pysankey/fruits.txt',
sep=' ', names=['true', 'predicted']
)
colorDict = {
'apple': '#f71b1b',
'blueberry': '#1b7ef7',
'banana': '#f3f71b',
'lime': '#12e23f',
'orange': '#f78c1b'
}
ax1 = plt.axes()
sankey(
df['true'], df['predicted'], aspect=20, colorDict=colorDict,
fontsize=12, ax=ax1
)
plt.show()
重要信息
在sankey()
中使用figureName
、closePlot
、figSize
已弃用,将在未来版本中删除。这样做是为了使matplotlib的使用更加透明,如原始github存储库上的此问题所建议。
现在,sankey
做更少的自定义,让用户按照自己的喜好进行自定义,通过返回matplotlib Axes
对象,这意味着用户也可以访问Figure
进行自定义。然后他们可以选择如何处理它 - 显示它,以更多的灵活性保存它。
对您的代码的推荐更改
- 要保存图形,可以简单地这样做
plt.savefig("<figureName>.png", bbox_inches="tight", dpi=150)
-
由于在
sankey()
之后没有plt.show()
,因此不再需要closePlot
。您仍然可以使用plt.close()
来确保在之后显示其他图形时不会显示此图形。 -
您可以通过更改matplotlib图形中的尺寸来修改sankey大小。
plt.gcf().set_size_inches(figSize)
包开发
pip3 install -e ".[test]"
代码检查
pylint pysankey
测试
python -m unittest
覆盖率
coverage run -m unittest
coverage html
# Open htmlcov/index.html in a navigator
项目详情
下载文件
下载适用于您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。
源分布
pysankeybeta-1.4.2.tar.gz (23.9 kB 查看哈希值)
构建分布
pysankeybeta-1.4.2-py3-none-any.whl (20.8 kB 查看哈希值)