# Visualization with Matplotlib -2 2D arrays, Images

2D arrays

Images

Matplotlib_2_2D
In [1]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import IPython.display as dp


### pixel intensity¶

• small is black
• large is white
In [2]:
u=np.linspace(-2,2,3)
v=np.linspace(-1,1,5)
X,Y=np.meshgrid(u,v)

In [3]:
X

Out[3]:
array([[-2.,  0.,  2.],
[-2.,  0.,  2.],
[-2.,  0.,  2.],
[-2.,  0.,  2.],
[-2.,  0.,  2.]])
In [4]:
Y

Out[4]:
array([[-1. , -1. , -1. ],
[-0.5, -0.5, -0.5],
[ 0. ,  0. ,  0. ],
[ 0.5,  0.5,  0.5],
[ 1. ,  1. ,  1. ]])
In [5]:
dp.Image('1.jpg',width=400,height=400)

Out[5]:
In [6]:
Z = X**2/25 + Y**2/4
Z

Out[6]:
array([[ 0.41  ,  0.25  ,  0.41  ],
[ 0.2225,  0.0625,  0.2225],
[ 0.16  ,  0.    ,  0.16  ],
[ 0.2225,  0.0625,  0.2225],
[ 0.41  ,  0.25  ,  0.41  ]])
In [7]:
plt.figure(figsize=(5,2))
plt.set_cmap('gray')
plt.pcolor(Z)
plt.xlabel('X')
plt.ylabel('Y')

Out[7]:
<matplotlib.text.Text at 0x7f15373a3f50>

### writing special characters in matplotlib¶

http://matplotlib.org/users/mathtext.html

In [8]:
a,b=np.meshgrid(np.linspace(-3,3),np.linspace(-2,2))
z=a**2/25 + b**2/4
plt.figure(figsize=(5,2))
plt.set_cmap('gray')
plt.pcolor(z)
plt.text(15,25,r'$f(x,y)=\frac{x^2}{25}+\frac{y^2}{25}$',color='w',fontsize=13)
plt.xlabel('X')
plt.ylabel('Y')

Out[8]:
<matplotlib.text.Text at 0x7f15348f13d0>
In [9]:
plt.figure(figsize=(5,2))
plt.pcolor(np.array([[1,2,3,2,1,0],[4,5,6,7,8,9]]))

Out[9]:
<matplotlib.collections.PolyCollection at 0x7f153450f2d0>
In [10]:
dp.Image('2.jpg',width=400,height=400)

Out[10]:

### Generating meshes¶

• In order to visualize two-dimensional arrays of data, it is necessary to understand how to generate and manipulate 2-D arrays.
• visualise using plt.imshow()
• colorbar
In [11]:
plt.figure(figsize=(5,3))

# Generate two 1-D arrays: u, v
u = np.linspace(-2, 2, 41)
v = np.linspace(-1, 1, 21)

# Generate 2-D arrays from u and v: X, Y
X,Y = np.meshgrid(u, v)

# Compute Z based on X and Y
Z = np.sin(3*np.sqrt(X**2 + Y**2))

# Display the resulting image with pcolor()
plt.pcolor(Z, cmap='Blues')
plt.colorbar()
plt.axis('tight')

# Save the figure to 'sine_mesh.png'
plt.savefig('sine_mesh.jpg')

plt.show()


### pcolor(x,y,z)¶

In [12]:
plt.figure(figsize=(5,3))
plt.pcolor(X,Y,Z,cmap='Reds')

Out[12]:
<matplotlib.collections.PolyCollection at 0x7f15342a6310>

## contour¶

In [13]:
plt.contour(Z,12,cmap='brg')

Out[13]:
<matplotlib.contour.QuadContourSet at 0x7f1534134b50>

## contourf¶

In [14]:
plt.contourf(Z,12,cmap='Blues')

Out[14]:
<matplotlib.contour.QuadContourSet at 0x7f15340dca10>

### Improve the spacing between the subplots with plt.tight_layout() and display the figure.¶

In [15]:
plt.set_cmap('winter')
# Generate a default contour map of the array Z
plt.subplot(2,2,1)
plt.contour(X, Y, Z)

# Generate a contour map with 20 contours
plt.subplot(2,2,2)
plt.contour(X, Y, Z, 20)

# Generate a default filled contour map of the array Z
plt.subplot(2,2,3)
plt.contourf(X, Y, Z)

# Generate a contour map with 20 contours
plt.subplot(2,2,4)
plt.contourf(X, Y, Z, 20)

# Improve the spacing between subplots
plt.tight_layout()

# Display the figure
plt.show()


## visualize 2-D histograms using plt.hist2d()¶

• You specify the coordinates of the points using plt.hist2d(x,y) assuming x and y are two vectors of the same length.
• You can specify the number of bins with the argument bins=(nx, ny) where nx is the number of bins to use in the horizontal direction and ny is the number of bins to use in the vertical direction.
• You can specify the rectangular region in which the samples are counted in constructing the 2D histogram. The optional parameter required is range=((xmin, xmax), (ymin, ymax))
• xmin and xmax are the respective lower and upper limits for the variables on the x-axis and
• ymin and ymax are the respective lower and upper limits for the variables on the y-axis. Notice that the optional range argument can use nested tuples or lists.
In [16]:
# Generate a 2-D histogram
plt.hist2d(np.random.randint(0,10,1000),
np.random.randint(0,30,1000),
bins=(20,20),
range=((0,13), (0, 35))
,cmap='Blues')

# Add a color bar to the histogram
plt.colorbar()

# Add labels, title, and display the plot
plt.xlabel('Horse power [hp]')
plt.ylabel('Miles per gallon [mpg]')
plt.title('hist2d() plot')
plt.show()


### generate random integars¶

In [17]:
np.random.randint(0,20,(5,3))

Out[17]:
array([[10, 12, 19],
[10,  9,  2],
[ 9,  1, 12],
[16,  3, 19],
[10,  0, 10]])

## Images¶

• The color image can be plotted as usual using plt.imshow()

• The resulting image loaded is a NumPy array of three dimensions. The array typically has dimensions M×N×3, where M×N is the dimensions of the image. The third dimensions are referred to as color channels (typically red, green, and blue).
In [18]:
# Load the image into an array: img

# Print the shape of the image
print(img.shape)

# Display the image
plt.imshow(img)

# Hide the axes
plt.axis('off')
plt.show()

(194, 259, 3)

In [19]:
# Load the image into an array: img

# Print the shape of the image
print(img.shape)

# Compute the sum of the red, green and blue channels: intensity
intensity = img.sum(axis=2)

# Print the shape of the intensity
print(intensity.shape)

# Display the intensity with a colormap of 'gray'
plt.imshow(intensity, cmap='gray')


(194, 259, 3)