matplotlib.pyplot.connect() in Python with example

Matplotlib is a powerful library or module in Python which provides interfaces like MATLAB and is used for plotting various graphs and data visualization. Matplotlib.pyplot is an API for matplotlib module of Python. So in this particular tutorial, we will see matplotlib.pyplot.connect() in Python with the help of an example.

matplotlib.pyplot.connect() function:

An event that consists of a string s can be connected to a function with the help of this method.

The syntax for this method is given below:

matplotlib.pyplot.connect(s, func)


An example is given below to clear all your doubts regarding matplolib.pyplot.connect() method. So read the tutorial carefully and enjoy the session of coding in Python.

This method involves certain parameters like button_press_event, motion_notify_event,etc. In this method the first step is to install all the required libraries from the command prompt of the system to your code space extension. The next step is to put the values for the plot of the figure and then get the x and y pixel coordinates and get the axes instance using event.inaxes which will print the x and y data coordinates in the plot. Then two parameters are used for plotting a graph named as ‘button_press_event‘, ‘motion_notify_event’,etc for on_move and on_click functions. At last print the plot using function. The following code is given below for your reference:

#import the required modules
from matplotlib.backend_bases import MouseButton
import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0.0, 2.0, 0.02)
s = np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)

#use on_move function 
def on_move(event):
  # get the x and y pixel coords
  x, y = event.x, event.y
  if event.inaxes:
    ax = event.inaxes # the axes instance
        #print data coor
    print('data coordinates % f % f' % (event.xdata,

def on_click(event):
  if event.button is MouseButton.LEFT:
    print('disconnecting callback')

binding_id = plt.connect('motion_notify_event',

plt.connect('button_press_event', on_click)
#show the plot



Leave a Reply

Your email address will not be published. Required fields are marked *