本文整理汇总了Python中matplotlib.widgets.Slider.on_changed方法的典型用法代码示例。如果您正苦于以下问题:Python Slider.on_changed方法的具体用法?Python Slider.on_changed怎么用?Python Slider.on_changed使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.widgets.Slider
的用法示例。
在下文中一共展示了Slider.on_changed方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: sliders
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import on_changed [as 别名]
def sliders(limits, ax, cb, valinits=None):
if valinits is None or not all([lim and len(lim) == 2
for lim in valinits]):
valinits = limits
axcolor = "lightgoldenrodyellow"
bottom = 0.1
sliders = []
plt.subplots_adjust(left=0.25, bottom=bottom*2+0.05*len(limits)*2)
for i in range(len(limits)):
axstime = plt.axes([0.25, bottom, 0.65, 0.03], axisbg=axcolor)
bottom += 0.05
axetime = plt.axes([0.25, bottom, 0.65, 0.03], axisbg=axcolor)
bottom += 0.05
stime = Slider(
axstime,
"Start {}".format(
i+1),
limits[i][0],
limits[i][1],
valinit=valinits[i][0],
valfmt="%.2f")
etime = Slider(
axetime,
"End {}".format(
i+1),
limits[i][0],
limits[i][1],
valinit=valinits[i][1],
valfmt="%.2f")
stime.on_changed(cb)
etime.on_changed(cb)
sliders.append([stime, etime])
return sliders
示例2: preparePlot
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import on_changed [as 别名]
def preparePlot(shapeModeler):
global sliders, mainPlot, fig
fig, ax = plt.subplots();
whiteSpace = 0.15 + numParams*0.05;
plt.subplots_adjust( bottom=whiteSpace);
plt.axis('equal');
#plot of initial shape
params = np.zeros((numParams,1));
shape = shapeModeler.makeShape(params);
shape = ShapeModeler.normaliseShape(shape);
numPointsInShape = len(shape)/2;
x_shape = shape[0:numPointsInShape];
y_shape = shape[numPointsInShape:];
mainPlot, = plt.plot(x_shape, -y_shape);
plt.axis([-1, 1, -1, 1],autoscale_on=False, aspect='equal');
#add sliders to modify parameter values
parameterVariances = shapeModeler.getParameterVariances();
sliders = [0]*numParams;
for i in range(numParams):
slider = Slider(plt.axes([0.25, 0.1+0.05*(numParams-i-1), 0.65, 0.03], axisbg=axcolor),
'Parameter '+str(i+1), -5*parameterVariances[i], 5*parameterVariances[i], valinit=0);
slider.on_changed(update);
sliders[i] = slider;
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
button.on_clicked(reset)
plt.show()
示例3: plotter
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import on_changed [as 别名]
def plotter():
'''
This process is supposed to handle the graphs.
Not pretty at the moment... but then matplotlib never is.
'''
signal.signal(signal.SIGINT, signal.SIG_IGN) # Ignore keyboard interrupt signal, parent process will handle.
waterfall_size = 150 # This makes it about 75 seconds in theory. Drawing the graph sometimes takes a bit longer.
fig = plt.figure(figsize=(20,15))
plt.subplots_adjust(left = 0.1, bottom = 0.25)
ax = plt.subplot(1, 1, 1)
line_lcp, = ax.plot([], [], 'bo', lw=1)
line_rcp, = ax.plot([], [], 'ro', lw=1)
ax.set_xlim(0,400)
vav_data_lcp = collections.deque(maxlen = waterfall_size)
vav_data_rcp = collections.deque(maxlen = waterfall_size)
slider_ax = plt.axes([0.25, 0.1, 0.65, 0.03])
video_average_length_slider = Slider(slider_ax, 'VAv', 1, waterfall_size, valinit=video_average_length.value)
def update(val):
video_average_length.value = int(video_average_length_slider.val)
fig.canvas.draw_idle()
video_average_length_slider.on_changed(update)
def init():
x = np.zeros(data_width)
y = np.zeros(data_width)
line_lcp.set_data(x,y)
line_rcp.set_data(x,y)
return line,
def animate(*args):
if script_run.value != 1:
sys.exit()
x = np.arange(0, 400, 400.0 / 1024.0)
vav_data_lcp.appendleft(data_stream_1[:])
vav_data_rcp.appendleft(data_stream_2[:])
lcp = np.zeros(data_width)
rcp = np.zeros(data_width)
for i in range(video_average_length.value):
if i < len(vav_data):
lcp += np.array(vav_data_lcp[i])
rcp += np.array(vav_data_rcp[i])
lcp /= video_average_length.value
rcp /= video_average_length.value
graph_max = 0
if lcp.max() > rcp.max():
graph_max = lcp.max()
else:
graph_max = rcp.max()
ax.set_ylim(0,graph_max + 1)
line_lcp.set_data(x,lcp)
line_rcp.set_data(x.rcp)
return line,
# Set the animation off to a start...
anim = animation.FuncAnimation(fig, animate, init_func=init, blit=True, interval=500)
plt.show()
print 'plotter process finished.'
示例4: mplot
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import on_changed [as 别名]
def mplot(func,x,**kwargs):
num_params = len(kwargs)
fig = plt.figure()
main_ax = fig.add_subplot(111)
fig.subplots_adjust(bottom=bottom_pad + (num_params+1)*per_slider)
param_vals = dict((param_name,(lo+hi)/2) for param_name, (lo,hi) in kwargs.items())
y = func(x,**param_vals)
l, = main_ax.plot(x,y)
def update(*args):
for param_name, slider in zip(param_vals,sliders):
param_vals[param_name] = slider.val
vals = func(x,**param_vals)
l.set_ydata(vals)
# using autoscale_view makes the axes shrink *and* grow
#main_ax.relim()
#main_ax.autoscale_view()
# setting ylim this way only lets the axes grow
ymin, ymax = main_ax.get_ylim()
main_ax.set_ylim(min(vals.min(),ymin),max(ymax,vals.max()))
fig.canvas.draw()
sliders = []
for idx, (param_name, (lo,hi)) in enumerate(kwargs.items()):
ax = fig.add_axes([0.25,bottom_pad+per_slider*idx,0.65,3/5*per_slider],axisbg=bgcolor)
slider = Slider(ax, param_name, lo, hi, valinit=param_vals[param_name])
slider.on_changed(update)
sliders.append(slider)
plt.axes(main_ax)
示例5: SinSlider
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import on_changed [as 别名]
class SinSlider():
pi = 3.14159
def __init__(self, num):
self.init_plot(num)
self.init_slider(num)
def init_plot(self, num):
pylab.subplot(111)
pylab.subplots_adjust(bottom = 0.25)
pylab.axis([0.0, 2 * self.pi, -1.0, 1.0])
pylab.title("y = sin(num * x)")
pylab.xlabel("x")
pylab.ylabel("y")
x, y = self.calc_xy(num)
self.plot, = pylab.plot(x, y) # comma after 'self.plot'
def init_slider(self, num):
slider_axes = pylab.axes([0.1, 0.1, 0.8, 0.05]) # left, bottom, width, height
self.slider = Slider(slider_axes, 'num', 0.0, 4.0, valinit = num)
self.slider.on_changed(self.update)
def update(self, num):
_, new_y = self.calc_xy(num)
self.plot.set_ydata(new_y)
pylab.draw()
def calc_xy(self, num):
start = 0.0
stop = 2 * self.pi
step = 0.01
x = pylab.arange(start, stop, step)
y = pylab.sin(num * x)
return x, y
示例6: slider
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import on_changed [as 别名]
class slider():
def __init__(self,res):
self.res=res
def slider_bar(self,res):
#setupthe slider
axcolor = 'lightgoldenrodyellow'
self.axtime = plt.axes([0.1, 0.05, 0.8, 0.03], axisbg=axcolor)
self.stime = Slider(self.axtime, 'Timestep', 0, len(res.resobj.fils.fid.dimensions['Time']), valinit=0)
def update(val,res):
t = self.stime.val
res.refresh_plot(t)
self.stime.on_changed(update(self,res))
def foward_button(self,res):
self.fwdax = plt.axes([0.1, 0.1, 0.1, 0.04])
self.fwdb = Button(self.fwdax, 'forward', color='lightgoldenrodyellow', hovercolor='0.975')
self.fwdb.on_clicked(slider.update(res.resobj.timestep-1,res))
示例7: ChangingPlot
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import on_changed [as 别名]
class ChangingPlot(object):
"""
Gives a pyplot object with a slider that shows the complex roots of
the truncated power series for the number of terms on the slider.
"""
def __init__(self,poly,NUMTERMS):
self.sols,self.NUMTERMS = solLists(poly,NUMTERMS)
self.windowBounds = minmax(self.sols)
self.inc = 1.0
self.fig, self.ax = plt.subplots()
self.sliderax = self.fig.add_axes([0.2, 0.02, 0.6, 0.03],
axisbg='yellow')
self.slider = Slider(self.sliderax, 'Value', 0, self.NUMTERMS-3, valinit=self.inc)
self.slider.on_changed(self.update)
self.slider.drawon = False
self.dot, = self.ax.plot(self.sols[0][0],self.sols[0][1], 'bo')
self.ax.axis(self.windowBounds)
def update(self, value):
value = int(value)
self.dot.set_data(self.sols[value][0],self.sols[value][1])
self.slider.valtext.set_text('{}'.format(value))
self.fig.canvas.draw()
def show(self):
plt.show()
示例8: create_sliders
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import on_changed [as 别名]
def create_sliders(self):
for i, name in enumerate(self.names):
dim = self.def_dim + i * self.del_dim
axes = self.f.add_axes(dim, axisbg = self.axcolor)
slider = Slider(axes, name, 0, 10, valinit=1)
slider.on_changed(self.update)
self.cont_of_slid[name] = (axes, slider)
示例9: cube_show_slider
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import on_changed [as 别名]
def cube_show_slider(cube, axis=2, **kwargs):
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
# check dim
if not cube.ndim == 3:
raise ValueError("cube should be an ndarray with ndim == 3")
# generate figure
fig = plt.figure()
ax = plt.subplot(111)
fig.subplots_adjust(left=0.25, bottom=0.25)
# select first image
s = [slice(0, 1) if i == axis else slice(None) for i in xrange(3)]
im = cube[s].squeeze()
# display image
l = ax.imshow(im, **kwargs)
axcolor = 'lightgoldenrodyellow'
ax = fig.add_axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
slider = Slider(ax, 'Axis %i index' % axis, 0, cube.shape[axis] - 1,
valinit=0, valfmt='%i')
def update(val):
ind = int(slider.val)
s = [slice(ind, ind + 1) if i == axis else slice(None) for i in xrange(3)]
im = cube[s].squeeze()
l.set_data(im, **kwargs)
fig.canvas.draw()
slider.on_changed(update)
plt.show()
示例10: Explorer
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import on_changed [as 别名]
class Explorer(object):
"""A simple interactive slicer that "pans" a series of 2D slices along a
given axis of a 3D volume. Additional kwargs are passed to "imshow"."""
def __init__(self, data, axis=2, **kwargs):
self.data = data
self.axis = axis
self.start, self.stop = 0, data.shape[self.axis] - 1
kwargs['cmap'] = kwargs.get('cmap', 'gray_r')
self.fig, self.ax = plt.subplots()
self.im = self.ax.imshow(self[self.start], **kwargs)
self.ax.axis('off')
self.sliderax = self.fig.add_axes([0.2, 0.02, 0.6, 0.03])
self.slider = Slider(self.sliderax, 'Z-slice', self.start, self.stop,
valinit=self.start, valfmt='%i')
self.slider.on_changed(self.update)
def __getitem__(self, i):
slices = self.data.ndim * [slice(None)]
slices[self.axis] = i
return self.data[slices].swapaxes(0, 1)
def update(self, val):
dat = self[int(val)]
self.im.set(data=dat, clim=[dat.min(), dat.max()])
self.fig.canvas.draw()
def show(self):
plt.show()
示例11: init
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import on_changed [as 别名]
def init():
""" Set up the initial conditions """
# Sets up initial dimensions
M.figure(figsize=(8,8))
density=N.loadtxt(os.path.join(sys.path[0], './densmesh.txt'))
# Real Fourier transform of "density"
density_k = N.fft.rfftn(density*1e3) # 1e3 to enhance contrast
global psi
psi = zeldovich(density_k)
# Zel'dovich displacement field
global scale
global slider_scale
scale = 1.0
slider_scale = 50.0
axcolor = 'lightgoldenrodyellow'
axScale = plt.axes([0.15, 0.1, 0.7, 0.03], axisbg=axcolor)
slider_scale = Slider(axScale, 'Scale', 0.0, 50.0, 1.0)
slider_scale.on_changed(update)
# Attempting to removed axes from the graph
plt.axes([0.15, 0.15, 0.7, 0.7])
plt.xticks([])
plt.yticks([])
return density_k, psi
示例12: interpolation
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import on_changed [as 别名]
def interpolation(threshold, X_Smooth1, Smooth_Y_Coordinates):
Smooth_X_npy = np.asarray(X_Coordinates)
Smooth_Y_npy = np.asarray(Smooth_Y_Coordinates)
f = interp1d(Smooth_X_npy, Smooth_Y_npy, kind = "cubic" )
temp = f(X_Coordinates)
plt.close('all')
fig, ax = plt.subplots(5)
fig.suptitle("Neutron Imaging Curve Smoothing", fontsize="x-large")
ax[0] = plt.subplot2grid((6,7), (0,0), rowspan=2, colspan=3)
ax[0].plot(X_Coordinates, Y_Coordinates)
ax[0].set_title('Original Plot')
ax[1] = plt.subplot2grid((6,7), (3,0), rowspan=2, colspan=3)
ax[1].plot(X_Coordinates, beta_list, 'r.-')
ax[1].axhline(y=threshold, linewidth=1, color='k')
ax[1].set_title('Peak Plot', )
ax[2] = plt.subplot2grid((6,7), (0,4), rowspan=2, colspan=3)
ax[2].plot(X_Coordinates, Smooth_Y_Coordinates)
ax[2].set_title('Smoothed graph')
ax[3] = plt.subplot2grid((6,7), (3,4), rowspan=2, colspan=3)
ax[3].plot(X_Coordinates, f(X_Coordinates))
ax[3].set_title('Interpolated')
ax[4] = plt.subplot2grid((6,7), (5,0), colspan=7)
ax[4].set_position([0.25, 0.1, 0.65, 0.03])
thres = Slider(ax[4], 'Threshold', 0.000, 0.005, valinit = threshold, valfmt='%1.5f')
workbook = xlwt.Workbook(encoding='ascii')
sheet = workbook.add_sheet("Sheet")
sheet.write(0, 0, "(Raw-OB)/OB")
sheet.write(0, 1, "wavelength (angs)")
for i in range(len(X_Coordinates)):
sheet.write(i+1, 0, X_Coordinates[i])
sheet.write(i+1, 1, temp[i])
workbook.save(outputfile)
def update(val):
threshold = thres.val
print ("Threshold value: "), threshold
smoothing_Plot(total_Span, threshold)
fig.canvas.draw_idle()
thres.on_changed(update)
plt.show()
fig2, ax2 = plt.subplots(2)
ax2[0] = plt.subplot2grid((7,2), (0,0), rowspan=3, colspan=2)
ax2[0].plot(X_Coordinates, Y_Coordinates)
ax2[0].set_title('Original Plot')
for i in X_Smooth1:
plt.axvline(x = i, linewidth=1, color='k')
ax2[1] = plt.subplot2grid((7,2), (4,0), rowspan=3, colspan=2)
ax2[1].plot(X_Coordinates, f(X_Coordinates))
ax2[1].set_title('Interpolated')
for i in X_Smooth1:
plt.axvline(x = i, linewidth=1, color='k')
plt.show()
示例13: showimages
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import on_changed [as 别名]
def showimages(img1, img2, pathtosave):
def press(event):
sys.stdout.flush()
if event.key == 'escape':
sys.exit(0)
elif event.key == ' ':
plt.savefig(os.path.join(pathtosave, 'overlay.pdf'), bbox_inches='tight')
print 'saved'
fig, ax = plt.subplots()
fig.canvas.mpl_connect('key_press_event', press)
plt.subplots_adjust(0.15, 0.1, 0.9, 0.98)
im = ax.imshow(img1)
axcolor = 'lightgoldenrodyellow'
BAR_HEIGHT = 0.03
axalpha = plt.axes([0.2, 0.2 * BAR_HEIGHT, 0.7, BAR_HEIGHT], axisbg = axcolor)
# axmax = plt.axes([0.2, BAR_HEIGHT + 0.4 * BAR_HEIGHT, 0.7, BAR_HEIGHT], axisbg = axcolor)
salpha = Slider(axalpha, 'Alpha', 0.0, 1.0, valinit = 1.0)
def update(event):
curralpha = salpha.val
ax.hold(False)
ax.imshow(img1, alpha = curralpha)
ax.hold(True)
ax.imshow(img2, alpha = 1 - curralpha)
plt.draw()
return curralpha
salpha.on_changed(update)
plt.show()
示例14: display
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import on_changed [as 别名]
def display(input, agc=1):
def update(val):
vmax = smax.val
vmin = smin.val
im.set_clim(vmax=vmax, vmin=vmin)
fig.canvas.draw_idle()
fig = pylab.figure()
'''displays a gather using imshow'''
dataset = toolbox.read(input)
vmax = np.amax(dataset['trace'])
vmin = np.amin(dataset['trace'])
if agc:
dataset = toolbox.agc(dataset)
im = pylab.imshow(dataset['trace'].T, aspect='auto', cmap='spectral', vmax =vmax, vmin=vmin)
pylab.colorbar()
axcolor = 'lightgoldenrodyellow'
axmax = pylab.axes([0.08, 0.06, 0.65, 0.01], axisbg=axcolor) #rect = [left, bottom, width, height] in normalized (0, 1) units
smax = Slider(axmax, 'vmax', vmin, vmax, valinit=vmax)
smax.on_changed(update)
axmin = pylab.axes([0.08, 0.03, 0.65, 0.01], axisbg=axcolor) #rect = [left, bottom, width, height] in normalized (0, 1) units
smin = Slider(axmin, 'vmin', vmin, vmax, valinit=vmin)
smin.on_changed(update)
smin.on_changed(update)
pylab.show()
示例15: main
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import on_changed [as 别名]
def main():
points = GeneratePoints(1000, 4.0)
theta = np.pi / 4.0
aspect = 0.5
params = {"theta": theta,
"aspect": aspect,
"original_points": points,
"points": points}
TransformPoints(params)
X0, Y0, Y = LinearRegressionOn2DPoints(params["points"])
points_plot, = plt.plot(X0, Y0, 'o')
line_plot, = plt.plot(X0, Y, 'r')
plt.axis('equal')
# Add UI Text and Sliders
text = plt.text(-4.5, 3.5, "Corr(x,y) %f" % Correlation2DPoints(params["points"]), fontsize=15)
ax_aspect = plt.axes([0.25, 0.1, 0.65, 0.03])
ax_theta = plt.axes([0.25, 0.15, 0.65, 0.03])
aspect_slider = Slider(ax_aspect, 'Aspect', 0.0, 1.0, valinit=aspect)
theta_slider = Slider(ax_theta, 'Theta', -0.5 * np.pi, 0.5 * np.pi, valinit=theta)
aspect_slider.on_changed(updateHandler("aspect", text, points_plot, line_plot, params))
theta_slider.on_changed(updateHandler("theta", text, points_plot, line_plot, params))
plt.show()