在散点图中的工具提示中每个气泡显示一个标签 (Matplotlib)

Display one label per bubble in tooltips in a scatter plot (Matplotlib)

我有一个动画散点图,显示多年来每个国家/地区的人均 GDP x 预期寿命。 我想添加一个工具提示,当有人将鼠标悬停在气泡上时会出现,我希望它显示气泡对应的国家/地区的名称。

我尝试使用 mplcursors 这样做,但在弄清楚如何显示国家名称时遇到了麻烦,因为它在每个气泡中都是不同的。

情节如下:

ax.scatter(y = data['lifeExpec'],
    x = data['gdp'],
    s = data['population']/40000,
    c = data['region'].astype('category').cat.codes,
    cmap = cm.viridis,
    edgecolors = 'none',
    alpha = 0.5)

 c1 = mplcursors.cursor(ax, hover=True)
    @c1.connect("add")
    def _(sel):
        sel.annotation.set_text(<????>)
        sel.annotation.set(position=(-15,15), 
                           fontsize=8, 
                           ha='center', 
                           va='center')

这是我的数据框示例:

country, gdp, lifeExpec, year, population, region
USA, 20000, 70, 2005, 100000, America
USA, 21000, 72, 2007, 104000, America
Canada, 20500, 71, 2005, 50000, America
Canada, 23000, 74, 2007, 53000, America

mplcursors 文档的 Customization 部分指出我可以简单地使用 target.index 来指示所选取的点的索引。这是最终代码:

c1 = mplcursors.cursor(ax, hover=True)
    @c1.connect("add")
    def _(sel):
        sel.annotation.set_text(data['country'].iat[sel.target.index])
        sel.annotation.set(position=(-15,15), 
                           fontsize=8, 
                           ha='center', 
                           va='center')