I'm trying to use a slider to change the limits for color scaling i.e using the set_clim(min,max) function. I want it so that two sliders control the values for the min and max values and after they have changed the figure is replotted.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.widgets import Slider, Button
x=np.linspace(0,100,100)
y=np.linspace(0,100,100)
z=np.zeros((100,100))
for i in range (0,100):
for j in range (0,100):
z[i,j]=np.random.random()
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.25)
l=plt.contourf(x,y,z)
axmax = plt.axes([0.25, 0.1, 0.65, 0.03])
axmin = plt.axes([0.25, 0.15, 0.65, 0.03])
smax = Slider(axmax, 'Max', 0, 1.0, valinit=1)
smin = Slider(axmin, 'Min', 0, 1.0, valinit=0)
def update(val):
fig.set_clim(smin.val,smax.val)
fig.canvas.draw_idle()
smax.on_changed(update)
smin.on_changed(update)
plt.show()
The above code gives me " AttributeError: 'AxesSubPlot' object has no attribute 'set_clim' " when I move the sliders although it does show me the initial unchanged figure. This is my first time using widgets in python (and more or less my first time using python) so there may well be some quite fundamental misunderstandings.
The problem is as the error tells you,
axes
objects don't have aset_clim
function. You want to change (which makes the error you report on the one I expect, but)to
as you need to call
set_clim
on aScalarMappable
object (doc).As a side note,
np.random.random
takes a size arguement so you can doinstead of your nested loops.