gpt4 book ai didi

python-3.x - Matplotlib 控制条之间的间距

转载 作者:行者123 更新时间:2023-12-04 04:11:10 25 4
gpt4 key购买 nike

我试图在两个特定的条之间插入间距,但找不到任何简单的方法来做到这一点。我可以手动添加一个高度为 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()

示例数据帧输出:

          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

示例输出(在代码外部添加的蓝色箭头以显示添加空行的位置。):

enter image description here

最佳答案

我认为您可以访问框的位置和标签的名称。然后修改它们。根据您的用例,您可能会找到更通用的方法,但这适用于给定的示例。

#define a function to add space starting a specific label
def add_space_after(ax, label_shift='', extra_space=0):
bool_space = False
# get postion of current ticks
ticks_position = np.array(ax.get_yticks()).astype(float)
# iterate over the boxes/label
for i, (patch, label) in enumerate(zip(ax.patches, ax.get_yticklabels())):
# if the label to start the shift found
if label.get_text()==label_shift: bool_space = True
# reposition the boxes and the labels afterward
if bool_space:
patch.set_y(patch.get_y() + extra_space)
ticks_position[i] += extra_space
# in the case where the spacing is needed
if bool_space:
ax.set_yticks(ticks_position)
ax.set_ylim([ax.get_ylim()[0]+extra_space, ax.get_ylim()[1]])

#note: no more blank row
mydict = {
'Event': ['Running', 'Swimming', 'Biking', 'Hiking', 'Jogging'],
'Completed': [2, 4, 3, 7, 9],
'Participants': [10, 20, 35, 10, 20]}
df = pd.DataFrame(mydict).set_index('Event')
df = df.assign(Completion=(df.Completed / df.Participants) * 100)

ax = sns.barplot(x=df.Completion, y=df.index, color="orange", orient='h')
plt.xticks(rotation=60)
plt.tight_layout()

#use the function
add_space_after(ax, 'Hiking', 0.6)

plt.show()

enter image description here

关于python-3.x - Matplotlib 控制条之间的间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61705783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com