Lla*_*maD 5 python user-interface widget matplotlib
我正在尝试使用滑块更改 matplotlib 填充等值线图上的颜色级别值。即轮廓f(x,y,z,np.linspace(a,b,n)),其中滑块将控制a和b,并在移动滑块时更改绘图颜色级别。以下代码采用列格式数据将其转换为contourf所需的形式,然后实现滑块。这是我尝试过的:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
data=np.genfromtxt('file.dat',skip_header=1)
len=np.sqrt(data[:,0].size)
x=np.reshape(data[:,0],(len,len))
y=np.reshape(data[:,1],(len,len))
z=np.reshape(data[:,3],(len,len))
l=plt.contourf(x,y,z,np.linspace(0,100,255))
axmax = plt.axes([0.25, 0.1, 0.65, 0.03]) #slider location and size
axmin = plt.axes([0.25, 0.15, 0.65, 0.03])
smax = Slider(axmax, 'Max',0, 100, 50) #slider properties
smin = Slider(axmin, 'Min', 0, 100, 0)
def update(val):
l.levels(np.linspace(smin.val,smax.val,255))#changing levels of plot
fig.canvas.draw_idle() #line that throws error
smax.on_changed(update)
smin.on_changed(update)
plt.show()
Run Code Online (Sandbox Code Playgroud)
当滑块移动时,会引发大量 matplotlib 错误,相关错误为“TypeError:'numpy.ndarray' object is not callable”,由该行抛出
fig.canvas.draw_idle()
Run Code Online (Sandbox Code Playgroud)
问题是这l.levels是一个数组,因此您必须更改该数组中的值。在我的测试中,更改这些值不会导致绘图更新。因此,另一种解决方案是清除轴并重新绘制绘图。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
data=np.random.random([25,4])
data = data*100
len=np.sqrt(data[:,0].size)
x=np.reshape(data[:,0],(len,len))
y=np.reshape(data[:,1],(len,len))
z=np.reshape(data[:,3],(len,len))
l=plt.contourf(x,y,z,np.linspace(0,100,255))
contour_axis = plt.gca()
axmax = plt.axes([0.25, 0.1, 0.65, 0.03]) #slider location and size
axmin = plt.axes([0.25, 0.15, 0.65, 0.03])
smax = Slider(axmax, 'Max',0, 100, 50) #slider properties
smin = Slider(axmin, 'Min', 0, 100, 0)
def update(val):
contour_axis.clear()
contour_axis.contourf(x,y,z,np.linspace(smin.val,smax.val,255))
plt.draw()
smax.on_changed(update)
smin.on_changed(update)
plt.show()
Run Code Online (Sandbox Code Playgroud)