[英]How to annotate text on horizontal Seaborn barplot?
我有一個問題,一旦我想注釋我的水平條,就會出現一些錯誤消息:
posx 和 posy 應該是有限值
然后我查看了代碼,令人驚訝的是我得到了一些 nan 值,這些值僅在使用hue
參數時出現。
代碼:
ax = sns.barplot(x="Points", y="Characters", hue="Average Speeds", data=albion_dataset, palette="Set1", dodge=False)
for p in ax.patches:
width = p.get_width()
print(width)
輸出:
南
南
2.57562
南
南
南
南
1.526325
南
...
但是當我刪除hue
選項時,就沒有 nan 並且注釋工作完美無缺。 數據框本身沒有 nan 值。 如何解決這個問題,以便我可以使用色調功能。 dtypes 是 x 的floats
,y 的色調和object
。
更新:找到了一種注釋條的方法,但現在最后一個條沒有注釋文本。
i = 0
for p in ax.patches:
ax.annotate("%.4f" % albion_dataset["Average Speeds"][i], (p.get_x() + p.get_width(), p.get_y() + 1.2),
xytext=(5, 10), textcoords='offset points')
print(i)
i += 1
此外,我如何將色調圖例中的文本添加到條形圖中,因為上面的代碼沒有考慮色調值的順序。 因此,我在條形圖上得到了錯誤的值。
一種選擇是依賴補丁本身的寬度,而不是嘗試將條形與數據框匹配:
tips = sns.load_dataset("tips")
tips.loc[(tips.day=="Thur")&(tips.sex=='Female')] = np.nan
tips.loc[(tips.day=="Sat")&(tips.sex=='Male')] = np.nan
ax = sns.barplot(y="day", x="total_bill", hue="sex", data=tips, ci=None)
for p in ax.patches:
ax.annotate("%.4f" % p.get_width(), xy=(p.get_width(), p.get_y()+p.get_height()/2),
xytext=(5, 0), textcoords='offset points', ha="left", va="center")
如果您需要知道hue
的值(或訪問與每個條形對應的子數據框),那么我建議您明確傳遞一個order=
和一個hue_order=
參數,以便您知道條形的繪制順序。
import itertools
tips = sns.load_dataset("tips")
tips.loc[(tips.day=="Thur")&(tips.sex=='Female')] = np.nan
tips.loc[(tips.day=="Sat")&(tips.sex=='Male')] = np.nan
group_col = 'day'
hue_col = 'sex'
order=['Sat','Sun','Thur','Fri']
hue_order = ['Female','Male']
ax = sns.barplot(y=group_col, x="total_bill", hue=hue_col, order=order, hue_order=hue_order, data=tips, ci=None)
for p,(cur_hue, cur_y) in zip(ax.patches,itertools.product(hue_order,order)):
temp_df = tips.loc[(tips[group_col]==cur_y)&(tips[hue_col]==cur_hue)]
# temp_df is the sub-dataframe that corresponds to the current bar `p`. It can contain 0 or more rows
pos = p.get_width() if p.get_width()>0 else 0
ax.annotate(cur_hue, xy=(pos, p.get_y()+p.get_height()/2),
xytext=(5, 0), textcoords='offset points', ha="left", va="center")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.