Search code examples
pythonmatplotlibcolorbar

Change Colorbar limit for changing scale with matplotlib 3.3+


The code at the bottom does exactly what I want it to do, but exclusively to a matplotlib version below at least 3.3.4 . For this version, 3.3.4, I get the following error message:

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

Accordingly, I tried to find out, how to do this in today's version, but failed. So, how can I change the color scale of the image and the Colobar in the newer versions?

Working Code (tested in 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)

Solution

  • I found a solution with the by @Trenton McKinneys provided link in the following post: Question by Merk.

    Solved code:

    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)
    

    (One) provided image: enter image description here