![](/img/trans.png)
[英]Plot mean of variable by group with specified number of instances in each bar
[英]Plot number of instances forming each group in a seaborn bar plot
如何輕松獲取每天的實例數(男性和女性)以及 plot 它在每個欄的頂部?
import seaborn as sns
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")
ax = sns.barplot(x="day", y="total_bill", hue="sex", data=tips)
for p in ax.patches:
ax.annotate("%.2f" % MISSING_VALUE_TO_PLOT, (p.get_x() + p.get_width() / 2., p.get_height()),
ha='center', va='center', fontsize=11, color='gray', xytext=(0, 20),
textcoords='offset points')
如果您想在 seaborn plot 上添加一些信息,我的建議是使用order=
和hue_order=
這樣您就可以提前知道繪制條的順序。
然后,只需按照相同的順序使用您需要的數據制作 dataframe。
import seaborn as sns
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")
x_col = 'day'
x_order = ['Fri', 'Thur', 'Sat', 'Sun']
hue_col = 'sex'
hue_order = ['Male','Female']
counts = tips.groupby([hue_col, x_col]).size().reindex(pd.MultiIndex.from_product([hue_order,x_order]))
plt.figure()
ax = sns.barplot(x="day", y="total_bill", order=x_order, hue="sex", hue_order=hue_order, data=tips)
for p,c in zip(ax.patches,counts):
ax.annotate("%d" % c, (p.get_x() + p.get_width() / 2., p.get_height()),
ha='center', va='center', fontsize=11, color='gray', xytext=(0, 20),
textcoords='offset points')
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.