Store mouse click event coordinates with Matplotlib

MatplotlibPythonData Visualization

To store mouse event coordinates with matplotlib, we can use "button_press_event" event.−

Steps

  • Set the figure size and adjust the padding between and around the subplots.
  • Create a figure and a set of subplots.
  • Plot a line in the range of 10
  • Bind the function *onclick* to the event *button_press_event*.
  • Print the x and y data of the event.
  • To display the figure, use show() method.

Example

from matplotlib import pyplot as plt
plt.rcParams['backend'] = 'TkAgg'
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
def onclick(event):
print([event.xdata, event.ydata])
fig, ax = plt.subplots()
ax.plot(range(10))
fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()

Output

[6.277811659536052 6.218189947945731]
[4.9416949672083685 3.7079096112932475]
[8.221254287227506 3.4145010811941963]
raja
Published on 15-May-2021 12:39:54
Advertisements