contourf 的 matplotlib 颜色条限制

matplotlib colorbar limits for contourf

你如何对与 contourf 一起使用的颜色条设置硬性限制?下面的代码按预期工作,使用 plot_surface 时颜色条限制设置为 [-3, 3],但使用 contourf 时限制不在颜色条的提示处。我需要它来从具有恒定颜色条的多个图像创建 gif。

import matplotlib.pyplot as plt 
import numpy as np

fig = plt.figure()

ax = fig.gca(projection='3d')
CHI = np.linspace(-45, 45, 35);
M = np.linspace(0, 1, 35) 
CHI, M = np.meshgrid(CHI, M)
R = 10*2*M*np.sin(  2 * np.deg2rad(CHI) )

cont = ax.contourf(CHI, M, R)
#cont = ax.plot_surface(CHI, M, R)
cont.set_clim(vmin=-3, vmax=3)

ax.set_xlim(-45,45)
cbar = plt.colorbar(cont, ticks=[-3,-2,-1,0,1,2,3])
plt.show()

您可以将 levels 参数传递给 matplotlib.pyplot.contourf 以指定轮廓区域的数量和位置。然后你可以设置 extend = 'both' 以绘制你使用的 levels 范围之外的国家地区:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()

ax = fig.gca(projection='3d')
CHI = np.linspace(-45, 45, 35);
M = np.linspace(0, 1, 35)
CHI, M = np.meshgrid(CHI, M)
R = 10*2*M*np.sin(  2 * np.deg2rad(CHI) )

levels = [-3, -2, -1, 0, 1, 2, 3]

cont = ax.contourf(CHI, M, R, levels = levels, extend = 'both')

ax.set_xlim(-45,45)
cbar = plt.colorbar(cont)
plt.show()