[英]Seaborn barplot label bars with 3rd variable
我對 Python 可視化相當陌生。 我有 3 個變量的數據; 月份、頻率和詞。 我想看看哪個詞在一個月內出現次數最多。
import pandas as pd
import seaborn as sns
test = pd.DataFrame({'month': ['2019-01','2019-02','2019-03','2019-04','2019-05'],
'freq':[3,5,22,6,3],
'word':['hello','world','seaborn','seaborn','python']})
sns.barplot(x = 'month', y = 'freq', data = test)
到目前為止,我在 x 軸上有月份,在 y 軸上有 freq。 但是,我想用那些月份出現的詞來標記條形圖。 例如,“你好”應該出現在 Jan-2019 欄上。
如果我理解正確,你可以這樣做:
import pandas as pd
import seaborn as sns
test = pd.DataFrame({'month': ['2019-01','2019-02','2019-03','2019-04','2019-05'],
'freq':[3,5,22,6,3],
'word':['hello','world','seaborn','exp','python']})
ax = sns.barplot(x = 'month', y = 'freq', data = test)
for bar, label in zip(ax.patches, test['word']):
x = bar.get_x()
width = bar.get_width()
height = bar.get_height()
ax.text(x+width/2., height + 0.2, label, ha="center")
使用plt.annotate將標簽放在所需的位置。
ha
和va
關鍵字負責正確(水平/垂直)對齊。
test = pd.DataFrame({'month': ['2019-01','2019-02','2019-03','2019-04','2019-05'],
'freq':[3,5,22,6,3],
'word':['hello','world','seaborn','seaborn','python']})
for i in test.index:
word = test.loc[i, "word"]
y = test.loc[i, "freq"]
plt.annotate(word, (i, y), ha="center", va="bottom")
sns.barplot(x = 'month', y = 'freq', data = test);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.