【问题标题】:How to add a colorbar to subplot2grid如何将颜色条添加到 subplot2grid
【发布时间】:2017-12-23 08:51:26
【问题描述】:

这应该很简单,但由于某种原因我无法让它工作:

def plot_image(images, heatmaps):
    plt.figure(0)
    for i, (image, map) in enumerate(zip(images, heatmaps)):
        a = plt.subplot2grid((2,4), (0,i))
        a.imshow(image)
        a = plt.subplot2grid((2,4), (1,i))
        a.imshow(map)
        plt.colorbar(a, fraction=0.046, pad=0.04) 
    plt.show()

颜色条行中的值取自here,但我得到:

AttributeError: 'AxesSubplot' 对象没有属性 'autoscale_None'

我正在绘制 2 x 4 网格的图像,我想在每个图像的右侧显示垂直颜色条,或者可能只在网格中最右边的图像旁边显示。

【问题讨论】:

    标签: python matplotlib subplot colormap


    【解决方案1】:

    plt.colorbar 期望图像作为其第一个参数(或通常是 ScalarMappable),而不是轴。

    plt.colorbar(im, ax=ax, ...)
    

    因此您的示例应为:

    import numpy as np
    import matplotlib.pyplot as plt
    
    def plot_image(images, heatmaps):
        fig = plt.figure(0)
        for i, (image, map) in enumerate(zip(images, heatmaps)):
            ax = plt.subplot2grid((2,4), (0,i))
            im = ax.imshow(image)
            ax2 = plt.subplot2grid((2,4), (1,i))
            im2 = ax2.imshow(map)
            fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04) 
            fig.colorbar(im2, ax=ax2, fraction=0.046, pad=0.04) 
        plt.show()
    
    a = [np.random.rand(5,5) for i in range(4)]
    b = [np.random.rand(5,5) for i in range(4)]
    plot_image(a,b)
    

    【讨论】:

      猜你喜欢
      • 2015-08-16
      • 1970-01-01
      • 1970-01-01
      • 2016-06-22
      • 2020-11-13
      • 2014-01-12
      • 2022-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多