What is Pylab?

The pylab module is a part of the matplotlib library in Python. It combines matplotlib.pyplot (to create visualizations) and numpy packages (to create, modify, and manipulate datasets) to provide users with a convenient way of plotting charts.

Installation

The pylab module is a part of the matplotlib plotting library, so it is installed alongside matplotlib. The following command installs the matplotlib library (this includes the pylab module):

pip install matplotlib  

Moreover, we must install the numpy library because the pylab module depends on it. The following command installs the numpy library:

pip install numpy  

Plotting curves

Now that we have an overview of installing the required libraries, let’s look at how to use pylab to create data visualizations.

Note: The pylab package has already been installed for you in the working example set up below.

from pylab import *
## Setting the x-axis
x = linspace(-3, 3)
## Plotting curves
plot(x,sin(x),'r.',label="sin graph")
plot(x,cos(x), 'b--',label="cos graph")
plot(x, -sin(x), 'g+',label="- sin graph")
## Adding labels
title("Sine and cosine graphs", color='b')
xlabel("Angle/ radians", color='r')
ylabel("Function value", color= 'r')
legend(loc='best')
## Displaying the final chart
show()

Explanation

Line 1: We import all the dependencies from the pylab module.

Line 2: We create the x-axis for our chart using a linearly spaced vector.

Lines 5–7: These lines create our sine, cosine, and negative cosine curves and set their respective titles.

Lines 9–11: These lines add the title, x-axis, and y-axis labels.

Line 12: This line creates a legend that adds the labels we gave to our plots to the chart. Moreover, by setting location= best, the function chooses the most suitable location to add the label to the chart.

Line 14: The show() function displays the final chart.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved