Reputation: 124
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)
Upvotes: 3
Views: 6920
Reputation: 62373
colorbar.ColorbarBase.set_clim
results in AttributeError: 'ColorBar' object has no attribute 'set_clim'
matplotlib.cm.ScalarMappable.set_clim
insteadmatplotlib.cm
, matplotlib.cm.ScalarMappable
, set_clim()
, and matplotlib.colorbar
.set_clim
can be used on a returned image object, instead of the colorbar object.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')
Upvotes: 4
Reputation: 124
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)
Upvotes: 5