Categories
Python Answers

How to add hovering annotations in Python matplotlib?

Spread the love

Sometimes, we want to add hovering annotations in Python matplotlib.

In this article, we’ll look at how to add hovering annotations in Python matplotlib.

How to add hovering annotations in Python matplotlib?

To add hovering annotations in Python matplotlib, we can call mpl_connect to add an event listener to watch for hovers.

For instance, we write

import matplotlib.pyplot as plt

fig = plt.figure()
plot = fig.add_subplot(111)

for i in range(4):
    plot.plot([i * 1, i * 2, i * 3, i * 4], gid=i)

def on_plot_hover(event):
    for curve in plot.get_lines():
        if curve.contains(event)[0]:
            print('over %s' % curve.get_gid())


fig.canvas.mpl_connect('motion_notify_event', on_plot_hover)
plt.show()

to create a curve plot with

fig = plt.figure()
plot = fig.add_subplot(111)

for i in range(4):
    plot.plot([i * 1, i * 2, i * 3, i * 4], gid=i)

Then we define the on_plot_hover that gets the curve we hovered over by looping through them and then get the one that has the event mouse position.

Next, we use that as the hover event listener with

fig.canvas.mpl_connect('motion_notify_event', on_plot_hover)

Conclusion

To add hovering annotations in Python matplotlib, we can call mpl_connect to add an event listener to watch for hovers.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *