如何使用ImageGrid在colorbar上添加标签?

4
在之前的一个问题(colobar label matplotlib in ImageGrid)中,有一种方法可以向colorbar添加标签,但是这种方法在当前版本中好像已经失效了。
我尝试过的平台有:
- Mac w/ Canopy: - python: 2.7 - matplotlib: 1.4.3-6 - Linux: - python: 2.7 - matplotlib: 1.3.1
下面是来自之前问题的代码,并加入了在iPython笔记本中运行所需的额外代码:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid

def get_demo_image():
    import numpy as np
    from matplotlib.cbook import get_sample_data
    f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
    z = np.load(f)
    # z is a numpy array of 15x15
    return z, (-3,4,-4,3)

def demo_grid_with_single_cbar(fig):
    """
    A grid of 2x2 images with a single colorbar
    """
    grid = AxesGrid(fig, 132, # similar to subplot(132)
                    nrows_ncols = (2, 2),
                    axes_pad = 0.0,
                    share_all=True,
                    label_mode = "L",
                    cbar_location = "top",
                    cbar_mode="single",
                    )

    Z, extent = get_demo_image()
    for i in range(4):
        im = grid[i].imshow(Z, extent=extent, interpolation="nearest")
    #plt.colorbar(im, cax = grid.cbar_axes[0])
    #grid.cbar_axes[0].colorbar(im)
    cbar = grid.cbar_axes[0].colorbar(im)
    cbar.ax.set_label_text("$[a.u.]$")

    for cax in grid.cbar_axes:
        cax.toggle_label(False)

    # This affects all axes as share_all = True.
    grid.axes_llc.set_xticks([-2, 0, 2])
    grid.axes_llc.set_yticks([-2, 0, 2])
#
F = plt.figure(1, (10.5, 2.5))
F.subplots_adjust(left=0.05, right=0.95)
demo_grid_with_single_cbar(F)

plt.draw()
plt.show()

代码的错误消息格式如下:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-1-60ebdb832699> in <module>()
     40 F = plt.figure(1, (10.5, 2.5))
     41 F.subplots_adjust(left=0.05, right=0.95)
---> 42 demo_grid_with_single_cbar(F)
     43 
     44 plt.draw()

<ipython-input-1-60ebdb832699> in demo_grid_with_single_cbar(fig)
     29     #grid.cbar_axes[0].colorbar(im)
     30     cbar = grid.cbar_axes[0].colorbar(im)
---> 31     cbar.ax.set_label_text("$[a.u.]$")
     32 
     33     for cax in grid.cbar_axes:

AttributeError: 'CbarAxes' object has no attribute 'set_label_text'

自从最初的问题被提出以来,matplotlib接口有改变吗?如果是这样,我该如何添加colorbar标签?
1个回答

8

个人而言,我一直认为matplotlibTeX一样是黑魔法,所以我不能保证我的答案是您想要的“官方”方法,或者它将在以后的版本中继续工作。但感谢这个画廊示例,我可以设计出以下咒语:

grid[0].cax.colorbar(im)
cax = grid.cbar_axes[0]
axis = cax.axis[cax.orientation]
axis.label.set_text("$[a.u.]$")

(不要忘记删除所有与colorbar相关的代码)。这在当前的matplotlib版本(1.4.3)中有效。结果如下:

enter image description here


谢谢!有时我也会感到同样的“黑魔法”的感觉,但我使用得越多,就越能理解它了! - Aaron Anderson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接