4⃣️. 二维图设计
Contour plots and image plotting
Contour lines (also known as level lines or isolines) for a function of two variables are curves where the function has constant values. f(x, y) = L.
contour(matrix, N)
There is also a similar function that draws a filled contours plot, contourf() function. contourf() fills the spaces between the contours lines with the same color progression used in the contour() plot:
fig = plt.figure()
matr = np.random.rand(21, 31)
ax1 = fig.add_subplot(121)
ax1 = plt.contour(matr)
ax2 = fig.add_subplot(122)
ax2 = plt.contourf(matr)
plt.colorbar()
![](https://img.haomeiwen.com/i3685911/7c9c490eee485c75.png)
Labeling the level lines is important in order to provide information about what levels were chosen for display; clabel() does this by taking as input a contour instance, as returned by a previous contour() call:
x = np.arange(-2,2,0.01)
y = np.arange(-2,2,0.01)
X, Y = np.meshgrid(x, y)
ellipses = X*X/9 + Y*Y/4 - 1
cs = plt.contour(ellipses)
plt.clabel(cs)
![](https://img.haomeiwen.com/i3685911/f09dbcd68d2b9eec.png)
Imaging plotting
imread() reads an image from a file and converts it into a NumPy array;
imshow() takes an array as input and displays it on the screen:
f = plt.imread('/path/to/image/file.ext')
plt.imshow(f)
Matplotlib can only read PNG files natively, but if the Python Imaging Library (usually known as PIL) is installed, then this library will be used to read the image and return an array (if possible).
imshow() can plot any 2D sets of data and not just the ones read from image files. For example, let's take the ellipses code we used for contour plot and see what imshow() draws:
x = np.arange(-2,2,0.01)
y = np.arange(-2,2,0.01)
X, Y = np.meshgrid(x, y)
ellipses = X*X/9 + Y*Y/4 - 1
cs = plt.imshow(ellipses)
plt.colorbar()
![](https://img.haomeiwen.com/i3685911/91d973e3c8a4f1ae.png)