Week 7 notebook

Plot legend

In [100]:
import numpy as np
import matplotlib.pyplot as plt
In [98]:
x = np.linspace(-1, 1, 500)
plt.plot(x, x**2, label='$f(x) = x^2$')
plt.plot(x, x**4, label='$f(x) = x^4$ ')
plt.plot(x, x**6, label='$f(x) = x^6$')
plt.legend(loc='upper right', fontsize=12)
plt.show()

Specifying colors in matplotlib

Color maps

A color map is a collection of colors, each color corresponding to an index between 0 and 1.

In [101]:
import matplotlib.cm as cm
In [103]:
x = np.linspace(0, 1, 40)

plt.figure(figsize=(14, 1))
for t in x:
    plt.plot(t, 0, 'o', ms=12, color=cm.jet(t))
plt.title('jet')
plt.show()
In [8]:
plt.figure(figsize=(14, 5))

plt.subplots_adjust(hspace=0.5)


plt.subplot(3, 1, 1)
for t in x:
    plt.plot(t, 0, 'o', ms=12, color=cm.inferno(t))
    plt.title('inferno')
    
plt.subplot(3, 1, 2)
for t in x:
    plt.plot(t, 0, 'o', ms=12, color=cm.viridis(t))
    plt.title('viridis')

plt.subplot(3, 1, 3)
for t in x:
    plt.plot(t, 0, 'o', ms=12, color=cm.autumn(t))
    plt.title('autumn')
plt.show()
In [106]:
dir(cm)
Out[106]:
['Accent',
 'Accent_r',
 'Blues',
 'Blues_r',
 'BrBG',
 'BrBG_r',
 'BuGn',
 'BuGn_r',
 'BuPu',
 'BuPu_r',
 'CMRmap',
 'CMRmap_r',
 'Dark2',
 'Dark2_r',
 'GnBu',
 'GnBu_r',
 'Greens',
 'Greens_r',
 'Greys',
 'Greys_r',
 'LUTSIZE',
 'OrRd',
 'OrRd_r',
 'Oranges',
 'Oranges_r',
 'PRGn',
 'PRGn_r',
 'Paired',
 'Paired_r',
 'Pastel1',
 'Pastel1_r',
 'Pastel2',
 'Pastel2_r',
 'PiYG',
 'PiYG_r',
 'PuBu',
 'PuBuGn',
 'PuBuGn_r',
 'PuBu_r',
 'PuOr',
 'PuOr_r',
 'PuRd',
 'PuRd_r',
 'Purples',
 'Purples_r',
 'RdBu',
 'RdBu_r',
 'RdGy',
 'RdGy_r',
 'RdPu',
 'RdPu_r',
 'RdYlBu',
 'RdYlBu_r',
 'RdYlGn',
 'RdYlGn_r',
 'Reds',
 'Reds_r',
 'ScalarMappable',
 'Set1',
 'Set1_r',
 'Set2',
 'Set2_r',
 'Set3',
 'Set3_r',
 'Spectral',
 'Spectral_r',
 'Vega10',
 'Vega10_r',
 'Vega20',
 'Vega20_r',
 'Vega20b',
 'Vega20b_r',
 'Vega20c',
 'Vega20c_r',
 'Wistia',
 'Wistia_r',
 'YlGn',
 'YlGnBu',
 'YlGnBu_r',
 'YlGn_r',
 'YlOrBr',
 'YlOrBr_r',
 'YlOrRd',
 'YlOrRd_r',
 '__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 '_deprecation_datad',
 '_generate_cmap',
 '_reverse_cmap_spec',
 '_reverser',
 'absolute_import',
 'afmhot',
 'afmhot_r',
 'autumn',
 'autumn_r',
 'binary',
 'binary_r',
 'bone',
 'bone_r',
 'brg',
 'brg_r',
 'bwr',
 'bwr_r',
 'cbook',
 'cmap_d',
 'cmapname',
 'cmaps_listed',
 'colors',
 'cool',
 'cool_r',
 'coolwarm',
 'coolwarm_r',
 'copper',
 'copper_r',
 'cubehelix',
 'cubehelix_r',
 'datad',
 'division',
 'flag',
 'flag_r',
 'get_cmap',
 'gist_earth',
 'gist_earth_r',
 'gist_gray',
 'gist_gray_r',
 'gist_heat',
 'gist_heat_r',
 'gist_ncar',
 'gist_ncar_r',
 'gist_rainbow',
 'gist_rainbow_r',
 'gist_stern',
 'gist_stern_r',
 'gist_yarg',
 'gist_yarg_r',
 'gnuplot',
 'gnuplot2',
 'gnuplot2_r',
 'gnuplot_r',
 'gray',
 'gray_r',
 'hot',
 'hot_r',
 'hsv',
 'hsv_r',
 'inferno',
 'inferno_r',
 'jet',
 'jet_r',
 'ma',
 'magma',
 'magma_r',
 'mpl',
 'nipy_spectral',
 'nipy_spectral_r',
 'np',
 'ocean',
 'ocean_r',
 'os',
 'pink',
 'pink_r',
 'plasma',
 'plasma_r',
 'print_function',
 'prism',
 'prism_r',
 'rainbow',
 'rainbow_r',
 'register_cmap',
 'revcmap',
 'seismic',
 'seismic_r',
 'six',
 'spec',
 'spec_reversed',
 'spectral',
 'spectral_r',
 'spring',
 'spring_r',
 'summer',
 'summer_r',
 'tab10',
 'tab10_r',
 'tab20',
 'tab20_r',
 'tab20b',
 'tab20b_r',
 'tab20c',
 'tab20c_r',
 'terrain',
 'terrain_r',
 'unicode_literals',
 'viridis',
 'viridis_r',
 'winter',
 'winter_r']
In [14]:
x = np.linspace(-np.pi, np.pi)

ax = plt.subplot(1, 1, 1)
ax.set_facecolor(cm.inferno(0.9))
plt.plot(x, np.sin(x), '-', color=cm.jet(0.9))
plt.plot(x, np.cos(x), '--', color=cm.winter(0.2))

plt.show()

RGB colors

RGB color model uses basic colors: red, green, blue. All other colors are obtained as a mixture of these basic colors. In the RGB model each color is specified by three numbers describing intensities of red, green, blue. In matplotlib these values are numbers between 0 (full off) and 1 (full on).

In [109]:
plt.plot(0, 0, 'o', ms=100, color=(0,1,1))
plt.show()
In [30]:
ax = plt.subplot(1, 1, 1)
ax.set_facecolor((0,0,0))

h = 3**0.5

plt.axis('equal')
plt.ylim(-0.5, 2.2)
plt.plot(-1, 0, 'o', ms=40, color=(1, 0,0))
plt.plot(1, 0, 'o', ms=40, color=(0, 0,1))
plt.plot(0, h, 'o', ms=40, color=(0, 1,0))
plt.plot(-1/2, h/2, 'o', ms=40, color =(1, 1, 0))
plt.plot(1/2, h/2, 'o', ms=40, color =(0, 1, 1))
plt.plot(0, 0, 'o', ms=40, color =(1, 0, 1))
plt.plot(0, h/3, 'o', ms=40, color =(1, 1, 1))

plt.show()

Multidimensional numpy arrays

In [39]:
a = np.arange(20)
print(a)
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]

The np.reshape() function can be used to change the shape of a numpy array:

In [40]:
b= a.reshape(4, 5)
print(b)
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]]
In [42]:
c = a.reshape(10,2)
print(c)
[[ 0  1]
 [ 2  3]
 [ 4  5]
 [ 6  7]
 [ 8  9]
 [10 11]
 [12 13]
 [14 15]
 [16 17]
 [18 19]]

b.shape gives dimensions of a numpy array b:

In [43]:
b.shape
Out[43]:
(4, 5)
In [44]:
c.shape
Out[44]:
(10, 2)
In [45]:
a.shape
Out[45]:
(20,)
In [55]:
x = np.arange(20)
In [62]:
print(x)
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]
In [57]:
y = x.reshape(20,1)
In [58]:
print(y)
[[ 0]
 [ 1]
 [ 2]
 [ 3]
 [ 4]
 [ 5]
 [ 6]
 [ 7]
 [ 8]
 [ 9]
 [10]
 [11]
 [12]
 [13]
 [14]
 [15]
 [16]
 [17]
 [18]
 [19]]

The ravel() function unravels a multidimensional array into a one dimensional array.

In [59]:
z = y.ravel()
In [61]:
print(z)
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]
In [63]:
u = x.reshape(1, 20)
print(u)
[[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]]

Using indexing to access array elements:

In [66]:
a = np.arange(20)
print(a)
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]
In [68]:
b = a.reshape(4, 5)
print(b)
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]]
In [69]:
b[0,0]
Out[69]:
0
In [70]:
b[3,4]
Out[70]:
19
In [71]:
b[2, 3] = -1
print(b)
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 -1 14]
 [15 16 17 18 19]]

Note: Reshaping produces a view of the original array, by changing the reshaped array we change also the original:

In [72]:
print(a)
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 -1 14 15 16 17 18 19]

The functions np.zeros(), np.ones(), np.empty() can be used to create arrays with more than one dimension:

In [74]:
d = np.zeros((3, 7), dtype='int')
print(d)
[[0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0]]

Math operations on multidimensional numpy arrays

In [75]:
a = np.ones((3,3))
print(a)
[[ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]]
In [76]:
b = 2*a
print(b)
[[ 2.  2.  2.]
 [ 2.  2.  2.]
 [ 2.  2.  2.]]
In [77]:
c = np.arange(9).reshape(3,3)
print(c)
[[0 1 2]
 [3 4 5]
 [6 7 8]]
In [78]:
d = b+c
print(d)
[[  2.   3.   4.]
 [  5.   6.   7.]
 [  8.   9.  10.]]
In [79]:
e = b*c
print(e)
[[  0.   2.   4.]
 [  6.   8.  10.]
 [ 12.  14.  16.]]

Matrix multiplication can be done using the dot() function:

In [80]:
f = d.dot(e)
print(f)
[[  66.   84.  102.]
 [ 120.  156.  192.]
 [ 174.  228.  282.]]

Numpy functions work on multidimensional array:

In [82]:
print(np.sin(f))
[[-0.02655115  0.73319032  0.99482679]
 [ 0.58061118 -0.88178462 -0.35493836]
 [-0.93646197  0.97262306 -0.67674976]]

Slicing multidimensional arrays

In [110]:
a = np.arange(35).reshape(5,7)
In [111]:
print(a)
[[ 0  1  2  3  4  5  6]
 [ 7  8  9 10 11 12 13]
 [14 15 16 17 18 19 20]
 [21 22 23 24 25 26 27]
 [28 29 30 31 32 33 34]]
In [112]:
print(a[0, :])
[0 1 2 3 4 5 6]
In [113]:
print(a[:, 0])
[ 0  7 14 21 28]
In [114]:
print(a[-1, :])
[28 29 30 31 32 33 34]
In [115]:
print(a[2:4, :])
[[14 15 16 17 18 19 20]
 [21 22 23 24 25 26 27]]
In [116]:
print(a[2:4, 3:])
[[17 18 19 20]
 [24 25 26 27]]
In [117]:
a[2:4, 3:] = 0
In [118]:
print(a)
[[ 0  1  2  3  4  5  6]
 [ 7  8  9 10 11 12 13]
 [14 15 16  0  0  0  0]
 [21 22 23  0  0  0  0]
 [28 29 30 31 32 33 34]]
In [119]:
x = np.arange(8).reshape(2,4)
a[2:4, 3:] = x
In [120]:
print(a)
[[ 0  1  2  3  4  5  6]
 [ 7  8  9 10 11 12 13]
 [14 15 16  0  1  2  3]
 [21 22 23  4  5  6  7]
 [28 29 30 31 32 33 34]]

imshow with color maps

np.random.rand() function produces a numpy array of random floats in the range [0, 1).

In [6]:
import numpy as np
a= np.random.rand(10)
print(a)
[ 0.68091309  0.79200389  0.13828149  0.9608676   0.86781074  0.82544014
  0.88140724  0.39580266  0.82894287  0.72978043]
In [7]:
a = np.random.rand(3,3)
print(a)
[[ 0.06540218  0.71288099  0.20521661]
 [ 0.66855737  0.87425255  0.6485906 ]
 [ 0.40918757  0.30767236  0.78599864]]

The matplotlib function imshow() creates an image from a 2-dimensional numpy array. The image will have one square for each element of the array. The color of each square is determined by the value of the corresponding array element and the color map used by imshow().

In [8]:
import matplotlib.pyplot as plt
plt.imshow(a, cmap='jet', interpolation='nearest')
plt.show()
In [9]:
import matplotlib.pyplot as plt
plt.imshow(a, cmap='viridis', interpolation='nearest')
plt.show()
In [10]:
import matplotlib.pyplot as plt
plt.imshow(a, cmap='gray', interpolation='nearest')
plt.show()
In [11]:
import matplotlib.pyplot as plt
plt.imshow(a, cmap='jet', interpolation='bilinear')
plt.show()
In [12]:
import matplotlib.pyplot as plt
plt.imshow(a, cmap='jet', interpolation='bicubic')
plt.show()
In [13]:
plt.imshow(a)
plt.show()

The imsave() function is similar to imshow() but it saves the image to a file:

In [14]:
a = np.random.rand(200, 200)
plt.imsave('imsave_test.png', a, cmap='jet')
In [17]:
a = np.arange(100).reshape(10,10)
plt.imshow(a)
plt.show()
In [18]:
print(a)
[[ 0  1  2  3  4  5  6  7  8  9]
 [10 11 12 13 14 15 16 17 18 19]
 [20 21 22 23 24 25 26 27 28 29]
 [30 31 32 33 34 35 36 37 38 39]
 [40 41 42 43 44 45 46 47 48 49]
 [50 51 52 53 54 55 56 57 58 59]
 [60 61 62 63 64 65 66 67 68 69]
 [70 71 72 73 74 75 76 77 78 79]
 [80 81 82 83 84 85 86 87 88 89]
 [90 91 92 93 94 95 96 97 98 99]]
In [20]:
a = np.random.rand(3,3)
print(a)
[[ 0.36374285  0.06782296  0.6125974 ]
 [ 0.46833032  0.58021441  0.86767435]
 [ 0.83057602  0.4939439   0.81557858]]
In [22]:
plt.imshow(a)
plt.show()
In [24]:
plt.imshow(a, vmin = 0, vmax=5)
plt.show()

imshow with RGB

The function imshow() can create images with colors specified by RGB coordinates. To do this we use a 3-dimensional numpy array a of dimensions m×n×3. Such array consists of three slices a[:,:, 0], a[:,:, 1], and a[:,:, 2] that give RGB coordinates of colors in the image.

In [25]:
a = np.random.rand(4,4,3)
print(a)
[[[ 0.86387262  0.27256743  0.42332121]
  [ 0.68723466  0.95718518  0.37178732]
  [ 0.02329174  0.3090571   0.05631313]
  [ 0.26783904  0.4628038   0.12895617]]

 [[ 0.23020603  0.3994337   0.37075155]
  [ 0.38250951  0.96434329  0.04747908]
  [ 0.98688317  0.28037966  0.27939332]
  [ 0.38759699  0.61253423  0.70408441]]

 [[ 0.41662635  0.24189516  0.41613582]
  [ 0.52958357  0.16953408  0.19804044]
  [ 0.41335231  0.47223215  0.95344127]
  [ 0.43851415  0.38979304  0.99547382]]

 [[ 0.89600481  0.37348981  0.33541994]
  [ 0.83650688  0.42933647  0.6876916 ]
  [ 0.64301705  0.86460713  0.77775213]
  [ 0.94239295  0.99629223  0.1957034 ]]]
In [26]:
a[2, 3, 0]
Out[26]:
0.4385141460025892
In [27]:
a[2,3,1]
Out[27]:
0.3897930354006468
In [29]:
plt.imshow(a)
plt.show()
In [30]:
a[0,0,0]
Out[30]:
0.86387261617721778
In [31]:
a[0,0,1]
Out[31]:
0.27256742808657863
In [32]:
a[0,0,2]
Out[32]:
0.42332121138259426
In [42]:
plt.figure(figsize=(15, 4))
plt.subplot(1,4,1)
plt.imshow(a)

plt.subplot(1,4,2)
r = np.copy(a)
r[:, :, 1] = 0
r[:, :, 2] = 0
plt.imshow(r)

plt.subplot(1,4,3)
g = np.copy(a)
g[:, :, 0] = 0
g[:, :, 2] = 0
plt.imshow(g)

plt.subplot(1,4,4)
b = np.copy(a)
b[:, :, 0] = 0
b[:, :, 1] = 0
plt.imshow(b)



plt.show()
In [43]:
b = np.zeros((20,20,3))
plt.imshow(b)
plt.show()
In [44]:
b[5:10, 10:15, 0] = 1
plt.imshow(b)
plt.show()
In [45]:
b[7:12, 7:12, 1] = 1
plt.imshow(b)
plt.show()
In [46]:
plt.imshow(b, interpolation='bilinear')
plt.show()
In [47]:
b = np.zeros((20,20,3))
plt.imshow(b)
plt.show()
In [49]:
og =  np.array([92, 100, 40])/255

b[:, 15, 0] = og[0]
b[:, 15, 1] = og[1]
b[:, 15, 2] = og[2]
plt.imshow(b)
plt.show()
In [50]:
og =  np.array([92, 100, 40])/255

b[:, 15, :] = og
plt.imshow(b)
plt.show()