, y:<>" How can I change the code so I see: "xaxis:<>, yaxis:<>" Also i" /> , y:<>" How can I change the code so I see: "xaxis:<>, yaxis:<>" Also i" /> , y:<>" How can I change the code so I see: "xaxis:<>, yaxis:<>" Also i"/>

How to change the x: and y: when using mplcursor in python

73 Views Asked by At

Using a simple code like below, the annotations I get for the cursors are "x:<>, y:<>" How can I change the code so I see: "xaxis:<>, yaxis:<>"

Also it would help to know how to do this if I have multiple subplots... enter image description here

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

data = np.outer(range(10), range(1, 5))

fig, ax = plt.subplots()
lines = ax.plot(data)
ax.set_title("Click somewhere on a line.\nRight-click to deselect.\n"
         "Annotations can be dragged.")

mplcursors.cursor(lines)  # or just mplcursors.cursor()
plt.xlabel('xaxis')
plt.ylabel('ylabel')
plt.show()
1

There are 1 best solutions below

0
JohanC On

You can change the annotation by adding a function to be called when the annotation is activated. Such a function can be in lambda form ("anonymous function"), or a separately written function in Python. When working with subplots, a cursor can be added to each of them.

You can take a look at the examples in the official documentation to get an overview of the possibilities.

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

def annotation_function(sel):
    ax = sel.artist.axes
    sel.annotation.set_text(
        f'{ax.get_xlabel()}: {sel.target[0]:.2f}\n{ax.get_ylabel()}: {sel.target[1]:.2f}')

fig, axs = plt.subplots(nrows=2, ncols=3, figsize=(15, 10))
for i, ax_row in enumerate(axs):
    for j, ax in enumerate(ax_row):
        data = np.random.normal(0.1, 100, size=(50, 5)).cumsum(axis=0)
        lines = ax.plot(data)
        ax.set_title(f'Subplot <{i},{j}>')
        ax.set_xlabel('x_' + ''.join(np.random.choice([*'ABCDEF'], np.random.randint(3, 8))))
        ax.set_ylabel('y_' + ''.join(np.random.choice([*'ABCDEF'], np.random.randint(3, 8))))

        cursor = mplcursors.cursor(lines)
        cursor.connect('add', annotation_function)
plt.tight_layout()
plt.show()

mplcursors with subplots and adapted annotations