Using a slider to change variable and replot Matpl

2019-09-16 10:54发布

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.

1条回答
贼婆χ
2楼-- · 2019-09-16 11:31

The problem is as the error tells you, axes objects don't have a set_clim function. You want to change (which makes the error you report on the one I expect, but)

fig.set_clim(smin.val,smax.val)

to

l.set_clim(smin.val,smax.val)

as you need to call set_clim on a ScalarMappable object (doc).

As a side note, np.random.random takes a size arguement so you can do

z = np.random.random((100, 100))

instead of your nested loops.

查看更多
登录 后发表回答