我试图在两个特定的条形图之间插入间距,但找不到任何简单方法。我可以手动添加一个高度为0的虚拟行来创建空白间隔,但这并不能让我控制空白间隔的宽度。是否有更多编程方法可用于在任何位置控制条形图之间的间距?
示例代码:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
mydict = {
'Event': ['Running', 'Swimming', 'Biking', '', 'Hiking', 'Jogging'],
'Completed': [2, 4, 3, 0, 7, 9],
'Participants': [10, 20, 35, 0, 10, 20]}
df = pd.DataFrame(mydict).set_index('Event')
df = df.assign(Completion=(df.Completed / df.Participants) * 100)
plt.subplots(figsize=(5, 4))
print(df.index)
ax = sns.barplot(x=df.Completion, y=df.index, color="orange", orient='h')
plt.xticks(rotation=60)
plt.tight_layout()
plt.show()
示例DataFrame输出:
Completed Participants Completion
Event
Running 2 10 20.000000
Swimming 4 20 20.000000
Biking 3 35 8.571429
0 0 NaN
Hiking 7 10 70.000000
Jogging 9 20 45.000000
示例输出(蓝色箭头添加在代码之外,以显示添加了空行的位置。):
ax.set_ylim([ax.get_ylim()[0]+extra_space, ax.get_ylim()[1]])
,我没有测试所有情况,所以无法确定应该在这里放置什么。如果数字不是太大,请尝试ax.set_ylim([ax.get_ylim()[0]+extra_space/2, ax.get_ylim()[1]])
。 - Ben.T