Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays. It provides an object-oriented API that helps in embedding plots in applications using Python GUI toolkits such as PyQt, WxPython Tkinter. It can be used in Python and IPython shells, Jupyter notebook, and web application servers also.
How to install matplot
Matplotlib and its dependency packages are available in the form of wheel packages on the standard Python package repositories and can be installed on Windows, Linux as well as macOS systems using the pip package manager.
python -m pip install -U pip python -m pip install -U matplotlib
matplotlib.pyplot is a collection of command style functions that make Matplotlib work like MATLAB. Each pyplot function makes some changes to a figure. For example, a function creates a figure, a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc.
The following are the list of plots that are available in matplot
Plot -It is used to plot lines and/or markers to the Axes
Scatter Make a scatter plot of x vs y
Bar Make a bar plot
Barh Make a horizontal bar plot
Boxplot Make a box and whisker plot
Hist Plot a histogram
Pie Plot a pie chart
Step Make a step plot
Stem Create a stem plot
Stackplot Draw a stacked area plot
The following are the list of Axis Functions that are available in matplot
Axes Add axes to the figure
Text Add text to the axes.
Title Set a title of the current axes
X – label Set the x-axis label of the current axis
Y – label Set the y-axis label of the current axis
X – lim Get or set the x limits of the current axes
Y – lim Get or set the y limits of the current axes
X – ticks Get or set the x-limits of the current tick locations and labels. Y – ticks Get or set the y-limits of the current tick locations and labels.
The following are the list of Figure Functions that are available in matplot
Figtext Add text to figure
Figure Creates a new figure
Sample Plot using matplot
Create a new untitled notebook with the .ipynb extension (stands for the IPython notebook)
We shall now display a simple line plot between 2 arrays To begin with, the Pyplot module from the Matplotlib package is imported, with an alias plt as a matter of convention.
import matplotlib.pyplot as plt
Next we need an array of numbers to plot. Various array functions are defined in the NumPy library which is imported with the np alias.
import numpy as np
Now we will obtain the ndarray objects for x and y
x = np.random.randint(5, 50,10)
## To generate random numbers for plotting
y = 2*x
The values from two arrays are plotted using the plot()
function. plt.plot(x,y)
You can set the plot title, and labels for x and y axes.
plt.xlabel("X-values")
plt.ylabel("Y-values")
plt.title('X vs Y’)
The Plot viewer window is invoked by the show() function plt.show()
The complete program is as follows
import numpy as np
import matplotlib.pyplot as plt
x=np.random.randint(5,50,10)
y=2*x
plt.xlabel("X-values")
plt.ylabel("Y-values")
plt.title('X vs Y')
plt.plot(x,y)
Output:
To display plot outputs inside the notebook itself and not in the separate viewer , enter the following magic statement
%matplotlib inline
Matplotlib – PyLab module
PyLab is a procedural interface to the Matplotlib object-oriented plotting library. Matplotlib is the whole package; matplotlib.pyplot is a module in Matplotlib, and PyLab is a module that gets installed alongside Matplotlib.
PyLab is a convenience module that imports matplotlib.pyplot (for plotting) and NumPy (for Mathematics and working with arrays) in a single namespace. Although many examples use PyLab, it is no longer recommended. Now we will plot a curve and try to play with the color and markers style
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-3, 3, 30)
y = x**2
plt.plot(x,y)
Output:
Supported marker styles :
“+” , “,” , “.” , “1” , “2” , “3” , “4” Supported line styles :
“–” , “– –” , “-.” , “:” , “steps”
Supported colour formats :
“b” , “g” , “r” , “c” , “m” , “y” , “k” , “w”
To plot symbols rather than lines and change colour , we need to provide an additional string argument.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-3, 3, 30)
y = x**2
## “g” represents the colour of the graph
plt.plot(x,y,’g’)
Output:
Now we will change the marker style of the above graph.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-3, 3, 30)
y = x**2
## “r” represents the colour and “-o” represents the marker style plt.plot(x,y,’r-o’)
Output:
Plotting curves of given equation
Here, we use NumPy which is a general-purpose array-processing package in python.
• To set the x-axis values, we use the np.arange() method in which the first two arguments are for range and the third one for step-wise increment. The result is a numpy array.
• To get corresponding y-axis values, we simply use the predefined np.sin() method on the numpy array.
• Finally, we plot the points by passing x and y arrays to the plt.plot() function.
x = np.arange(0, 2*(np.pi), 0.1) y = np.sin(x)
plt.plot(x, y)
Output:
x = np.linspace(-3, 3, 30)
y = np.linspace(-3, 3, 20)
plt.plot(x, sin(x),'g--') plt.scatter(y,sin(y),c='b',marker='o') plt.show()
Output:
Plots can be overlaid. Just use the multiple plot commands.
x = np.linspace(-3, 3, 30)
plt.plot(x, sin(x),’b’)
plt.plot(x, cos(x), ‘r’)
plt.plot(x, -sin(x), ‘g’)
plt.legend([‘Sin’,’Cos','-Sin'])
Output:
• Here, we plot three curves on the same graph. We differentiate between them by giving them a name(label) which is passed as an argument of .plot() function.
• The small rectangular box giving information about the type of line and its color is called a legend. We can add a legend to our plot using .legend() function.
Multiple Subplots
Sometimes it is helpful to compare different views of data side by side. To this end, Matplotlib has the concept of subplots: groups of smaller axes that can exist together within a single figure. These subplots might be insets, grids of plots, or other more complicated layouts. In this section, we’ll explore four routines for creating subplots in Matplotlib. This is the general syntax for subplots
subplot(nrows, ncols, index)
Now we will try to create a empty 2 X 2 layout
plt.subplots(2,2)
Output:
Now we will try to plot graphs using subplot function
x = np.linspace(-3, 3, 30)
plt.subplot(2,2,1)
plt.plot(x, sin(x),’b’)
plt.subplot(2,2,2)
plt.plot(x, cos(x),’r’)
plt.subplot(2,2,3)
plt.plot(x, -sin(x),’g’)
plt.subplot(2,2,4)
plt.plot(x, -cos(x),’y')
Output:
In the next article, we will learn how to visualize the remaining types of plots.
4 Responses