【问题标题】:matplotlib colorbar limits for contourf轮廓f的matplotlib颜色条限制
【发布时间】:2022-01-09 19:16:49
【问题描述】:

您如何对与 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()

【问题讨论】:

  • 可能是ax.contourf(..., levels=np.arange(-3,4))?
  • 太棒了!这就是我需要的:)

标签: python matplotlib plot data-visualization colorbar


【解决方案1】:

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

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

【讨论】:

  • 谢谢!我的情节在没有“extend=both”的情况下被截断。
猜你喜欢
  • 2016-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-05
  • 1970-01-01
  • 2020-06-15
相关资源
最近更新 更多