【问题标题】:Adding a single colorbar to multiple healpy subplots将单个颜色条添加到多个 healpy 子图中
【发布时间】:2020-08-29 02:25:54
【问题描述】:

我想将自定义 plt.colorbar 添加到包含多个 healpy 绘图的图形中。我发现了很多关于如何针对多个 axes 对象的常见情况执行此操作的帖子,但 healpy 使其变得困难。

到目前为止,我有以下 MWE:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import healpy as hp

rows, cols = 8, 8
nplots = rows * cols
npix = 48
data = np.random.uniform(size=(nplots, npix))
fig = plt.figure()
for i in range(len(data)):
    hp.mollview(data[i, :], title='', cbar=False, fig=fig,
                sub=(rows, cols, i+1), margins=(0, 0, 0, 0),
                min=data.min(), max=data.max())

fig, ax = plt.gcf(), plt.gca()
image = ax.get_images()[0]
norm =  mpl.colors.Normalize(vmin=data.min(), vmax=data.max())

from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(ax)
cax = divider.new_vertical(size="5%", pad=0.7, pack_start=True)
fig.add_axes(cax)
fig.colorbar(image, cax=cax, norm=norm, orientation='horizontal',
             label='colorbar')
plt.show()

See the erroneous plot here

如链接图像所示,我最终将colorbar 附加到最后一个ax,而不是整个fig。我想在fig 的底部(或右侧)有一个简单的colorbar,其范围通过Normalize 指定,如上所述。同样,事实上,我使用healpy 生成的数字排除了通常的解决方案,至少据我所知。

【问题讨论】:

    标签: python matplotlib healpy


    【解决方案1】:

    我没有安装 healpy,但可能这个库只是创建了自己的轴。下面的代码模拟了这种情况。您可以从fig.axes 获取坐标轴。 与this tutorial 一样,只需提供所有“轴”的列表即可放置默认颜色条(ax 或多或少是 matplotlib 子图的名称):plt.colorbar(im, ax=fig.axes)。如果颜色条太大,它有一个shrink=0.6 参数。

    from matplotlib import pyplot as plt
    import numpy as np
    
    fig = plt.figure(figsize=(20, 6))
    
    nrows = 4
    ncols = 6
    for i in range(1, nrows + 1):
        for j in range(1, ncols + 1):
            plt.subplot(nrows, ncols, (i - 1) * ncols + j, projection="mollweide")
            arr = np.random.rand(18, 36)
            Lon, Lat = np.meshgrid(np.linspace(-np.pi, np.pi, 36 + 1), np.linspace(-np.pi / 2., np.pi / 2., 18 + 1))
            plt.pcolormesh(Lon, Lat, arr, cmap=plt.cm.hot)
    im = fig.axes[0].collections[0] # or fig.axes[0].get_images()[0] when created as image
    plt.colorbar(im, ax=fig.axes)
    
    plt.show()
    

    请注意,在您的代码中,fig 已经指向当前图形,因此不需要 fig = plt.gcf()ax = plt.gca() 表示上次活动的ax。在示例图的情况下,这似乎是右下角。因此,这有助于找到示例图像,但不能将颜色条放置在所有子图旁边。

    如果您需要对颜色条位置进行更多控制,也可以采用this post的方法:

    fig.subplots_adjust(right=0.85)
    cbar_ax = fig.add_axes([0.90, 0.15, 0.03, 0.7])
    fig.colorbar(im, cax=cbar_ax)
    

    【讨论】:

    • 这很好用,谢谢!我不得不使用im = fig.axes[0].get_images()[0] 的第二个建议,因为fig.axes[0] 的类型为healpy.projaxes.HpxMollweideAxesfig.axes[0].collections 是一个空列表。
    猜你喜欢
    • 2020-07-23
    • 2021-08-14
    • 2019-03-22
    • 1970-01-01
    • 2023-01-12
    • 2016-06-22
    • 2020-11-13
    • 2015-08-18
    • 1970-01-01
    相关资源
    最近更新 更多