我是 Matplotlib 中 Sankey 图函数的新手,我希望有人能够帮助我解决一些问题,因为我似乎无法弄清楚。
首先:我使用以下示例来了解如何创建桑基图: https://flothesof.github.io/sankey-tutorial-matplotlib.html
这是桑基图:
现在有一些事情我需要改变,其中两件事我不知道如何改变。
希望有人能帮忙。
每个图的
.text
字段都包含其中心标签作为 Text
对象。 .texts
是每个进入/离开箭头的 Text
对象列表。您可以检查字符串以了解它是关于哪个文本,并更改属性,例如 bold
或 xy 位置。
由于桑基图非常复杂,一旦创建图就可以对位置进行微调。一个简单的方法是在字符串中添加额外的换行符。
import matplotlib.pyplot as plt
from matplotlib.sankey import Sankey
fig, ax = plt.subplots(figsize=(8, 12))
ax.set_xticks([])
ax.set_yticks([])
ax.set_title("My funnel")
ax.set_axis_off()
number = [round(12345 * 0.6 ** i) for i in range(6)]
labels = ["\n\n\n\n\n\n\nTotal joined", "\n\n\n\nFirst", "\n\nSecond", "\nThird", "\nFourth", "\n\nReached final"]
sankey = Sankey(ax=ax, scale=0.0015, offset=0.3)
for input_number, output_number, label in zip(number[:-1], number[1:], labels):
this_index = len(sankey.diagrams)
prior = this_index - 1 if this_index > 0 else None
pathlengths = [0, 0, 2 if this_index != 4 else 10]
exitlabel = labels[-1] if this_index == 4 else None
sankey.add(flows=[input_number, -output_number, output_number - input_number],
orientations=[0, 0, 1],
patchlabel=label,
labels=['', exitlabel, 'quit'],
prior=prior,
connect=(1, 0),
pathlengths=pathlengths,
trunklength=10.,
rotation=-90,
facecolor=plt.cm.spring((this_index + 1) / 5))
diagrams = sankey.finish()
for diagram in diagrams:
diagram.text.set_fontweight('bold')
diagram.text.set_fontsize('10')
for text in diagram.texts:
text.set_fontsize('10')
label = text.get_text() # can be normal label, "quit", a number or empty
if len(label) > 0:
if label[0].isdigit():
text.set_visible(False)
elif label.startswith('quit'):
xy = text.get_position()
text.set_position((xy[0] + 2, xy[1]))
else:
text.set_fontweight('bold')
plt.ylim(ymin=plt.ylim()[0] * 1.05)
plt.show()