我有一个动画散点图,显示多年来每个国家的人均 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
最佳答案
Customization mplcursors 文档的部分指出,我可以简单地使用 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')
关于python - 在散点图的工具提示中为每个气泡显示一个标签 (Matplotlib),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50703051/