[英]Annotate scatter plot with multiindex
我使用來自具有多索引的 DataFrame 的數據構建了一個散點圖。 索引是國家和年份
fig,ax=plt.subplots(1,1)
rel_pib=welfare["rel_pib_pc"].loc[:,1960:2010].groupby("country").mean()
rel_lambda=welfare["Lambda"].loc[:,1960:2010].groupby("country").mean()
ax.scatter(rel_pib,rel_lambda)
ax.set_ylim(0,2)
ax.set_ylabel('Bienestar(Lambda)')
ax.set_xlabel('PIBPc')
ax.plot([0,1],'red', linewidth=1)
我想用國家/地區名稱(如果可能,還有 Lambda 值)注釋每個點。 我有以下代碼
for i, txt in enumerate(welfare.index):
plt.annotate(txt, (welfare["rel_pib_pc"].loc[:,1960:2010].groupby("country").mean()[i], welfare["Lambda"].loc[:,1960:2010].groupby("country").mean()[i]))
我不確定如何表明我想要國家/地區名稱,因為給定國家/地區的所有lambda
和pib_pc
值都作為單個值給出,因為我使用的是.mean()
函數。
我曾嘗試使用.xs()
但我嘗試過的所有組合都不起作用。
我使用了以下測試數據:
rel_pib_pc Lambda
country year
Country1 2007 260 1.12
2008 265 1.13
2009 268 1.10
Country2 2007 230 1.05
2008 235 1.07
2009 236 1.04
Country3 2007 200 1.02
2008 203 1.07
2009 208 1.05
然后,為了生成散點圖,我使用了以下代碼:
fig, ax = plt.subplots(1, 1)
ax.scatter(rel_pib,rel_lambda)
ax.set_ylabel('Bienestar(Lambda)')
ax.set_xlabel('PIBPc')
ax.set_xlim(190,280)
annot_dy = 0.005
for i, txt in enumerate(rel_lambda.index):
ax.annotate(txt, (rel_pib.loc[txt], rel_lambda.loc[txt] + annot_dy), ha='center')
plt.show()
並得到以下結果:
正確生成注釋的技巧是:
我還添加了ax.set_xlim(190,280)以將注釋保留在圖片矩形內。 也許你不需要它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.