1

I have an animated scatter plot which shows GDP per capita x life expectancy per country through the years. I want to add a tooltip that will appear when someone hovers the mouse over a bubble, and I want it to display the name of the country that bubble is equivalent to.

I attempted to use mplcursors to do so, but had trouble figuring out how to display the name of the country, since it's a different one in each bubble.

Here's the plot:

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

Here's a sample of my dataframe:

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
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Geralt
  • 180
  • 2
  • 16
  • Label may not be the best way to go about doing this... – Mad Physicist Jun 05 '18 at 14:54
  • @MadPhysicist I edited the question and added my attempt to use mplcursors – Geralt Jun 05 '18 at 15:02
  • 1
    The solution to this is in principle given in the answer to [Possible to make labels appear when hovering over a point in matplotlib?](https://stackoverflow.com/questions/7908636/possible-to-make-labels-appear-when-hovering-over-a-point-in-matplotlib). – ImportanceOfBeingErnest Jun 06 '18 at 00:45

1 Answers1

2

The Customization section of the mplcursors documentation states that I can simply use target.index to indicate the index of the point that was picked. Here's the final code:

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')
Geralt
  • 180
  • 2
  • 16