Python数据分析三剑客:Pandas、Numpy、Matplotlibmatplotlibmatplotlib

4⃣️. 二维图设计

2018-10-26  本文已影响6人  Joeylee1990s

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.
上一篇 下一篇

猜你喜欢

热点阅读