简体   繁体   中英

Seaborn: Problem with values on the countplot in Python

I have DataFrame like this:

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

And I present this DataFrame on a seaborn countplot like this: ax=sns.countplot(x="Gender", hue="children", data=df, palette="binary")

I try to present values on each column on the countplot using this code:

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()

But I have Error:

AttributeError: 'Text' object has no attribute 'patches'

What can I do so as to have values on each column of the plot ? Please do not send my link to other answers I checked everything and I need simple answer. Please modyfi my code or tell me what is a reason of mentioned Error ? 在此处输入图片说明

the problem is that .set_title returns text, not a matplotlib subplot.

You should instead do

ax=sns.countplot(x="Gender", hue="children", data=df, palette="binary")
ax.set_title(<insert your title here>)

on separate lines

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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