Tutorial on Python Library: matplotlib


Bikash Santra and Avisek Gupta

Indian Statistical Institute, Kolkata


1. Import library

In [1]:
import matplotlib
import numpy as np
print(matplotlib.__version__)
2.2.3
In [2]:
import matplotlib.pyplot as plt

2. A basic plot: A sinusoid

In [3]:
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.show()

3. Customizing the plot

In [4]:
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.figure(figsize=(11,6), dpi=200)
[line_handle] = plt.plot(x, y, c='g', linewidth=4, label='sine')
y2 = np.cos(x)
[line_handle2] = plt.plot(x, y2, c='#ffadcd', linewidth=2, label='cos')
plt.legend(handles=[line_handle, line_handle2], fontsize=30, loc='lower right', shadow=True)
plt.xlabel('x axis', fontsize=30)
plt.ylabel('y axis', fontsize=30)
plt.title('A plot', fontsize=30)
plt.xticks(fontsize=20)
plt.yticks([-1, -0.5, 0, 0.5, 1], [-1, -0.5, 0, 0.5, 1], fontsize=20)
plt.show()

4. Scatter Plots with customized legends

In [5]:
x1 = np.random.normal(loc=[0,0], scale=1, size=(100,2))
x2 = np.random.normal(loc=[10,0], scale=1, size=(100,2))
x3 = np.random.normal(loc=[5,5], scale=1, size=(100,2))

plt.figure(figsize=(9,6), dpi=150)

g1 = plt.scatter(
    x1[:,0], x1[:,1], marker='x', s=80, c='b',
    label='Gaussian #1'
)
g2 = plt.scatter(
    x2[:,0], x2[:,1], marker='o', s=80, c='w', edgecolor='r',
    label='Gaussian #2'
)
g3 = plt.scatter(
    x3[:,0], x3[:,1], marker='d', s=80, c='w', edgecolor='g',
    label='Gaussian #3'
)

plt.legend(
    handles=[g1, g2, g3], fontsize=30, shadow=True, 
    bbox_to_anchor=(1.03, 1), borderaxespad=0
)

plt.xlabel('Feature 1', fontsize=30)
plt.ylabel('Feature 2', fontsize=30)
plt.title('Mixture of 3 Gaussians', fontsize=30)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.show()

#plt.savefig('scatter_demo.png', dpi=300, bbox_inches='tight', pad_inches=0.05)

5. Supported image file types to save to

In [6]:
plt.gcf().canvas.get_supported_filetypes()
Out[6]:
{'ps': 'Postscript',
 'eps': 'Encapsulated Postscript',
 'pdf': 'Portable Document Format',
 'pgf': 'PGF code for LaTeX',
 'png': 'Portable Network Graphics',
 'raw': 'Raw RGBA bitmap',
 'rgba': 'Raw RGBA bitmap',
 'svg': 'Scalable Vector Graphics',
 'svgz': 'Scalable Vector Graphics'}
<Figure size 432x288 with 0 Axes>

6. Plotting in 3D

In [7]:
%matplotlib notebook

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

n = 100
xs = np.random.rand(n)
ys = np.random.rand(n)
zs = np.random.rand(n)
mask = zs < 0.5
c = ['r', 'b']
m = ['o', '^']
ax.scatter(xs[mask==0], ys[mask==0], zs[mask==0], c=c[0], marker=m[0])
ax.scatter(xs[mask==1], ys[mask==1], zs[mask==1], c=c[1], marker=m[1])


ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()