拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 从DIFFERENTCOLUMN向分组的seabornbarplot添加标签

从DIFFERENTCOLUMN向分组的seabornbarplot添加标签

白鹭 - 2022-01-26 2006 0 0

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

假设我有这个资料框:

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)

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

如何使用“数字”列中的条目标记条形图?为了清楚起见,我选择了数字 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)

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

提前致谢。

从 DIFFERENT COLUMN 向分组的 seaborn barplot 添加标签

uj5u.com热心网友回复:

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

从 DIFFERENT COLUMN 向分组的 seaborn barplot 添加标签

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *