How get the (x,y) position pointing with mouse in an interactive plot (Python Matplotlib)?

MatplotlibPythonData Visualization

To get the (x, y) positions pointing with mouse in an interactive plot, we can take the following steps


  • Set the figure size and adjust the padding between and around the subplots.

  • Create a new figure or activate an existing figure.

  • Bind the function *mouse_event* to the event *button_press_event*.

  • Create x and y data points using numpy.

  • Plot the x and y data points using plot() method.

  • To display the figure, use Show() method.


import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

def mouse_event(event):
   print('x: {} and y: {}'.format(event.xdata, event.ydata))

fig = plt.figure()
cid = fig.canvas.mpl_connect('button_press_event', mouse_event)

x = np.linspace(-10, 10, 100)
y = np.exp(x)

plt.plot(x, y)


It will produce the following output −

Now, click anywhere on the plot and it will show the coordinates of the points on the console −

x: -3.633289020076159 and y: 7344.564590474489
x: 3.2193731551790172 and y: 3255.6463283494704
x: 8.680088326085489 and y: 802.2953710744596
x: 7.680741758860773 and y: 11269.926122114506
x: 0.6139338906288732 and y: 16503.741497634528
Updated on 19-Oct-2021 08:36:26