本文共 6004 字,大约阅读时间需要 20 分钟。
contour做的云图不是填充的,而contourf画的云图是填充的
来两个例子一目了然,代码可用。()contour([X, Y,] Z, [levels], **kwargs)
X and Y must both be 2-D with the same shape as Z (e.g. created via numpy.meshgrid), or they must both be 1-D such that len(X) == M is the number of columns in Z and len(Y) == N is the number of rows in Z.
If not given, they are assumed to be integer indices, i.e. X = range(M), Y = range(N).
The height values over which the contour is drawn.
Determines the number and positions of the contour lines / regions.
If an int n, use MaxNLocator, which tries to automatically choose no more than n+1 “nice” contour levels between vmin and vmax.
If array-like, draw contour lines at the specified levels. The values must be in increasing order.
import matplotlibimport numpy as npimport matplotlib.cm as cmimport matplotlib.pyplot as pltdelta = 0.025x = np.arange(-3.0, 3.0, delta)y = np.arange(-2.0, 2.0, delta)X, Y = np.meshgrid(x, y)Z1 = np.exp(-X**2 - Y**2)Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)Z = (Z1 - Z2) * 2fig, ax = plt.subplots()CS = ax.contour(X, Y, Z)ax.clabel(CS, inline=True, fontsize=10)ax.set_title('Simplest default with labels')plt.show()我们可以结合cmap,让不同大小区域用不同颜色填充,将下面代码替换掉上面的相应代码。
fig, ax = plt.subplots()im = ax.imshow(Z, interpolation='bilinear', origin='lower', cmap=cm.gray, extent=(-3, 3, -2, 2))levels = np.arange(-1.2, 1.6, 0.2)CS = ax.contour(Z, levels, origin='lower', cmap='flag', extend='both', linewidths=2, extent=(-3, 3, -2, 2))# Thicken the zero contour.zc = CS.collections[6]plt.setp(zc, linewidth=4)ax.clabel(CS, levels[1::2], # label every second level inline=True, fmt='%1.1f', fontsize=14)# make a colorbar for the contour linesCB = fig.colorbar(CS, shrink=0.8)ax.set_title('Lines with colorbar')# We can still add a colorbar for the image, too.CBI = fig.colorbar(im, orientation='horizontal', shrink=0.8)# This makes the original colorbar look a bit out of place,# so let's improve its position.l, b, w, h = ax.get_position().boundsll, bb, ww, hh = CB.ax.get_position().boundsCB.ax.set_position([ll, b + 0.1*h, ww, h*0.8])plt.show()
contour([X, Y,] Z, [levels], **kwargs)
X and Y must both be 2-D with the same shape as Z (e.g. created via numpy.meshgrid), or they must both be 1-D such that len(X) == M is the number of columns in Z and len(Y) == N is the number of rows in Z.
If not given, they are assumed to be integer indices, i.e. X = range(M), Y = range(N).
Determines the number and positions of the contour lines / regions.
If an int n, use MaxNLocator, which tries to automatically choose no more than n+1 “nice” contour levels between vmin and vmax.
If array-like, draw contour lines at the specified levels. The values must be in increasing order.
import numpy as npimport matplotlib.pyplot as pltorigin = 'lower'delta = 0.025x = y = np.arange(-3.0, 3.01, delta)X, Y = np.meshgrid(x, y)Z1 = np.exp(-X**2 - Y**2)Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)Z = (Z1 - Z2) * 2nr, nc = Z.shape# put NaNs in one corner:Z[-nr // 6:, -nc // 6:] = np.nan# contourf will convert these to maskedZ = np.ma.array(Z)# mask another corner:Z[:nr // 6, :nc // 6] = np.ma.masked# mask a circle in the middle:interior = np.sqrt(X**2 + Y**2) < 0.5Z[interior] = np.ma.masked# We are using automatic selection of contour levels;# this is usually not such a good idea, because they don't# occur on nice boundaries, but we do it here for purposes# of illustration.fig1, ax2 = plt.subplots(constrained_layout=True)CS = ax2.contourf(X, Y, Z, 10, cmap=plt.cm.bone, origin=origin)# Note that in the following, we explicitly pass in a subset of# the contour levels used for the filled contours. Alternatively,# We could pass in additional levels to provide extra resolution,# or leave out the levels kwarg to use all of the original levels.CS2 = ax2.contour(CS, levels=CS.levels[::2], colors='r', origin=origin)ax2.set_title('Nonsense (3 masked regions)')ax2.set_xlabel('word length anomaly')ax2.set_ylabel('sentence length anomaly')# Make a colorbar for the ContourSet returned by the contourf call.cbar = fig1.colorbar(CS)cbar.ax.set_ylabel('verbosity coefficient')# Add the contour line levels to the colorbarcbar.add_lines(CS2)fig2, ax2 = plt.subplots(constrained_layout=True)# Now make a contour plot with the levels specified,# and with the colormap generated automatically from a list# of colors.levels = [-1.5, -1, -0.5, 0, 0.5, 1]CS3 = ax2.contourf(X, Y, Z, levels, colors=('r', 'g', 'b'), origin=origin, extend='both')# Our data range extends outside the range of levels; make# data below the lowest contour level yellow, and above the# highest level cyan:CS3.cmap.set_under('yellow')CS3.cmap.set_over('cyan')CS4 = ax2.contour(X, Y, Z, levels, colors=('k',), linewidths=(3,), origin=origin)ax2.set_title('Listed colors (3 masked regions)')ax2.clabel(CS4, fmt='%2.1f', colors='w', fontsize=14)# Notice that the colorbar gets all the information it# needs from the ContourSet object, CS3.fig2.colorbar(CS3)# Illustrate all 4 possible "extend" settings:extends = ["neither", "both", "min", "max"]cmap = plt.cm.get_cmap("winter")cmap.set_under("magenta")cmap.set_over("yellow")# Note: contouring simply excludes masked or nan regions, so# instead of using the "bad" colormap value for them, it draws# nothing at all in them. Therefore the following would have# no effect:# cmap.set_bad("red")fig, axs = plt.subplots(2, 2, constrained_layout=True)for ax, extend in zip(axs.ravel(), extends): cs = ax.contourf(X, Y, Z, levels, cmap=cmap, extend=extend, origin=origin) fig.colorbar(cs, ax=ax, shrink=0.9) ax.set_title("extend = %s" % extend) ax.locator_params(nbins=4)plt.show()
转载地址:http://ftrti.baihongyu.com/