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()

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)

Here, we draw several ellipses and then call clabel() to display the selected levels. We used the NumPy meshgrid() function to get the coordinate matrices, X and Y, from the two coordinate vectors, x and y.

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()

This example creates a full spectrum of colors starting from deep blue of the image center, slightly turning into green, yellow, and red near the image corners.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。