在 3.4 版本中,matplotlib 添加了自动 Bar 标签:https://matplotlib.org/stable/users/whats_new.html#new-automatic-labeling-for-bar-charts https://matplotlib.org/stable/users/whats_new.html#new-automatic-labeling-for-bar-charts
我正在尝试在 Seaborn 生成的条形图上使用它。
fig, axs = plt.subplots(
nrows=2,
)
for i, col in enumerate(['col_1', 'col_2']):
ax = axs[i]
sns.barplot(
x="class",
y=col,
hue="hue_col",
data=data_df,
edgecolor=".3",
linewidth=0.5,
ax=ax
)
ax.bar_label(ax.containers[i]) # Doesn't work
我需要做什么才能使这项工作成功?示例图 https://i.stack.imgur.com/Blz3a.png
您可以循环遍历容器并调用ax.bar_label(...)
对于他们每个人来说。请注意,seaborn 为每个色调值创建一组条形。
以下示例使用泰坦尼克号数据集和集合ci=None
以避免误差线与文本重叠(如果需要误差线,可以设置较浅的颜色,例如errcolor='gold'
).
import seaborn as sns
import matplotlib.pyplot as plt
titanic = sns.load_dataset('titanic')
fig, axs = plt.subplots(ncols=2, figsize=(12, 4))
for ax, col in zip(axs, ['age', 'fare']):
sns.barplot(
x='sex',
y=col,
hue="class",
data=titanic,
edgecolor=".3",
linewidth=0.5,
ci=None,
ax=ax
)
ax.set_title('mean ' + col)
ax.margins(y=0.1) # make room for the labels
for bars in ax.containers:
ax.bar_label(bars, fmt='%.1f')
plt.tight_layout()
plt.show()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)