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.
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
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-axisx = linspace(-3, 3)## Plotting curvesplot(x,sin(x),'r.',label="sin graph")plot(x,cos(x), 'b--',label="cos graph")plot(x, -sin(x), 'g+',label="- sin graph")## Adding labelstitle("Sine and cosine graphs", color='b')xlabel("Angle/ radians", color='r')ylabel("Function value", color= 'r')legend(loc='best')## Displaying the final chartshow()
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