【问题标题】:Matplotlib wrong color scheme when plotting colorbar绘制颜色条时 Matplotlib 错误的配色方案
【发布时间】:2020-07-07 09:15:47
【问题描述】:

当我尝试使用 contourf 绘制颜色条时,我得到了错误的配色方案和范围。它适用于 pcolormesh。我的目标是只为所有子图使用 1 个颜色条

fig = plt.figure(figsize=(9,8))
gs = gridspec.GridSpec(nrows=1, ncols=3)
color = plt.get_cmap('PRGn')

ax0 = plt.subplot(gs[0, 0])
ax0.contourf(x, y, z1, cmap=color)

ax1 = plt.subplot(gs[0, 1])
ax1.contourf(x, y, z2, cmap=color)

ax2 = plt.subplot(gs[0, 2])
ax2.contourf(x, y, z3, cmap=color)

# colorbar
im = plt.gca().get_children()[0]
cax = fig.add_axes([.918, 0.175, 0.025, 0.4])
cb = fig.colorbar(im, cax=cax)

谢谢

【问题讨论】:

    标签: python python-3.x matplotlib subplot colorbar


    【解决方案1】:

    最简单的方法是将contourf 的结果存储在一个变量中以传递给plt.colorbar

    请注意,要使 3 个图使用相同的颜色条,每个图的限制必须相同。默认情况下,vminvmax 设置为给定 z 数组的最小值和最大值。为了使 3 个图的它们相等,可以将它们设置为全局最小值和最大值。

    这是一个例子(使用现代方式定义子图):

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig, (ax0, ax1, ax2) = plt.subplots(nrows=1, ncols=3, figsize=(9, 8))
    
    # create some dummy data, where z1, z2 and z3 possibly have different ranges
    x, y = np.meshgrid(np.linspace(0, 4, 20), np.linspace(300, 850, 20))
    z1 = np.cos(x) + np.sin(y / 100)
    z2 = np.cos(x) + np.sin(y / 100) + 0.2
    z3 = np.cos(x) + np.sin(y / 100) + 0.5
    vmin = min(z1.min(), z2.min(), z3.min())
    vmax = max(z1.max(), z2.max(), z3.max())
    
    cmap = plt.get_cmap('PRGn')
    contour_z1 = ax0.contourf(x, y, z1, cmap=cmap, vmin=vmin, vmax=vmax)
    contour_z2 = ax1.contourf(x, y, z2, cmap=cmap, vmin=vmin, vmax=vmax)
    contour_z3 = ax2.contourf(x, y, z3, cmap=cmap, vmin=vmin, vmax=vmax)
    
    # colorbar
    cax = fig.add_axes([.918, 0.175, 0.025, 0.4])
    cb = fig.colorbar(contour_z1, cax=cax)
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多