【问题标题】:Empty colorbar using basemap.pcolor in an ImageGrid在 ImageGrid 中使用 basemap.pcolor 清空颜色条
【发布时间】:2016-10-21 09:30:25
【问题描述】:

以下代码生成我想要的图像,但颜色条为空白/白色,并且与数据不匹配:

def plot_array(da, ax=None, shift=True):
    """plots an array of lat by lon on a coastline map"""

    m = basemap.Basemap()
    m.drawcoastlines()
    m.pcolormesh(da.lon, y=da.lat, data=da.T, latlon=True)

    return m

# 'monthly mean' is an xarray DataArray

fig = plt.figure(0, (14, 8))
grid = ImageGrid(fig, 111, nrows_ncols=(3, 4), axes_pad=0.3,
                 cbar_mode='single', cbar_location="bottom",)
for i, m in enumerate(months):
    plt.sca(grid[i])
    plot_array(monthly_mean.sel(month=i + 1))
    plt.title(m)
plt.suptitle("{b} - {y} monthly means".format(b=benchmark, y=year))
# plt.colorbar()
plt.tight_layout()

os.makedirs("plots/monthly_means/{y}".format(y=year), exist_ok=True)
plt.savefig("plots/monthly_means/{y}/{b}_{y}.png".format(b=benchmark, y=year))
plt.close()

我还需要做些什么才能让颜色条与 ImageGrid 一起使用,还是 ImageGrid 和 Basemap 不能很好地协同工作?

【问题讨论】:

    标签: python matplotlib matplotlib-basemap subplot


    【解决方案1】:

    据我了解,这不是底图问题。 ImageGrid() 调用只是为颜色条设置了一组空白轴,可以通过cax 参数传递给plt.colorbar()。默认情况下,ImageGrid() 具有参数cbar_set_cax=True,它在每个子图上设置cax 属性。然后你可以把它传递给colorbar():

    ...
    plt.colorbar(cax=grid[0].cax)
    plt.tight_layout()
    ...
    

    这将只使用当前活动的轴来确定颜色条数据范围,因此它只会与最终图一致。您将不得不使用vmin/vmaxpcolormesh() 的组合来确保所有绘图的一致性。

    【讨论】:

    • 当我尝试使用plt.colorbar(cax=grid[0].cax) 时,我得到一个错误:RuntimeError: No mappable was found to use for colorbar creation. First define a mappable such as an image (with imshow) or a contour set (with contourf). 如果我尝试plt.colorbar(plt.gca(), cax=grid[0].cax) 我得到错误AttributeError: 'CbarAxes' object has no attribute 'autoscale_None' 最后,如果我尝试plt.colorbar(grid[0],cax=grid[0].cax) 我得到错误AttributeError: 'LocatableAxes' object has no attribute 'autoscale_None 知道如何解决这个问题吗?
    • 使用下面的 Serentiy 答案解决了这个问题
    • @user2472441 可能有点。 plt.colorbar(pcm) 正在添加一个新的颜色条实例,而不是替换已经由 ImageGrid 建立的实例。原来的空白仍然存在于新的下方 - 尝试在颜色栏调用中设置 orientation="vertical" 以查看它们。如果您不替换原始的,它可能会以一些图形尺寸显示。
    【解决方案2】:

    Matplotlib 无法定义您要在颜色条上绘制的内容。像这样写

    ...
    pcm = m.pcolormesh(da.lon, y=da.lat, data=da.T, latlon=True)
    plt.colorbar(pcm)
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-04
      • 2012-04-01
      相关资源
      最近更新 更多