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

标签 python python-3.x matplotlib mplcursors

我有一个动画散点图,显示多年来每个国家的人均 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/

相关文章:

python - 了解 MySQL 游标类型

python - Pandas iterrows() row.get() 方法返回系列而不是单元格值

python - 在pygame中旋转图像

python - 使用 `.rstrip()` 和 `.strip() to remove newline `\n`

基于循环计数器的python matplotlib轴标签下标

python - 通过在 matplotlib 中使用 Latex 在 xticklabel 中的正值和负值之间的差异

python - Pymongo:从数组中删除一个元素

python - 需要帮助将列表中的整数转换为字符串

python - 生成器内的 for 循环?

python - Google Collab Notebook与普通的Python脚本创建了不同类型的绘图大小