Home > other >  How do I use mpl_connect to highlight points different from the one selected?
How do I use mpl_connect to highlight points different from the one selected?

Time:01-31

I have a simple time series (x, y, t). I have plotted all the points (x,y) on a two-dimensional scatter plot using matplotlib and am able to access the time value for each point by making "t" a label and using mplcursors connect:

labels = data.index
points = plt.scatter(data['Column1'], data['Column2'], color=color)
cursor = mplcursors.cursor(points, hover=2)
cursor.connect("add", lambda sel: sel.annotation.set_text(labels[sel.index]))

I am looking for a way that upon selection of a point, that point as well as the next point in the time series will be highlighted, so the viewer can see where the series is going. I can always put the coordinates of the following point in as a label, but I would like the visual.

CodePudding user response:

You can draw a small circle, e.g. via plt.scatter at the position of the next point. Appending it to sel.extras takes care of removing it as soon as the current highlight is removed.

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import mplcursors

def annotation_func(sel):
    if sel.index < len(data) - 1:
        x0, y0 = data.iloc[sel.index][['Column1', 'Column2']]
        x1, y1 = data.iloc[sel.index   1][['Column1', 'Column2']]
        circle = plt.scatter(x1, y1, s=100, fc='none', ec='red', lw=2)
        line, = plt.plot([x0, x1], [y0, y1], c='red', lw=1, ls=':')
        sel.extras.append(circle)
        sel.extras.append(line)
    sel.annotation.set_text(data.index[sel.index])

data = pd.DataFrame({'Column1': np.arange(30),
                     'Column2': np.random.randn(30).cumsum()},
                    index=[f'P{i}' for i in range(30)])

points = plt.scatter(data['Column1'], data['Column2'], color='turquoise')
cursor = mplcursors.cursor(points, hover=2)
cursor.connect("add", annotation_func)
plt.show()

mplcursors add extra circle and line

  • Related