PolarSPARC

Useful Matplotlib Code Snippets


Bhaskar S 10/02/2021


Overview

Matplotlib is a popular data visualization library in Python. For an introductory material, please refer to the following 3-part series:

In this article, we will demonstrate and share some useful Matplotlib code snippets.

Useful Code Snippets

We need to import few Python modules, enable inline plots, and initialize some data variables for the code snippets to work. The following code snippet lists all these pre-requisites:


Listing.1
import math
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

%matplotlib inline

np.random.seed(100)

mu = 0
sd = math.sqrt(1)
N = 1000
a = np.array([3, 1])
b = np.array([1, 3])
xmin, xmax = -6, 6
ymin, ymax = -6, 6
x1 = np.random.randint(low=1, high=11, size=10)
y1 = np.random.randint(low=10, high=91, size=10)
x2 = np.random.randint(low=1, high=11, size=10)
y2 = np.random.randint(low=10, high=91, size=10)
x3 = np.linspace(mu - 3*sd, mu + 3*sd, N)
y3 = norm.pdf(x3, mu, sd)
f_x3 = np.linspace(-1.00, -3.00, 10)
f_y3 = norm.pdf(f_x3, mu, sd)

Plot Size

The following code snippet allows one to change the size of the plot:


Listing.2
plt.figure(figsize=(5,5))
plt.scatter(x1, y1)
plt.scatter(x2, y2)
plt.show()

plt.figure(figsize=(W,H)) - sets the size of the plot, where W is the width and H is the height, in inches.

Executing the above code snippet results in the following plot:

Plot Size
Figure.1

Plot Style

The following code snippet allows one to change the style of the plot:


Listing.3
plt.figure(figsize=(5,5))
plt.style.use('seaborn')
plt.scatter(x1, y1)
plt.scatter(x2, y2)
plt.show()

plt.style.use(S) - sets the style of the plot, where S is a style name, such as 'seaborn', 'ggplot', 'default', etc.

Executing the above code snippet results in the following plot:

Plot Style
Figure.2

X-axis and Y-axis Limits

The following code snippet allows one to set the X-axis and Y-axis limits of the plot:


Listing.4
plt.figure(figsize=(5,5))
plt.style.use('default')
plt.xlim(xmin, xmax)
plt.ylim(ymin, ymax)
plt.show()

plt.xlim(L, R) - sets the x-axis limits, where L is the left limit and R is the right limit.

plt.ylim(B, T) - sets the y-axis limits, where B is the bottom limit and T is the top limit.

Executing the above code snippet results in the following plot:

Plot Style
Figure.3

X-axis and Y-axis Lines

The following code snippet allows one to display the X-axis and Y-axis lines on the plot:


Listing.5
plt.figure(figsize=(5,5))
plt.style.use('seaborn')
plt.xlim(xmin, xmax)
plt.ylim(ymin, ymax)
plt.axis('square')
plt.axhline(y=0, linestyle='--', color='firebrick')
plt.axvline(x=0, linestyle='--', color='firebrick')
plt.show()

plt.axhline(y=N, linestyle=S, color=C) - allows one to add a horizontal line, where N is the y-coordinate of the line, S is the style of the line, and C is the color of the line.

plt.axvline(x=N, linestyle=S, color=C) - allows one to add a vertical line, where N is the x-coordinate of the line, S is the style of the line, and C is the color of the line.

Executing the above code snippet results in the following plot:

Axes Lines
Figure.4

X-axis and Y-axis Tick Marks

The following code snippet allows one to display the specified x-axis and y-axis tick marks on the default plot:


Listing.6
plt.figure(figsize=(5,5))
plt.style.use('default')
plt.xlim(xmin, xmax)
plt.ylim(ymin, ymax)
plt.axis('square')
plt.xticks(np.arange(xmin, xmax+1, 1.0))
plt.yticks(np.arange(ymin, ymax+1, 1.0))
plt.axhline(y=0, linestyle='--', color='firebrick')
plt.axvline(x=0, linestyle='--', color='firebrick')
plt.show()

plt.xticks(L) - allows one to the x-axis ticks, where L is the list of all the tick locations.

plt.yticks(L) - allows one to the y-axis ticks, where L is the list of all the tick locations.

Executing the above code snippet results in the following plot:

Axes Ticks
Figure.5

X-axis and Y-axis Tick Mark Color

The following code snippet allows one to display the specified x-axis and y-axis tick marks in different colors on the default plot:


Listing.7
plt.figure(figsize=(5,5))
plt.style.use('default')
plt.xlim(xmin, xmax)
plt.ylim(ymin, ymax)
plt.axis('square')
plt.xticks(np.arange(xmin, xmax+1, 1.0))
plt.yticks(np.arange(ymin, ymax+1, 1.0))
plt.tick_params(axis='x', colors='blue')
plt.tick_params(axis='y', colors='crimson')
plt.axhline(y=0, linestyle='--', color='skyblue')
plt.axvline(x=0, linestyle='--', color='skyblue')
plt.show()

plt.tick_params(axis=A, colors=C) - allows one to the color of either the x-axis and y-axis tick marks, where A is the axis - 'x' for x-axis and 'y' for y-axis, and C is the specified color.

Executing the above code snippet results in the following plot:

Axes Tick Color
Figure.6

Display Grid in the Default Plot

The following code snippet allows one to display the grid line in any color on the default plot:


Listing.8
plt.figure(figsize=(5,5))
plt.style.use('default')
plt.xlim(xmin, xmax)
plt.ylim(ymin, ymax)
plt.axis('square')
plt.xticks(np.arange(xmin, xmax+1, 1.0))
plt.yticks(np.arange(ymin, ymax+1, 1.0))
plt.tick_params(axis='x', colors='green')
plt.tick_params(axis='y', colors='crimson')
plt.axhline(y=0, linestyle='--', color='mediumpurple')
plt.axvline(x=0, linestyle='--', color='mediumpurple')
plt.grid(color='lavender')
plt.show()

plt.grid(color=C) - allows one to display the grid lines using the specified color C.

Executing the above code snippet results in the following plot:

Grid Color
Figure.7

Plot a Line with Arrow Head

The following code snippet allows one to plot a line between two points with an arrow at the head of the line:


Listing.9
plt.figure(figsize=(5,5))
plt.style.use('seaborn')
plt.xlim(xmin, xmax)
plt.ylim(ymin, ymax)
plt.axis('square')
plt.xticks(np.arange(xmin, xmax+1, 1.0))
plt.yticks(np.arange(ymin, ymax+1, 1.0))
plt.axhline(y=0, linestyle='--', color='grey')
plt.axvline(x=0, linestyle='--', color='grey')
plt.arrow(x=0, y=0, dx=a[0], dy=a[1], width=0.07, color='darkviolet')
plt.arrow(x=0, y=0, dx=b[0], dy=b[1], width=0.1, color='dodgerblue')
plt.show()

plt.arrow(x=X, y=Y, dx=DX, dy=DY, width=W, color=C) - allows one to line between two points with an arrow at the head of the line, where (X, Y) is the starting point, (X+DX, Y+DY) is the ending point, W is the width of the line and C is the color of the line.

Executing the above code snippet results in the following plot:

Arrow at Head
Figure.8

Annotate a Point

The following code snippet allows one to annotate any point on the plot with text:


Listing.10
plt.figure(figsize=(5,5))
plt.style.use('ggplot')
plt.xlim(xmin, xmax)
plt.ylim(ymin, ymax)
plt.axis('square')
plt.xticks(np.arange(xmin, xmax+1, 1.0))
plt.yticks(np.arange(ymin, ymax+1, 1.0))
plt.axhline(y=0, linestyle='--', color='grey')
plt.axvline(x=0, linestyle='--', color='grey')
plt.arrow(x=0, y=0, dx=b[0], dy=b[1], width=0.1, color='dodgerblue')
txt = 'b=(%d, %d)' % (b[0], b[1])
plt.annotate(txt, xy=(b[0]+0.3, b[1]+0.3), color='crimson')
plt.show()

plt.annotate(T, xy=(X, Y), color=C) - allows one to annotate any point on the plot, where T is the text, (X, Y) is the coordinate point where the text must be placed, and C is the color of the text.

Executing the above code snippet results in the following plot:

Annotate a Point
Figure.9

Box Around a Text Annotatation

The following code snippet allows one to decorate a text annotation with a box around it:


Listing.11
plt.figure(figsize=(5,5))
plt.style.use('ggplot')
plt.xlim(xmin, xmax)
plt.ylim(ymin, ymax)
plt.axis('square')
plt.xticks(np.arange(xmin, xmax+1, 1.0))
plt.yticks(np.arange(ymin, ymax+1, 1.0))
plt.axhline(y=0, linestyle='--', color='grey')
plt.axvline(x=0, linestyle='--', color='grey')
plt.arrow(x=0, y=0, dx=b[0], dy=b[1], width=0.1, color='dodgerblue')
txt = 'b=(%d, %d)' % (b[0], b[1])
plt.annotate(txt, xy=(b[0]+0.3, b[1]+0.8), ha='center', weight='bold', color='crimson',
             bbox={'boxstyle': 'round', 'fc': 'none', 'ec': 'crimson'})
plt.show()

plt.annotate(T, xy=(X, Y), weight=W, color=C1, bbox={'boxstyle': S, 'fc': C2, 'ec': C3}) - allows one to decorate a text annotation with a box around it, where T is the text, (X, Y) is the coordinate point where the text must be placed, W is the font weight, C1 is the color of the text, S is the style of the box, C2 is the background color of the box, and C3 is the color of the box border.

Executing the above code snippet results in the following plot:

Boxed Annotatation
Figure.10

Annotate a Point with an Arrow

The following code snippet allows one to annotate any point on the plot with text and an arrow pointing towards the point:


Listing.12
plt.figure(figsize=(5,5))
plt.style.use('ggplot')
plt.xlim(xmin, xmax)
plt.ylim(ymin, ymax)
plt.axis('square')
plt.xticks(np.arange(xmin, xmax+1, 1.0))
plt.yticks(np.arange(ymin, ymax+1, 1.0))
plt.axhline(y=0, linestyle='--', color='grey')
plt.axvline(x=0, linestyle='--', color='grey')
plt.plot(b[0], b[1], 'ro', color='coral')
txt = 'b=(%d, %d)' % (b[0], b[1])
plt.annotate(txt, xy=(b[0], b[1]), xytext=(b[0]+1.2, b[1]+1.2), color='crimson',
             arrowprops={'arrowstyle': '->', 'lw': 1, 'ec': 'blue'}, ha='center')
plt.show()

plt.annotate(T, xy=(X, Y), color=C1, arrowprops={'arrowstyle': S, 'lw': W, 'ec': C2}, ha=A) - allows one to annotate any point on the plot with an arrow pointing towards the coordinate point, where T is the text, (X, Y) is the coordinate point where the text must be placed, C1 is the color of the text, A is the alignment of the text, S is the arrow style, W is the thickness of the arrow, and C2 is the color of the arrow.

Executing the above code snippet results in the following plot:

Annotate with Arrow
Figure.11

Normal Distribution Curve

The following code snippet allows one to plot a normal distribution curve (commonly referred to as the bell curve):


Listing.13
plt.figure(figsize=(5,5))
plt.style.use('default')
plt.plot(x3, y3, color='blue')
plt.show()

plt.plot(LX, LY, color=C) - allows one to plot a list of points, where LX is the list of the x values, LY is the list of the corresponding y values, and C is the color.

Executing the above code snippet results in the following plot:

Normal Curve
Figure.12

Fill a Region of a Curve

The following code snippet allows one to fill a region on a curve:


Listing.14
plt.style.use('default')
plt.figure(figsize=(5,5))
plt.plot(x3, y3, color='dodgerblue')
plt.axvline(x=-1.00, color='dimgrey', linestyle='dashed')
plt.fill_between(f_x3, f_y3, color='coral', alpha='0.4')
plt.annotate('z=-1.00', (-2.00, 0.35))
plt.show()

plt.fill_between(LX, LY, color=C, alpha=T) - allows one to plot a section of a curve, where LX is the list of the x values between the min and max of the region, LY is the list of the corresponding y values, C is the color, and T is the level of transparency.

Executing the above code snippet results in the following plot:

Fill a Region
Figure.13

References

Matplotlib Documentation

Introduction to Matplotlib - Part 1

Introduction to Matplotlib - Part 2

Introduction to Matplotlib - Part 3


© PolarSPARC