我有数据显示某个性别的人是否有孩子(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")
答案 0 :(得分: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")
ax.set_title('Survival in terms of gender', fontsize=20)
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()