Untitled

mail@pastecode.io avatar
unknown
python
10 days ago
2.5 kB
0
Indexable
Never
import numpy as np
import matplotlib.pyplot as plt

def makedatatip(hObj, index):
    def create_datatip(h_data_cursor_mgr, h_obj):
        return h_data_cursor_mgr.create_artists(h_obj)

    def update_data_cursors(h_data_cursor_mgr):
        h_data_cursor_mgr.update()

    if len(hObj) != 1:
        raise ValueError('HOBJ must be scalar.')
    if not plt.gca().findobj(hObj):
        raise ValueError('HOBJ is an invalid handle object.')

    is_image = hObj[0].get_type() == 'image'  # Determine if target is image

    try:
        X = hObj[0].get_xdata()
        Y = hObj[0].get_ydata()
        Z = hObj[0].get_zdata()
    except Exception as e:
        # Object must have an XData and YData property to be valid
        raise ValueError(f'Objects of class {type(hObj)} are not a valid targets for datatips.') from e

    if not index:
        return

    if not isinstance(index, np.ndarray) or index.dtype != 'int' or np.any(index < 1) or np.any(np.floor(index) != index) or np.any(np.isinf(index)):
        raise ValueError('Subscript indices must be positive integers.')

    if np.ndim(index) == 1 or (np.ndim(index) == 2 and np.size(index, 1) == 2):
        h_datatip = [None] * len(index)
        index = np.ravel(index)
        is_linear = True
    else:
        h_datatip = [None] * np.size(index, 0)
        is_linear = False

    h_data_cursor_mgr = plt.get_current_fig_manager().datacursor
    for n in range(len(index)):
        if is_image and is_linear:
            i, j = np.unravel_index(index[n], (X.shape[0], Y.shape[0]))
            pos = [i, j, 1]
        elif is_image:
            pos = [index[n, 0], index[n, 1], 1]
        elif Z is None:
            pos = [X[index[n]], Y[index[n]]]
        elif is_linear:
            pos = [X[index[n]], Y[index[n]], Z[index[n]]]
        else:
            pos = [X[index[n, 0], index[n, 1]], Y[index[n, 0], index[n, 1]], Z[index[n, 0], index[n, 1]]]

        h_datatip[n] = create_datatip(h_data_cursor_mgr, hObj[0])
        if is_image:
            h_datatip[n].data = {'index': pos, 'position': pos[:2]}
        else:
            h_datatip[n].data = {'index': index[n], 'position': pos}

        h_datatip[n].position = pos

    update_data_cursors(h_data_cursor_mgr)

    return h_datatip

# Example usage
x = np.arange(1, 11)
y = np.random.rand(10)
hPlot, = plt.plot(x, y)
makedatatip([hPlot], np.array([[3, 8]]))
plt.show()
Leave a Comment