繁体   English   中英

将标签添加到来自不同列的分组 seaborn 条形图

[英]Add labels to grouped seaborn barplot from DIFFERENT COLUMN

我知道还有其他类似的条目,但没有完全像这样的条目。

假设我有这个 dataframe:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame({"percentage": [0.3, 0.4, 0.5, 0.2],
                   "xaxis": ["set1", "set1", "set2", "set2"],
                   "hues": ["a", "b", "c", "d"],
                   "number": [1,2,3,4]
                  })

我在 Seaborn 中创建了一个分组条形图:

sns.set(style="whitegrid")

fig, ax = plt.subplots(figsize=(10,10))
ax = sns.barplot(data=df,
                 x="xaxis",
                 y="percentage",
                 hue="hues")
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0)

for container in ax.containers:
    ax.bar_label(container)

这很好地添加了“百分比”列中的标签。

如何使用“数字”列中的条目 label 条形图? 为了清楚起见,我选择了数字 1、2、3、4 作为玩具示例。 它们在我的真实数据中不是连续的。

作为参考,我使用的是 Python 3.9.X、Seaborn 0.11.2 和 Matplotlib 3.5.0。

我怀疑答案在容器中的某个地方,但不知道。

我还看到了使用此代码的潜在答案:

for index, row in df.iterrows():
    ax.text(insert_codehere)

但这似乎对我也不起作用。

提前致谢。

在此处输入图像描述

for container, number in zip(ax.containers, df.number):
    ax.bar_label(container, labels=[number, number])

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM