pythonmatplotlibmplcursors

How to add hovering annotations with multiple curves


I am using matplotlib to plot multiple curves (time series) in one plot. To do this, I use a for loop as seen below.

%matplotlib

for i in range(0, len(force)):

    plt.plot(distance, (force[i]), alpha=0.1)
    
    plt.xlabel('Distance [mm]', fontsize=12)
    plt.ylabel('Force [N]', fontsize=12)

Unfortunately, with the number of curves (approx. 70) that I have, the plot would be unreadable if I labeled each curve. Does anyone know of a way to create labels that only appear when the cursor hovers in the vicinity of that curve (timeseries)?

I looked on the example from this post, but have no clue how to adapt it to my issue:

Possible to make labels appear when hovering over a point in matplotlib?


Solution

  • You could use mplcursors. Each curve can have a unique label, which is shown by default.

    from matplotlib import pyplot as plt
    import mplcursors
    import numpy as np
    
    force = np.random.randn(70, 100).cumsum(axis=1)
    force -= force.mean(axis=1, keepdims=True)
    plt.figure(figsize=(12, 5))
    for i in range(len(force)):
         plt.plot(force[i], alpha=0.2, label=f'force[{i}]')
    plt.margins(x=0.01)
    cursor = mplcursors.cursor(hover=True)
    plt.show()
    

    mplcursors showing 70 labeled curves

    If you're working with a Jupyter notebook, you might need %matplotlib nbagg or %matplotlib qt instead of %matplotlib inline to enable interactivity.