How to add interactivity by capturing mouse events

Initially, you must import everything that we normally use and use the interactive Notebook backend. Now, the user is not familiar with asynchronous programming with the callback function. This takes in an event, which is then called when that event occurs. The important information of that event is passed as an argument to that function.

We will begin by defining a function called draw_circle (event). These are the events that are passed by Matplotlib callbacks, and they include information about the event. So, in the case of a mouse click, it would be where on the plot the click has occurred.

Call the plt.plot function with the x data and the y data of that event, along with a circle. Note that we are calling the canvas.draw method on the figure. Here, the canvas object that belongs to each figure is essentially the screen object. The canvas object actually captures these events and is essentially the lowest-level interface for a figure. Next, add a callback to this canvas using the mpl_connect method, along with button_press_event:

# Mouse click events with button_press_event
plt.plot(np.random.normal(size=100))
def draw_circle(event):
# Draw a circle
plt.plot(event.xdata, event.ydata, 'bo')
# After the figure is updated, re-draw the canvas
plt.gcf().canvas.draw()
# Add a listener for mouse button press
cid = plt.gcf().canvas.mpl_connect('button_press_event', draw_circle)

The output of the preceding code is as follows:

There are a lot of different events that we can add callbacks for. If you're interested in learning more, you can take a look at the Matplotlib documentation: https://matplotlib.org/contents.html.

We can see that every time we click on this plot, a small circle is drawn, as shown in the following output:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset