[英]Bar labels in matplotlib/Seaborn
In version 3.4, matplotlib added automatic Bar labels: https://matplotlib.org/stable/users/whats_new.html#new-automatic-labeling-for-bar-charts在 3.4 版本中,matplotlib 添加了自动 Bar 标签: https://matplotlib.org/stable/users/whats_new.html#new-automatic-labeling-for-bar-charts
I'm trying to use this on a bar plot generated by Seaborn.我正在尝试在由 Seaborn 生成的 plot 上使用它。
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
What do I need to do to make this work?我需要做什么才能完成这项工作? example plot例如 plot
You can loop through the containers and call ax.bar_label(...)
for each of them.您可以遍历容器并为每个容器调用ax.bar_label(...)
。 Note that seaborn creates one set of bars for each hue value.请注意,seaborn 为每个色调值创建一组条。
The following example uses the titanic dataset and sets ci=None
to avoid the error bars overlapping with the text (if error bars are needed, one could set a lighter color, eg errcolor='gold'
).以下示例使用 titanic 数据集并设置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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.