【问题标题】:How to add a colorbar to one subplot axes如何将颜色条添加到一个子图轴
【发布时间】:2021-08-14 01:43:50
【问题描述】:

我正在尝试使用 matplotlib 创建一个图形,但它并没有像我预期的那样顺利。我想在顶行创建一个包含 4 个图像的合成图形,以及 4 个图像正下方的 1 个长图像。我想只为底部图像添加一个颜色条,但是,它会抛出错误。

import numpy as np
import matplotlib.pyplot as plt

img = np.random.rand(25, 20)
img2 = np.random.rand(25, 100)

fig = plt.figure(figsize=(12.8, 8.6),
#           gridspec_kw={'height_ratios':[1, 1.5],
#                     'wspace':0.1, 'hspace':0.1}
          )

im0 = plt.subplot(2,4,1)
im0.imshow(img, aspect='equal')
im0.axis('off')

im1 = plt.subplot(2,4,2)
im1.imshow(img, aspect='equal')
im1.axis('off')

im2 = plt.subplot(2,4,3)
im2.imshow(img, aspect='equal')
im2.axis('off')

im3 = plt.subplot(2,4,4)
im3.imshow(img, aspect='equal')
im3.axis('off')

im4 = plt.subplot(2,1,2)
im4.imshow(img2, aspect='equal')
im4.axis('off')

# cbar = fig.colorbar(im4)

plt.show()

取消注释 cbar = fig.colorbar(im4) 会导致:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-170-91eaa4089d9f> in <module>
     27 im4.axis('off')
     28 
---> 29 cbar = fig.colorbar(im4)
     30 
     31 plt.show()

e:\Anaconda3\lib\site-packages\matplotlib\figure.py in colorbar(self, mappable, cax, ax, use_gridspec, **kw)
   1171                              'panchor']
   1172         cb_kw = {k: v for k, v in kw.items() if k not in NON_COLORBAR_KEYS}
-> 1173         cb = cbar.Colorbar(cax, mappable, **cb_kw)
   1174 
   1175         self.sca(current_ax)

e:\Anaconda3\lib\site-packages\matplotlib\colorbar.py in __init__(self, ax, mappable, **kwargs)
   1169         # Ensure the given mappable's norm has appropriate vmin and vmax set
   1170         # even if mappable.draw has not yet been called.
-> 1171         if mappable.get_array() is not None:
   1172             mappable.autoscale_None()
   1173 

AttributeError: 'AxesSubplot' object has no attribute 'get_array'

【问题讨论】:

    标签: python matplotlib colorbar


    【解决方案1】:
    • 使用来自Axes Divider 的示例
    • 将绘图分配给单独的对象。
      • im&lt;class 'matplotlib.image.AxesImage'&gt;
      • im4&lt;class 'matplotlib.axes._subplots.AxesSubplot'&gt;
    im4 = plt.subplot(2,1,2)
    
    # assign plot to a new object
    im = im4.imshow(img2, aspect='equal')
    
    # add the bar
    cbar = plt.colorbar(im)
    
    im4.axis('off')
    
    plt.show()
    

    【讨论】:

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