Structure of
matplotlib
• Matplotlib consists of three main layers.
Backend Layer
• It has three abstract classes:
• FigureCanvas: Defines the area on which
the figure is drawn.
• Renderer: It is the tool to draw on
FigureCanvas.
• Event: Handles user inputs such as
keybord strokes and mouse clicks.
Artist Layer
• Artist layer is composed of one object which
is Artist.
• Titles, lines, texts, axis labels are all instances of
Artist.
• Figure is the main Artist object that holds
everything together.
• #importing matplotlib
import matplotlib.pyplot as plt
%matplotlib inline#creating a figure artist
fig = plt.figure(figsize=(10,6))
<Figure size 720x432 with 0 Axes>
There are two types of artist objects:
• Composite: Figure, Axes
• Primitive: Line, Circle, Text
Scripting Layer
• Scripting layer is the matplotlib.pyplot interface. Thus, when
we create plots using “plt” after the following command.
• import matplotlib.pyplot as plt
• Scripting layer automates the process of putting everthing
together. Thus, it is easier to use than the Artist layer.
• #create array to be plotted
import numpy as np
ser = np.random.randn(50)#create the plot
fig = plt.figure(figsize=(10,6))
ax = fig.add_subplot(111)
ax.plot(ser)
• We have created a Figure and Axes. Then called plot function
on the Axes object and pass the array to be plotted. The
rendered plot is:
• This figure has 1 Axes but a figure can contain multiple Axes.
Let’s create one with multiple Axes:
• #arrays to be plotted
ser1 = np.random.randn(50)
ser2 = ser1**2#create figure and axes
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2,
sharey=True,figsize=(10,6))#plot the arrays on axes
ax1.plot(ser1)
ax2.plot(ser2)
• ser1 = np.random.randn(50)
ser2 = ser1**2fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2,
sharey=True, figsize=(12,6))ax1.plot(ser1)
ax1.grid()
ax1.set_title('First Series', fontsize=15)
ax1.set_ylabel('Values', fontsize=12)
ax1.set_xlabel('Timesteps', fontsize=12)ax2.plot(ser2)
ax2.set_title('Second Series', fontsize=15)
ax2.text(25,-1, 'First Series Squared', fontsize=12)
ax2.set_xlabel('Timesteps', fontsize=12)
• In addition to the titles and axis labels, we have added grid
lines to the first axes and a text artist to the second axes. The
plot we have produced:
Contour Plot using
Matplotlib – Python
• Contour plots also called level plots are a tool for doing
multivariate analysis and visualizing 3-D plots in 2-D space.
• Contour plots are widely used to visualize density, altitudes or
heights of the mountain as well as in the meteorological
department. Due to such wide
usage matplotlib.pyplot provides a method contour to make it
easy for us to draw contour plots.
• The matplotlib.pyplot.contour() are usually useful when Z =
f(X, Y) i.e Z changes as a function of input X and Y.
• Syntax: matplotlib.pyplot.contour([X, Y, ] Z, [levels], **kwargs)
• Parameters:
X, Y: 2-D numpy arrays with same shape as Z or 1-D arrays
such that len(X)==M and len(Y)==N (where M and N are rows
and columns of Z)
Z: The height values over which the contour is drawn. Shape is
(M, N)
levels: Determines the number and positions of the contour
lines / regions.
• Example #1: Plotting of Contour using conour() which
only plots contour lines.
• # Implementation of matplotlib functiont
• import matplotlib.pyplot as plt
• import numpy as np
• feature_x = np.arange(0, 50, 2)
• feature_y = np.arange(0, 50, 3)
• # Creating 2-D grid of features
• [X, Y] = np.meshgrid(feature_x, feature_y)
• fig, ax = plt.subplots(1, 1)
• Z = np.cos(X / 2) + np.sin(Y / 4)
• # plots contour lines
• ax.contour(X, Y, Z)
• ax.set_title('Contour Plot')
• ax.set_xlabel('feature_x')
• ax.set_ylabel('feature_y')
• plt.show()
• # Implementation of matplotlib function
• import matplotlib.pyplot as plt
• import numpy as np
• feature_x = np.linspace(-5.0, 3.0, 70)
• feature_y = np.linspace(-5.0, 3.0, 70)
• # Creating 2-D grid of features
• [X, Y] = np.meshgrid(feature_x, feature_y)
• fig, ax = plt.subplots(1, 1)
• Z = X ** 2 + Y ** 2
• # plots filled contour plot
• ax.contourf(X, Y, Z)
• ax.set_title('Filled Contour Plot')
• ax.set_xlabel('feature_x')
• ax.set_ylabel('feature_y')
• plt.show()
• Vector fields
• The quantity incorporating both magnitude and direction is
known as Vectors.
• In order to perform this task we are going to use
the quiver() method and the streamplot() method
in matplotlib module.
• Syntax:
• To plot a vector field using the quiver() method:
• matplotlib.pyplot.quiver(X, Y, U, V, **kw)
• Where X, Y define the Vector location and U, V are directional
arrows with respect of the Vector location.
• To plot a vector field using the streamplot() method:
• matplotlib.pyplot.streamplot(X, Y, U, V, density=1,
linewidth=None, color=None, **kw)
• Where X, Y are evenly spaced grid[1D array] and U and V
represent the stream velocity of each point present on the
grid. Density is the no. of vector per area of the plot. Line
width represents the thickness of streamlines.
• Example 1: Plotting a single vector using quiver() method in matplotlib module.
# Import libraries
import numpy as np
import matplotlib.pyplot as plt
# Vector origin location
X = [0]
Y = [0]
# Directional vectors
U = [2]
V = [1]
# Creating plot
plt.quiver(X, Y, U, V, color='b', units='xy', scale=1)
plt.title('Single Vector')
# x-lim and y-lim
plt.xlim(-2, 5)
plt.ylim(-2, 2.5)
# Show plot with grid
plt.grid()
plt.show()
• Example 2: Generating multiple vectors using quiver() method.
• # Import required modules
• import numpy as np
• import matplotlib.pyplot as plt
• # Meshgrid
• x, y = np.meshgrid(np.linspace(-5, 5, 10),
• np.linspace(-5, 5, 10))
• # Directional vectors
• u = -y/np.sqrt(x**2 + y**2)
• v = x/(x**2 + y**2)
• # Plotting Vector Field with QUIVER
• plt.quiver(x, y, u, v, color='g')
• plt.title('Vector Field')
• # Setting x, y boundary limits
• plt.xlim(-7, 7)
• plt.ylim(-7, 7)
• # Show plot with grid
• plt.grid()
• plt.show()
• Example 3: Plotting multiple vectors using streamplot() method
in matplotlib module.
• # Import required modules
• import numpy as np
• import matplotlib.pyplot as plt
• # 1D arrays
• x = np.arange(-5,5,0.1)
• y = np.arange(-5,5,0.1)
• # Meshgrid
• X,Y = np.meshgrid(x,y)
• # Assign vector directions
• Ex = (X + 1)/((X+1)**2 + Y**2) - (X - 1)/((X-1)**2 + Y**2)
• Ey = Y/((X+1)**2 + Y**2) - Y/((X-1)**2 + Y**2)
• # Depict illustration
• plt.figure(figsize=(10, 10))
• plt.streamplot(X,Y,Ex,Ey, density=1.4, linewidth=None,
color='#A23BEC')
• plt.plot(-1,0,'-or')
• plt.plot(1,0,'-og')
• plt.title('Electromagnetic Field')
• # Show plot with grid
• plt.grid()
• plt.show()