我正在使用seaborn构建一个条形图,并且已经解决了大部分问题。但我遇到了情节中第一个和最后一个项目的问题。在所附的屏幕截图中,您可以看到当我希望边缘和条形之间有空间时,第一个和最后一个条形位于图的边缘。
这是创建图表的代码
fig, ax = plt.subplots(figsize=(17,10))
# variables for table
examiner_figure_title = (f'Examiner Production - {yesterday}')
# hide axes
fig.patch.set_visible(False)
fig.suptitle(examiner_figure_title, fontsize=24)
# variables for bar graph
x = yesterday_df['Production']
y = yesterday_df['Examiner']
ax = sns.barplot(x=x, y=y, hue=y, orient='h', ax=ax, palette=sns.color_palette())
ax.set(yticklabels=[])
ax.tick_params(left=False)
ax.bar_label
# change_width(ax, .75)
change_height(ax, 1)
ax.legend(bbox_to_anchor=(1, .5))
plt.show()
我尝试改变我的图形尺寸,认为这可能是原因。这并没有影响酒吧的位置。
我使用自定义高度函数来创建条形而不是细线。如果我不应用条形的自定义尺寸,则线条不会紧靠图形边缘,但您无法真正看到线条,这就是我使用自定义设置的原因。也许我需要在函数中添加一些东西? (附加 View 的自定义高度和宽度)
def change_width(ax, new_value):
for patch in ax.patches:
current_width = patch.get_width()
diff = current_width - new_value
patch.set_width(new_value)
patch.set_x(patch.get_x() + diff * .5)
def change_height(ax, new_value):
for patch in ax.patches:
current_height = patch.get_height()
diff = current_height - new_value
patch.set_height(new_value)
patch.set_y(patch.get_y() + diff * .5)
有人可以对此提供一些见解吗?
最佳答案
要在更改矩形后重新计算限制,您可以使用:
ax.relim()
ax.autoscale_view()
ax.margins(y=0.01) # for a smaller padding, as the default is rather wide
但您可能只想设置dodge=False
。否则,将为每个 y 位置的每个色调值保留一个点。
其他一些备注:
- 默认的
sns.color_palette()
只有 10 种不同的颜色,这使得图例很困惑;你可以使用例如turbo
或tab20
用于更多颜色 - 要添加条形标签,您可以循环遍历
ax.containers
,例如:对于ax.containers中的bars_group:ax.bar_label(bars_group)
(每个色调值有一个“组”) - 如果为图例设置了
bbox_to_anchor=
,则还需要设置loc=
;默认情况下,使用 loc='best',它可以根据绘图内容而变化
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
fig, ax = plt.subplots(figsize=(17, 10))
fig.patch.set_visible(False)
x = [1, 4, 7, 9, 11, 12, 14, 16, 19, 20, 23, 24, 27, 28, 31, 32, 35.5, 40, 39, 40]
y = ['Hydrogen', 'Helium', 'Lithium', 'Berylium', 'Boron', 'Carbon', 'Nitrogen', 'Oxygen', 'Fluorine', 'Neon', 'Sodium', 'Magnesium', 'Aluminium', 'Silicon', 'Phosphorus', 'Sulphur', 'Chlorine', 'Argon', 'Potassium', 'Calcium']
ax = sns.barplot(x=x, y=y, hue=y, orient='h', dodge=False, ax=ax, palette='turbo')
ax.tick_params(left=False, labelleft=False)
for bars_group in ax.containers:
ax.bar_label(bars_group, padding=3, fontsize=15)
ax.legend(bbox_to_anchor=(1, .5), loc='center left')
# ax.margins(x=0.15) # optionally more space for the text
sns.despine()
plt.tight_layout()
plt.show()
关于python - 如何在我的seaborn条形图的第一个/最后一个条形周围添加空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70958632/