Seaborn:如何在计数图中显示值?

问题描述 投票:1回答:1

我拥有的数据显示,某个性别的人是否有孩子(1)(0)。这在countplot中显示。但是,我想在列中或列顶部具有值。我该如何实现?

请不要发送指向其他答案的链接,因为我已经检查了它,但我不理解。请简单地修改我可以在我的情况下使用的代码。

df = pd.DataFrame({"Gender":["Male", "Male", "Female", "Male", "Female", "Female"],
                   "children":["0", "1", "0", "0", "1", "1"]})

sns.countplot(x="Gender", hue="children", data=df, palette="binary")

enter image description here

python seaborn
1个回答
2
投票

仅循环遍历countplot返回的所有补丁。然后,根据每个补丁的x位置和高度创建一个文本。我选择白色,并添加了换行符,以在栏顶部下方显示数字。

某些代码:

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

df = pd.DataFrame({"Gender":["Male", "Male", "Female", "Male", "Female", "Female", "Male", "Male", "Female", "Male", "Female", "Female"],
                   "Children":["0", "1", "0", "0", "1", "1", "0", "1", "0", "0", "1", "1"]})
ax = sns.countplot(x="Gender", hue="Children", data=df, palette="plasma")
for p in ax.patches:
    ax.annotate(f'\n{p.get_height()}', (p.get_x()+0.2, p.get_height()), ha='center', va='top', color='white', size=18)
plt.show()

example countplot

© www.soinside.com 2019 - 2024. All rights reserved.