The most of contents borrowed from the book 『Python Data Science Handbook: Essential Tools for Working with Data, Jake VanderPlas, O'REILLY, 2017』. I have just added somewhat object-oriented or matlab style codes.

Customizing ColorBar

In [4]:
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('classic')

%matplotlib inline
In [5]:
x = np.linspace(0, 10, 1000)
I = np.sin(x) * np.cos(x[:, np.newaxis])
In [6]:
# make noise in 1% of the image pixels
speckles = (np.random.random(I.shape) < 0.01)
I[speckles] = np.random.normal(0, 3, np.count_nonzero(speckles))
plt.figure(figsize=(10, 3.5))
plt.subplot(1, 2, 1)
plt.imshow(I, cmap='RdBu')
plt.colorbar()
plt.subplot(1, 2, 2)
plt.imshow(I, cmap='RdBu')
plt.colorbar(extend='both')
plt.clim(-1, 1);
In [10]:
# make noise in 1% of the image pixels
speckles = (np.random.random(I.shape) < 0.01)
I[speckles] = np.random.normal(0, 3, np.count_nonzero(speckles))

fig = plt.figure(figsize=(10, 3.5))
ax1 = fig.add_subplot(1,2,1)
im1 = ax1.imshow(I, cmap='RdBu')
fig.colorbar(im1, ax=ax1)


ax2 = fig.add_subplot(1,2,2)
im2 = ax2.imshow(I, cmap='RdBu')
im2.set_clim(-1, 1)
fig.colorbar(im2, ax=ax2)
Out[10]:
<matplotlib.colorbar.Colorbar at 0x251cd27f348>
In [11]:
print(type(im2))
<class 'matplotlib.image.AxesImage'>

Example : Handwritten Digits

In [15]:
from sklearn.datasets import load_digits
digits = load_digits(n_class=6)

fig, ax = plt.subplots(8, 8, figsize=(6,6))
for i, axi in enumerate(ax.flat):
    axi.imshow(digits.images[i], cmap='binary')
    axi.set(xticks=[], yticks=[])
In [16]:
from sklearn.manifold import Isomap
iso = Isomap(n_components=2)
projection = iso.fit_transform(digits.data)
In [17]:
plt.scatter(projection[:,0], projection[:,1], lw=0.1,\
           c=digits.target, cmap=plt.cm.get_cmap('cubehelix', 6))
plt.colorbar(ticks=range(6), label='digit value')
plt.clim(-0.5, 5.5)
In [18]:
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

scatter = ax1.scatter(projection[:,0], projection[:,1], lw=0.1,\
           c=digits.target, cmap=plt.cm.get_cmap('cubehelix', 6))
fig.colorbar(scatter, ax= ax1, ticks=range(6), label='digit value')
scatter.set_clim(-0.5, 5.5)
In [ ]: