注意
前往結尾以下載完整的範例程式碼。
等高線展示#
說明簡單的等高線繪圖、帶有等高線色彩條的影像上的等高線,以及標記的等高線。
另請參閱等高線影像範例。
使用預設色彩建立帶有標籤的簡單等高線圖。clabel 的 inline 引數將控制標籤是否繪製在等高線的線段上方,移除標籤下方的線條。
fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z)
ax.clabel(CS, fontsize=10)
ax.set_title('Simplest default with labels')

可以透過提供位置列表(以資料座標表示)來手動放置等高線標籤。有關互動式放置,請參閱互動式函數。
fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z)
manual_locations = [
(-1, -1.4), (-0.62, -0.7), (-2, 0.5), (1.7, 1.2), (2.0, 1.4), (2.4, 1.7)]
ax.clabel(CS, fontsize=10, manual=manual_locations)
ax.set_title('labels at selected locations')

您可以強制所有等高線使用相同的顏色。
fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z, 6, colors='k') # Negative contours default to dashed.
ax.clabel(CS, fontsize=9)
ax.set_title('Single color - negative contours dashed')

您可以將負等高線設定為實線而非虛線
plt.rcParams['contour.negative_linestyle'] = 'solid'
fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z, 6, colors='k') # Negative contours default to dashed.
ax.clabel(CS, fontsize=9)
ax.set_title('Single color - negative contours solid')

而且您可以手動指定等高線的色彩
fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z, 6,
linewidths=np.arange(.5, 4, .5),
colors=('r', 'green', 'blue', (1, 1, 0), '#afeeee', '0.5'),
)
ax.clabel(CS, fontsize=9)
ax.set_title('Crazy lines')

或者您可以使用色彩映射來指定色彩;預設色彩映射將用於等高線。
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.
lws = np.resize(CS.get_linewidth(), len(levels))
lws[6] = 4
CS.set_linewidth(lws)
ax.clabel(CS, levels[1::2], # label every second level
fmt='%1.1f', fontsize=14)
# make a colorbar for the contour lines
CB = 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().bounds
ll, bb, ww, hh = CB.ax.get_position().bounds
CB.ax.set_position([ll, b + 0.1*h, ww, h*0.8])
plt.show()

參考資料
本範例中顯示了以下函數、方法、類別和模組的使用方式
腳本總執行時間: (0 分鐘 5.790 秒)