用多索引标注散点图

2024-06-03 04:21:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经构建了一个散点图,它使用了来自多索引数据框的数据。指数是国家和年份

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(),但我试过的所有组合都不起作用


Tags: 数据lambdaplt国家axmeancountryloc
1条回答
网友
1楼 · 发布于 2024-06-03 04:21:24

我使用了以下测试数据:

               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()

并得到如下结果:

enter image description here

正确生成批注的技巧是:

  • 枚举已生成的系列对象之一的索引, 因此,txt包含国家名称
  • 从已生成的系列对象中获取值(不计算 这些值(请重复)
  • 通过当前索引值定位两个坐标
  • 要将这些注释放在各个点的正上方,请使用:
    • ha(水平定线)作为“中心”
    • y坐标向上移动一点(如果需要,用另一个进行试验 的值不能小于eem>

我还添加了ax.setxlim(190280),以便在 图片矩形。也许你不需要它

相关问题 更多 >