Matplotlib
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a
multi-platform data visualization library built on NumPy arrays and designed to work with the
broader SciPy stack. It was introduced by John Hunter in the year 2002.
python -mpip install -U matplotlib
from matplotlib import pyplot as plt
or
import matplotlib.pyplot as plt
Line plot :
# importing matplotlib module
from matplotlib import pyplot as plt
# x-axis values
x = [5, 2, 9, 4, 7]
# Y-axis values
y = [10, 5, 8, 4, 2]
# Function to plot
plt.plot(x,y)
# function to show the plot
plt.show()
Bar plot :
# importing matplotlib module
from matplotlib import pyplot as plt
# x-axis values
x = [5, 2, 9, 4, 7]
# Y-axis values
y = [10, 5, 8, 4, 2]
# Function to plot the bar
plt.bar(x,y)
# function to show the plot
plt.show()
Histogram :
# importing matplotlib module
from matplotlib import pyplot as plt
# Y-axis values
y = [10, 5, 8, 4, 2]
# Function to plot histogram
plt.hist(y)
# Function to show the plot
plt.show()
Scatter Plot :
# importing matplotlib module
from matplotlib import pyplot as plt
# x-axis values
x = [5, 2, 9, 4, 7]
# Y-axis values
y = [10, 5, 8, 4, 2]
# Function to plot scatter
plt.scatter(x, y)
# function to show the plot
plt.show()
Pyplot in Matplotlib
Matplotlib is a plotting library for creating static, animated, and interactive visualizations in
Python. Matplotlib can be used in Python scripts, the Python and IPython shell, web
application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc.
pip install matplotlib
Pyplot
Pyplot is a Matplotlib module which provides a MATLAB-like interface. Matplotlib is designed to
be as usable as MATLAB, with the ability to use Python and the advantage of being free and open-
source. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting
area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc. The various
plots we can utilize using Pyplot are Line Plot, Histogram, Scatter, 3D Plot, Image, Contour,
and Polar.
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.axis([0, 6, 0, 20])
plt.show()
Parameters: This function accepts parameters that enables us to set axes scales and format
the graphs. These parameters are mentioned below :-
plot(x, y): plot x and y using default line style and color.
plot.axis([xmin, xmax, ymin, ymax]): scales the x-axis and y-axis from minimum to
maximum values
plot.(x, y, color=’green’, marker=’o’, linestyle=’dashed’, linewidth=2, markersize=12):
x and y co-ordinates are marked using circular markers of size 12 and green color line with
— style of width 2
plot.xlabel(‘X-axis’): names x-axis
plot.ylabel(‘Y-axis’): names y-axis
plot(x, y, label = ‘Sample line ‘) plotted Sample Line will be displayed as a legend
Example 1: Linear Plot
# Python Program to illustrate Linear Plotting
import matplotlib.pyplot as plt
# year contains the x-axis values
# and e-india & e-bangladesh
# are the y-axis values for plotting
year = [1972, 1982, 1992, 2002, 2012]
e_india = [100.6, 158.61, 305.54, 394.96, 724.79]
e_bangladesh = [10.5, 25.21, 58.65, 119.27, 274.87]
# plotting of x-axis(year) and
# y-axis(power consumption)
with different colored labels of two countries
plt.plot(year, e_india, color ='orange',
label ='India')
plt.plot(year, e_bangladesh, color ='g',
label ='Bangladesh')
# naming of x-axis and y-axis
plt.xlabel('Years')
plt.ylabel('Power consumption in kWh')
# naming the title of the plot
plt.title('Electricity consumption per capita\
of India and Bangladesh')
plt.legend()
plt.show()
Example 2: Linear Plot with line formatting
# Python Program to illustrate Linear Plotting
import matplotlib.pyplot as plt
year = [1972, 1982, 1992, 2002, 2012]
e_india = [100.6, 158.61, 305.54,
394.96, 724.79]
e_bangladesh = [10.5, 25.21, 58.65,
119.27, 274.87]
# formatting of line style and
# plotting of co-ordinates
plt.plot(year, e_india, color ='orange',
marker ='o', markersize = 12,
label ='India')
plt.plot(year, e_bangladesh, color ='g',
linestyle ='dashed', linewidth = 2,
label ='Bangladesh')
plt.xlabel('Years')
plt.ylabel('Power consumption in kWh')
plt.title('Electricity consumption per \
capita of India and Bangladesh')
plt.legend()
plt.show()
Matplotlib – Axes Class
Axes class
Axes is the most basic and flexible unit for creating sub-plots. Axes allow placement of plots at any
location in the figure. A given figure can contain many axes, but a given axes object can only be in
one figure. The axes contain two axis objects 2D as well as, three-axis objects in the case of 3D.
Let’s look at some basic functions of this class.
axes() function
axes() function creates axes object with argument, where argument is a list of 4 elements [left,
bottom, width, height]. Let us now take a brief look to understand the axes() function.
axes([left, bottom, width, height])
import matplotlib.pyplot as plt
fig = plt.figure()
#[left, bottom, width, height]
ax = plt.axes([0.1, 0.1, 0.8, 0.8])
add_axes() function
Alternatively, you can also add the axes object to the figure by calling the add_axes() method. It
returns the axes object and adds axes at position [left, bottom, width, height] where all quantities are
in fractions of figure width and height.
Syntax :
add_axes([left, bottom, width, height])
import matplotlib.pyplot as plt
fig = plt.figure()
#[left, bottom, width, height]
ax = fig.add_axes([0, 0, 1, 1])
ax.legend() function
Adding legend to the plot figure can be done by calling the legend() function of the axes class. It
consists of three arguments.
Syntax :
ax.legend(handles, labels, loc)
import matplotlib.pyplot as plt
fig = plt.figure()
#[left, bottom, width, height]
ax = plt.axes([0.1, 0.1, 0.8, 0.8])
ax.legend(labels = ('label1', 'label2'),
loc = 'upper left')
ax.plot() function
plot() function of the axes class plots the values of one array versus another as line or marker.
Syntax : plt.plot(X, Y, ‘CLM’)
Parameters:
X is x-axis.
Y is y-axis.
‘CLM’ stands for Color, Line and Marker.
Example: The following example shows the graph of sine and cosine functions.
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(-np.pi, np.pi, 15)
C = np.cos(X)
S = np.sin(X)
# [left, bottom, width, height]
ax = plt.axes([0.1, 0.1, 0.8, 0.8])
# 'bs:' mentions blue color, square
# marker with dotted line.
ax1 = ax.plot(X, C, 'bs:')
#'ro-' mentions red color, circle
# marker with solid line.
ax2 = ax.plot(X, S, 'ro-')
ax.legend(labels = ('Cosine Function',
'Sine Function'),
loc = 'upper left')
ax.set_title("Trigonometric Functions")
plt.show()
How to create multiple subplots in Matplotlib
in Python?
To create multiple plots use matplotlib.pyplot.subplots method which returns the figure along
with Axes object or array of Axes object. nrows, ncols attributes of subplots() method
determine the number of rows and columns of the subplot grid.
By default, it returns a figure with a single plot. For each axes object i.e plot we can set title (set via
set_title()), an x-label (set via set_xlabel()), and a y-label set via set_ylabel()).
Example 1: 1-D array of subplots
# importing library
import matplotlib.pyplot as plt
# Some data to display
x = [1, 2, 3]
y = [0, 1, 0]
z = [1, 0, 1]
# Creating 2 subplots
fig, ax = plt.subplots(2)
# Accessing each axes object to plot the data through returned array
ax[0].plot(x, y)
ax[1].plot(x, z)
Example2: Stacking in two directions returns a 2D array of axes objects.
# importing library
import matplotlib.pyplot as plt
import numpy as np
# Data for plotting
x = np.arange(0.0, 2.0, 0.01)
y = 1 + np.sin(2 * np.pi * x)
# Creating 6 subplots and unpacking the output array immediately
fig, ((ax1, ax2), (ax3, ax4), (ax5, ax6)) = plt.subplots(3, 2)
ax1.plot(x, y, color="orange")
ax2.plot(x, y, color="green")
ax3.plot(x, y, color="blue")
ax4.plot(x, y, color="magenta")
ax5.plot(x, y, color="black")
ax6.plot(x, y, color="red")
How to Add Title to Subplots in Matplotlib?
Matplotlib : Matplotlib is an amazing visualization library in Python for 2D plots of arrays.
Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed
to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002.
Subplots : The subplots() function in pyplot module of matplotlib library is used to create a
figure and a set of subplots. Subplots are required when we want to show two or more plots
in same figure.
Title of a plot : The title() method in matplotlib module is used to specify title of the
visualization depicted and displays the title using various attributes.
Steps Needed
Import Libraries
Create/ Load data
Make subplot
Plot subplot
Set title to subplots.
Example 1: (Using set_title() method)
We use matplotlib.axes._axes.Axes.set_title(label) method to set title (string label) for the current
subplot Axes.
# importing packages
import numpy as np
import matplotlib.pyplot as plt
# create data
x=np.array([1, 2, 3, 4, 5])
# making subplots
fig, ax = plt.subplots(2, 2)
# set data with subplots and plot
ax[0, 0].plot(x, x)
ax[0, 1].plot(x, x*2)
ax[1, 0].plot(x, x*x)
ax[1, 1].plot(x, x*x*x)
# set the title to subplots
ax[0, 0].set_title("Linear")
ax[0, 1].set_title("Double")
ax[1, 0].set_title("Square")
ax[1, 1].set_title("Cube")
# set spacing
fig.tight_layout()
plt.show()
Example 2: (Using title.set_text() method)
# importing packages
import numpy as np
import matplotlib.pyplot as plt
# create data
x=np.array([1, 2, 3, 4, 5])
# making subplots
fig, ax = plt.subplots(2, 2)
# set data with subplots and plot
ax[0, 0].plot(x, x)
ax[0, 1].plot(x, x*2)
ax[1, 0].plot(x, x*x)
ax[1, 1].plot(x, x*x*x)
# set the title to subplots
ax[0, 0].title.set_text("Linear")
ax[0, 1].title.set_text("Double")
ax[1, 0].title.set_text("Square")
ax[1, 1].title.set_text("Cube")
# set spacing
fig.tight_layout()
plt.show()
Example 3: (Using plt.gca().set_title() method)
If you use Matlab-like style in the interactive plotting, then you could use plt.gca() to get the
reference of the current axes of the subplot and combine set_title() method to set title to the subplots
in Matplotlib.
# importing packages
import numpy as np
import matplotlib.pyplot as plt
# create data
x=np.array([1, 2, 3, 4, 5])
# making subplots
fig, ax = plt.subplots(2, 2)
# set data with subplots and plot
title = ["Linear", "Double", "Square", "Cube"]
y = [x, x*2, x*x, x*x*x]
for i in range(4):
# subplots
plt.subplot(2, 2, i+1)
# plotting (x,y)
plt.plot(x, y[i])
# set the title to subplots
plt.gca().set_title(title[i])
# set spacing
fig.tight_layout()
plt.show()
Example 4: (Using plt.gca().title.set_text() method)
If you use Matlab-like style in the interactive plotting, then you could use plt.gca() to get the
reference of the current axes of the subplot and combine title.set_text() method to set title to the
subplots in Matplotlib.
# importing packages
import numpy as np
import matplotlib.pyplot as plt
# create data
x=np.array([1, 2, 3, 4, 5])
# making subplots
fig, ax = plt.subplots(2, 2)
# set data with subplots and plot
title = ["Linear","Double","Square","Cube"]
y = [x, x*2, x*x, x*x*x]
for i in range(4):
# subplots
plt.subplot(2, 2, i+1)
# plotting (x,y)
plt.plot(x, y[i])
# set the title to subplots
plt.gca().title.set_text(title[i])
# set spacing
fig.tight_layout()
plt.show()