PyPlot Zoo

A simple zoo of examples for PyPlot, since since the official documentation is frustrating at best.

In [1]:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D  # Used for 3D plots

def _map(*args, **aargs):
    return list(map(*args, **aargs))

%matplotlib inline

plt.rcParams['figure.figsize'] = (15, 15)

Colors

Color maps

In [2]:
cmaps = [('Perceptually Uniform Sequential', [
            'viridis', 'plasma', 'inferno', 'magma']),
         ('Sequential', [
            'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
            'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
            'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']),
         ('Sequential (2)', [
            'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink',
            'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia',
            'hot', 'afmhot', 'gist_heat', 'copper']),
         ('Diverging', [
            'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
            'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic']),
         ('Qualitative', [
            'Pastel1', 'Pastel2', 'Paired', 'Accent',
            'Dark2', 'Set1', 'Set2', 'Set3',
            'tab10', 'tab20', 'tab20b', 'tab20c']),
         ('Miscellaneous', [
            'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',
            'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg', 'hsv',
            'gist_rainbow', 'rainbow', 'jet', 'nipy_spectral', 'gist_ncar'])]

# rmaps = [c for e in cmaps for c in e[1] ]

from matplotlib import cm
rmaps = cm.datad.keys()
print(rmaps)
dict_keys(['Blues', 'BrBG', 'BuGn', 'BuPu', 'CMRmap', 'GnBu', 'Greens', 'Greys', 'OrRd', 'Oranges', 'PRGn', 'PiYG', 'PuBu', 'PuBuGn', 'PuOr', 'PuRd', 'Purples', 'RdBu', 'RdGy', 'RdPu', 'RdYlBu', 'RdYlGn', 'Reds', 'Spectral', 'Wistia', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd', 'afmhot', 'autumn', 'binary', 'bone', 'brg', 'bwr', 'cool', 'coolwarm', 'copper', 'cubehelix', 'flag', 'gist_earth', 'gist_gray', 'gist_heat', 'gist_ncar', 'gist_rainbow', 'gist_stern', 'gist_yarg', 'gnuplot', 'gnuplot2', 'gray', 'hot', 'hsv', 'jet', 'nipy_spectral', 'ocean', 'pink', 'prism', 'rainbow', 'seismic', 'spring', 'summer', 'terrain', 'winter', 'Accent', 'Dark2', 'Paired', 'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b', 'tab20c', 'Blues_r', 'BrBG_r', 'BuGn_r', 'BuPu_r', 'CMRmap_r', 'GnBu_r', 'Greens_r', 'Greys_r', 'OrRd_r', 'Oranges_r', 'PRGn_r', 'PiYG_r', 'PuBu_r', 'PuBuGn_r', 'PuOr_r', 'PuRd_r', 'Purples_r', 'RdBu_r', 'RdGy_r', 'RdPu_r', 'RdYlBu_r', 'RdYlGn_r', 'Reds_r', 'Spectral_r', 'Wistia_r', 'YlGn_r', 'YlGnBu_r', 'YlOrBr_r', 'YlOrRd_r', 'afmhot_r', 'autumn_r', 'binary_r', 'bone_r', 'brg_r', 'bwr_r', 'cool_r', 'coolwarm_r', 'copper_r', 'cubehelix_r', 'flag_r', 'gist_earth_r', 'gist_gray_r', 'gist_heat_r', 'gist_ncar_r', 'gist_rainbow_r', 'gist_stern_r', 'gist_yarg_r', 'gnuplot_r', 'gnuplot2_r', 'gray_r', 'hot_r', 'hsv_r', 'jet_r', 'nipy_spectral_r', 'ocean_r', 'pink_r', 'prism_r', 'rainbow_r', 'seismic_r', 'spring_r', 'summer_r', 'terrain_r', 'winter_r', 'Accent_r', 'Dark2_r', 'Paired_r', 'Pastel1_r', 'Pastel2_r', 'Set1_r', 'Set2_r', 'Set3_r', 'tab10_r', 'tab20_r', 'tab20b_r', 'tab20c_r'])
In [3]:
gradient = np.linspace(0, 1, 256)
gradient = np.tile(gradient, 5).reshape(5, 256)
In [4]:
_, axes = plt.subplots(nrows=len(rmaps), ncols=1, figsize = (80,35))

for axe,cmap in zip(axes, rmaps):
    try:
        axe.set_title(cmap, y=-.25)
        axe.set_axis_off()
        axe.imshow(gradient, cmap=cmap)
    except ValueError:
        pass

Colors

Scatter

In [5]:
x = np.linspace(0, 20, 50)
y = np.linspace(0, 20, 50)

X, Y = np.meshgrid(x, y)
Z = np.abs(X - Y)
In [6]:
plt.scatter(X, Y, c=Z, cmap='rainbow', linewidth=0)
plt.plot([0, 20], [0, 20])
plt.title("Absolute distance between X and Y")
plt.xlim([0, 20])
plt.xlabel("X")
plt.ylim([0, 20])
plt.ylabel("Y")
c = plt.colorbar()
c.set_label("Z = |X - Y|")

Plot

In [7]:
p = np.linspace(0, 1, 100)
h = - p * np.log2(p) - (1-p) * np.log2(1-p)
h[0] = 0
h[-1] = 0
<ipython-input-7-27b3defca4f0>:2: RuntimeWarning: divide by zero encountered in log2
  h = - p * np.log2(p) - (1-p) * np.log2(1-p)
<ipython-input-7-27b3defca4f0>:2: RuntimeWarning: invalid value encountered in multiply
  h = - p * np.log2(p) - (1-p) * np.log2(1-p)
In [8]:
plt.plot(p, h)
plt.plot([.5,.5], [0,1], linewidth=1, color='green')
plt.title("Entropy H(p)")
plt.xlim([0, 1])
xs = np.linspace(0, 1, 11)
plt.xticks(xs, _map(str, xs))
plt.xlabel("p")
plt.ylim([0, 1])
plt.ylabel("H(p)")
Out[8]:
Text(0, 0.5, 'H(p)')

Matrices

In [9]:
x = np.linspace(0, 17, 10)
y = np.linspace(0, 20, 20)

X, Y = np.meshgrid(x, y)
Z = X * Y
In [10]:
plt.imshow(Z, interpolation='None', cmap='jet')
plt.title("X * Y")
plt.xticks(range(len(x)), ["{:.2f}".format(e) for e in x], rotation=90)
plt.xlabel("X")
plt.yticks(range(len(y)), ["{:.2f}".format(e) for e in y])
plt.ylabel("Y")

c = plt.colorbar()
c.set_label("Z = X * Y")

Histogram

In [11]:
import random
random.seed(0)
v = [sum((random.choice([-1,1]) for _ in range(100))) for _ in range(1000)]
In [12]:
_, _, _ = plt.hist(v, bins=100, range=(-100,100))
plt.xscale('linear')
_ = plt.xticks(range(-100,101, 10))

Multiple histograms

In [13]:
random.seed(0)
a = [sum((random.choice([-1,1]) for _ in range(100))) for _ in range(1000)]
b = [random.randint(-100,100) for _ in range(1000)]
In [14]:
bins = np.linspace(-100, 100, 100)
plt.hist(a, bins, alpha=0.5, label='a')
plt.hist(b, bins, alpha=0.5, label='b')
plt.legend(loc='upper right')
Out[14]:
<matplotlib.legend.Legend at 0x7f00dc8b6e20>

3d functions

f(x, y) = z

Trisurf

In [15]:
x = np.linspace(-5, 5, 20)
y = np.linspace(-5, 5, 50)

X, Y = np.meshgrid(x, y)
X, Y = X.ravel(), Y.ravel()
Z = [a*b for a,b in zip(X, Y)]
In [16]:
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_title("f(x, y) = sin(x*y)")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.view_init(10, 45)
ax.plot_trisurf(X, Y, Z, linewidth=0.2, antialiased=True, color="red")
Out[16]:
<mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x7f00dc74b0a0>

Wireframe

In [17]:
p = np.linspace(0.0000, 1, 100)
q = np.linspace(0.0000, 1, 100)

P, Q = np.meshgrid(p, q)
H = -P*np.log(Q) - (1-P)*np.log(1-Q)
<ipython-input-17-49895059b58f>:5: RuntimeWarning: divide by zero encountered in log
  H = -P*np.log(Q) - (1-P)*np.log(1-Q)
<ipython-input-17-49895059b58f>:5: RuntimeWarning: invalid value encountered in multiply
  H = -P*np.log(Q) - (1-P)*np.log(1-Q)
In [18]:
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_title("Cross entropy H(P,Q)")
ax.set_xlabel("P")
ax.set_ylabel("Q")
ax.view_init(10, 45)
ax.plot_wireframe(P, Q, H, color='blue', antialiased=True)
Out[18]:
<mpl_toolkits.mplot3d.art3d.Line3DCollection at 0x7f00dc438d00>
/usr/lib/python3.8/site-packages/mpl_toolkits/mplot3d/proj3d.py:152: RuntimeWarning: invalid value encountered in true_divide
  txs, tys, tzs = vecw[0]/w, vecw[1]/w, vecw[2]/w

Surface

In [19]:
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)

X, Y = np.meshgrid(x, y)
Z = np.cos(np.sqrt(X**2 + Y**2))
In [20]:
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_title("f(x, y) = cos(sqrt(x^2 + y^2))")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.view_init(30, 60)
ax.plot_surface(X, Y, Z, cmap='jet', antialiased=True)
Out[20]:
<mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x7f00dc5d7b20>

3D scatterplots

In [21]:
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)

X, Y = np.meshgrid(x, y)
# X, Y = X.flatten(), Y.flatten()
Z = np.cos(np.sqrt(X**2 + Y**2))
In [22]:
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_title("f(x, y) = cos(sqrt(x^2 + y^2))")
ax.set_xlabel("x")
ax.set_ylabel("y")
# ax.view_init(45, 45)
ax.scatter(X, Y, Z, c='gray', s=10, marker='.')
Out[22]:
<mpl_toolkits.mplot3d.art3d.Path3DCollection at 0x7f00db177100>

Contours

In [23]:
a = np.linspace(-10,10, 100)
x, y = np.meshgrid(a, a)
r = np.sqrt(x**2 + y**2)
c = r <= 2
In [24]:
plt.title("Example of a contour")
plt.imshow(r, interpolation='none', cmap='gray')
plt.contour(c, interpolation='none', cmap='rainbow')
<ipython-input-24-92f691ebba86>:3: UserWarning: The following kwargs were not used by contour: 'interpolation'
  plt.contour(c, interpolation='none', cmap='rainbow')
Out[24]:
<matplotlib.contour.QuadContourSet at 0x7f00dc35fbb0>

Subplots

In [25]:
img1 = np.arange(10000).reshape(100,100)

a = np.linspace(-10,10, 100)
x, y = np.meshgrid(a, a)
img2 = np.sqrt(x**2 + y**2)
In [26]:
figs = [(img1, "Nice range"),
        (img2, "A thing")]

_, axes = plt.subplots(nrows=1, ncols=len(figs))

for axe, fig in zip(axes, figs):
    axe.set_title(fig[1])
    axe.imshow(fig[0])
In [ ]: