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

2022-02-27 00:00:00 python seaborn

问题描述

我有数据显示某个性别的人是否有孩子(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")


解决方案

只需循环访问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")
ax.set_title('Survival in terms of gender', fontsize=20)
for p in ax.patches:
    ax.annotate(f'
{p.get_height()}', (p.get_x()+0.2, p.get_height()), ha='center', va='top', color='white', size=18)
plt.show()

相关文章