Search code examples
python-3.xmatplotlibmplcursors

How to have a fast crosshair mouse cursor for subplots in matplotlib?


In this video of backtrader's matplotlib implementation https://youtu.be/m6b4Ti4P2HA?t=2008 I can see that a default and very fast and CPU saving crosshair mouse cursor seems to exist in matplotlib.

I would like to have the same kind of mouse cursor for a simple multi subplot plot in matplotlib like this:

import numpy as np
import matplotlib

matplotlib.use('QT5Agg')
matplotlib.rcParams['figure.figsize'] = (20.0, 22.0)
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = plt.subplot(2, 1, 1)
ax2 = plt.subplot(2, 1, 2, sharex=ax1)

ax1.plot(np.array(np.random.rand(100)))
ax2.plot(np.array(np.random.rand(100)))

plt.show()

So, if I am with my mouse in the lower subplot, I want to see directly and very precisely, which value of x/y in the lower plot corresponds to which value pair in the upper plot.

I have found other solutions to do this but they seem to be very slow compared to the implementation in the video.


Solution

  • Sorry for the late answer, but I was horrified by how much code was suggested above, when there is this one-liner on matplotlib to do a simple crosshair accross different axes. It won't show your labels but it's CPU-light.

    from matplotlib.widgets import MultiCursor
    cursor = MultiCursor(fig.canvas, (ax[0], ax[1]), color='r',lw=0.5, horizOn=True, vertOn=True)