簡體   English   中英

用多索引注釋散點圖

[英]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]))

我不確定如何表明我想要國家/地區名稱,因為給定國家/地區的所有lambdapib_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()

並得到以下結果:

在此處輸入圖片說明

正確生成注釋的技巧是:

  • 枚舉已生成的Series對象之一的索引,以便txt包含國家/地區名稱。
  • 從已經生成的Series對象中獲取值(不要再次計算這些值)。
  • 按當前索引值定位兩個坐標。
  • 要將這些注釋放在相應的點上方,請使用:
    • ha (水平對齊)為'center'
    • 移位y坐標稍微向上(如果需要的話,實驗annot_dy的othere值。

我還添加了ax.set_xlim(190,280)以將注釋保留在圖片矩形內。 也許你不需要它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM