我使用具有多个索引的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(),但我尝试的所有组合都无法工作。
发布于 2020-09-07 06:44:23
我使用了以下测试数据:
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()并得到以下结果:

正确生成注释的诀窍是:
annot_dy.
H 112ha(水平对齐)作为‘中心’,H 213H 114移位y坐标一点向上(如果需要的话,使用of值进行实验)。我还添加了ax.set_xlim(190,280),以便将注释保留在图片矩形中。也许你不需要它。
https://stackoverflow.com/questions/63770443
复制相似问题