How to show mouse release event coordinates with Matplotlib?


To show mouse release event coordinates with matplotlib, we can take the following 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_release_event*.
  • Print event and its x and y data.
  • 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.button, event.xdata, event.ydata)
fig, ax = plt.subplots()
ax.plot(range(10))
fig.canvas.mpl_connect('button_release_event', onclick)
plt.show()

Output

MouseButton.LEFT 4.961566107601828 1.6644009000562534
MouseButton.LEFT 6.782345894140708 3.7026907931745727
MouseButton.LEFT 2.98552602918754 7.177807987999249

Updated on: 15-May-2021

374 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements