【问题标题】:Change Colorbar limit for changing scale with matplotlib 3.3+使用 matplotlib 3.3+ 更改颜色条限制以更改比例
【发布时间】:2021-11-24 19:47:35
【问题描述】:

底部的代码完全符合我的要求,但仅限于至少低于 3.3.4 的 matplotlib 版本。对于此版本 3.3.4,我收到以下错误消息:

AttributeError: 'ColorBar' object has no attribute 'set_clim'

因此,我试图找出如何在今天的版本中执行此操作,但失败了。 那么,如何在新版本中更改图像和 Colobar 的色阶?

工作代码(在 2.2.2 中测试):

import matplotlib.pyplot as plt
import numpy as np
import time

x = np.linspace(0, 10, 100)
y = np.cos(x)
y = y.reshape(10,10)

plt.ion()

figure = plt.figure()
line1 = plt.imshow(y)
cbar = plt.colorbar(line1)

for p in range(100):
    updated_y = np.random.randint(0,10)*np.cos(x-0.05*p).reshape(10,10)
    
    line1.set_data(updated_y)

    cbar.set_clim(vmin=np.min(updated_y),vmax=np.max(updated_y)) #this line creates the error
    cbar.draw_all()
    
    figure.canvas.draw()
    figure.canvas.flush_events()
    time.sleep(1)

【问题讨论】:

    标签: python matplotlib colorbar


    【解决方案1】:

    import matplotlib.image as mpimg
    import matplotlib.pyplot as plt
    
    img = mpimg.imread('stinkbug.png')
    lum_img = img[:, :, 0]
    
    fig, (ax1, ax2)= plt.subplots(1, 2, figsize=(10, 7))
    
    im1 = ax1.imshow(lum_img)
    im1.set_cmap('nipy_spectral')
    ax1.set_title('Before')
    fig.colorbar(im1, ax=ax1, ticks=[0.1, 0.3, 0.5, 0.7], orientation='horizontal')
    
    im2 = ax2.imshow(lum_img)
    im2.set_cmap('nipy_spectral')
    im2.set_clim(0.0, 0.7)  # set clim on the im2 image object
    ax2.set_title('After')
    fig.colorbar(im2, ax=ax2, ticks=[0.1, 0.3, 0.5, 0.7], orientation='horizontal')
    

    【讨论】:

      【解决方案2】:

      我通过@Trenton McKinneys 在以下帖子中提供的链接找到了解决方案:Question by Merk

      解决的代码:

      import matplotlib.pyplot as plt
      import numpy as np
      import time
      
      x = np.linspace(0, 10, 100)
      y = np.cos(x)
      y = y.reshape(10,10)
      
      plt.ion()
      
      figure = plt.figure()
      line1 = plt.imshow(y)
      cbar = plt.colorbar(line1)
      
      for p in range(100):
          updated_y = np.random.randint(0,10)*np.cos(x-0.05*p).reshape(10,10)
          
          line1.set_data(updated_y)
      
          #cbar.set_clim(vmin=np.min(updated_y),vmax=np.max(updated_y)) #this line creates the error
          cbar.mappable.set_clim(vmin=np.min(updated_y),vmax=np.max(updated_y)) #this works
          cbar.draw_all()
          
          figure.canvas.draw()
          figure.canvas.flush_events()
          time.sleep(1)
      

      (一)提供的图片:

      【讨论】:

        猜你喜欢
        • 2013-07-21
        • 2021-01-07
        • 1970-01-01
        • 2015-01-07
        • 1970-01-01
        • 2020-04-12
        • 1970-01-01
        • 1970-01-01
        • 2021-10-26
        相关资源
        最近更新 更多