本文整理汇总了Python中matplotlib.widgets.Slider.set_val方法的典型用法代码示例。如果您正苦于以下问题:Python Slider.set_val方法的具体用法?Python Slider.set_val怎么用?Python Slider.set_val使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.widgets.Slider
的用法示例。
在下文中一共展示了Slider.set_val方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ImgView
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import set_val [as 别名]
class ImgView(object):
def __init__(self, img, fig_id=None, imin=None, imax=None):
self.fig = plt.figure(fig_id)
self.ax = self.fig.add_axes([0.1, 0.25, 0.8, 0.7])
self.fig.subplots_adjust(bottom=0.25)
axcolor = 'lightgoldenrodyellow'
self.axlo = self.fig.add_axes([0.15, 0.1, 0.65, 0.03], axisbg=axcolor)
self.axhi = self.fig.add_axes([0.15, 0.15, 0.65, 0.03], axisbg=axcolor)
self.axrefr = self.fig.add_axes([0.15, 0.05, 0.10, 0.03], axisbg=axcolor)
imsort = np.sort(img.flatten())
n = len(imsort)
if imin is None:
imin = imsort[int(n * 0.005)]
if imax is None:
imax = imsort[int(n * 0.995)]
self.slo = Slider(self.axlo, 'Scale min', imin, imax, valinit=imsort[int(n * 0.02)])
self.shi = Slider(self.axhi, 'Scale max', imin, imax, valinit=imsort[int(n * 0.98)])
self.brefr = Button(self.axrefr, 'Refresh')
self.slo.on_changed(self.update_slider)
self.shi.on_changed(self.update_slider)
self.brefr.on_clicked(self.refresh)
self.set_img(img)
def update_slider(self, val):
if self.shi.val <= self.slo.val:
self.shi.set_val(self.slo.val + 1)
self.imgplt.set_clim(self.slo.val, self.shi.val)
self.fig.canvas.draw()
def set_img(self, img=None):
if img is not None:
self.img = img
self.ax.set_xlim(0, self.img.shape[1]-1)
self.ax.set_ylim(0, self.img.shape[0]-1)
self.imgplt = self.ax.imshow(self.img, vmin=self.slo.val, vmax=self.shi.val,
cmap='hot', origin='lower',
interpolation='nearest')
self.imgplt.set_cmap('hot')
divider = make_axes_locatable(self.ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
self.fig.colorbar(self.imgplt, cax=cax)
self.fig.canvas.draw()
def refresh(self, event=None):
self.set_img()
示例2: Index
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import set_val [as 别名]
class Index(object):
def __init__(self, ax_slider, ax_prev, ax_next):
self.ind = 0
self.num = len(wavelengths)
self.bnext = Button(ax_next, 'Next')
self.bnext.on_clicked(self.next)
self.bprev = Button(ax_prev, 'Previous')
self.bprev.on_clicked(self.prev)
self.slider = Slider(ax_slider,
"Energy Resolution: {:.2f} nm".format(wavelengths[0]), 0,
self.num, valinit=0, valfmt='%d')
self.slider.valtext.set_visible(False)
self.slider.label.set_horizontalalignment('center')
self.slider.on_changed(self.update)
position = ax_slider.get_position()
self.slider.label.set_position((0.5, -0.5))
self.slider.valtext.set_position((0.5, -0.5))
def next(self, event):
i = (self.ind + 1) % (self.num + 1)
self.slider.set_val(i)
def prev(self, event):
i = (self.ind - 1) % (self.num + 1)
self.slider.set_val(i)
def update(self, i):
self.ind = int(i)
image.set_data(R[self.ind])
if self.ind != len(wavelengths):
self.slider.label.set_text("Energy Resolution: {:.2f} nm"
.format(wavelengths[self.ind]))
else:
self.slider.label.set_text("Calibrated Pixels")
if self.ind != len(wavelengths):
number = 11
cbar.set_clim(vmin=0, vmax=maximum)
cbar_ticks = np.linspace(0., maximum, num=number, endpoint=True)
else:
number = 2
cbar.set_clim(vmin=0, vmax=1)
cbar_ticks = np.linspace(0., 1, num=number)
cbar.set_ticks(cbar_ticks)
cbar.draw_all()
plt.draw()
示例3: __init__
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import set_val [as 别名]
class GUI:
def __init__(self, coinToss):
self._coinToss = coinToss
maxTosses = coinToss.tosses
axcolor = 'lightgoldenrodyellow'
self.figure = pyplot.figure()
self.mainAxis = pyplot.axes([0.05, 0.2, 0.9, 0.75])
# Slider for number of tosses
tossAxis = pyplot.axes([0.1, 0.05, 0.8, 0.05])
self.tossSlider = Slider(tossAxis, 'Tosses', 0., 1.*maxTosses, valinit=0, valfmt=u'%d')
self.tossSlider.on_changed(lambda x: self.draw(x))
# Reset button
resetAxis = pyplot.axes([0.8, 0.85, 0.1, 0.05])
self.resetButton = Button(resetAxis, 'Re-toss', color=axcolor, hovercolor='0.975')
self.resetButton.on_clicked(self.retoss)
# Key press events
self.figure.canvas.mpl_connect('key_press_event', lambda x: self.press(x))
self._coinToss.doTosses()
def retoss(self, event):
self._coinToss.doTosses()
self.draw(self.tossSlider.val)
def press(self, event):
if event.key == u'left' and self.tossSlider.val > self.tossSlider.valmin:
self.tossSlider.set_val(self.tossSlider.val - 1)
if event.key == u'right' and self.tossSlider.val < self.tossSlider.valmax:
self.tossSlider.set_val(self.tossSlider.val + 1)
if event.key == u'r':
self.retoss(event)
def draw(self, x = 0):
c = self._coinToss
m = max(enumerate(c.posterior[int(x),:]), key=operator.itemgetter(1))
self.mainAxis.clear()
self.mainAxis.plot(c.conditional,c.posterior[int(x),:], lw=2, color='red')
self.mainAxis.vlines(c.conditional[m[0]],0,c.posterior.max())
self.figure.canvas.draw()
示例4: InteractivePlot
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import set_val [as 别名]
class InteractivePlot(object):
def __init__(self, record_wins, sliding_wins, example_labels,
similarities, is_test=None, plot_rc=None):
self.score_plot = ScorePlot(record_wins, sliding_wins, example_labels,
similarities, is_test=is_test,
plot_rc=plot_rc)
self.fig, self.main_ax = self.score_plot.fig, self.score_plot.main_ax
plt.subplots_adjust(bottom=0.2)
self.score_plot.draw()
max_time = self.score_plot.records.absolute_end
ax_s = plt.axes([0.15, 0.1, 0.75, 0.03])
ax_w = plt.axes([0.15, 0.05, 0.75, 0.03])
self.slider_start = Slider(ax_s, 'Start', 0., max_time, valinit=0.)
self.slider_start.on_changed(self.update)
self.slider_width = Slider(ax_w, 'Width', 0., 30., valinit=15.)
self.slider_width.on_changed(self.update)
self.fig.canvas.mpl_connect('key_press_event', self.on_key)
def update(self, val):
self.score_plot.current.absolute_start = self.slider_start.val
width = self.slider_width.val
self.score_plot.current.absolute_end = (
self.score_plot.current.absolute_start + width)
self.score_plot.draw()
def on_key(self, event):
if event.key == 'right':
direction = 1
elif event.key == 'left':
direction = -1
else:
return
self.slider_start.set_val(self.slider_start.val +
direction * .5 * self.slider_width.val)
self.update(None)
示例5: ReadRun
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import set_val [as 别名]
class CompareAnimation:
"""
Launch two parallel animations of runs, so the user can
easily compare the structures. Example:
R1 = ReadRun("fake/path/run_1/")
R2 = ReadRun("fake/path/run_2/")
new_anim=CompareAnimation(R1.S,R2.S)
new_anim.launch()
plt.show()
"""
def __init__(self,snaplist1,snaplist2, symbol="bo", dt = None, markersize=2, **kwargs):
if snaplist1[0].t < snaplist2[0].t:
S = deepcopy(snaplist1[0])
S.t = snaplist2[0].t
snaplist1.reverse()
snaplist1.append(S)
snaplist1.reverse()
if snaplist2[0].t < snaplist1[0].t:
S = deepcopy(snaplist2[0])
S.t = snaplist1[0].t
snaplist2.reverse()
snaplist2.append(S)
snaplist2.reverse()
self.snaplists = [ snaplist1, snaplist2 ]
self.times = [ [s.t for s in snapl] for snapl in self.snaplists ]
#self.nsnap=len(snaplist)
self.n = [ 0, 0 ]
self.t=0.
self.tmax = max(self.snaplists[0][-1].t, self.snaplists[1][-1].t)
self.dt = self.tmax/200. if dt is None else dt
self.delay=1
self.symbol= symbol
self.markersize= markersize
self.pause_switch=True
self.BackgroundColor='white'
self.kwargs=kwargs
def create_frame(self):
self.fig = plt.figure(figsize=(15,10))
print "fig created"
self.ax = []
for i in range(2):
ax = self.fig.add_subplot(121+i, projection='3d',
adjustable='box',
axisbg=self.BackgroundColor)
ax.set_aspect('equal')
plt.tight_layout()
ax.set_xlabel("x (pc)")
ax.set_ylabel ("y (pc)")
ax.set_zlabel ("z (pc)")
self.ax.append(ax)
X,Y,Z = [],[],[]
for snapl in self.snaplists:
X.append( snapl[0].x )
Y.append( snapl[0].y )
Z.append( snapl[0].z )
max_range = np.array([X[0].max()-X[0].min(),
Y[0].max()-Y[0].min(),
Z[0].max()-Z[0].min()]).max() / 3.0
mean_x = X[0].mean(); mean_y = Y[0].mean(); mean_z = Z[0].mean()
self.fig.subplots_adjust(bottom=0.06)#, left=0.1)
self.line, self.canvas = [],[]
for (x,y,z,ax) in zip(X,Y,Z,self.ax):
self.line.append(ax.plot(x, y, z, self.symbol, markersize=self.markersize,
**self.kwargs )[0])
self.canvas.append(ax.figure.canvas)
ax.set_xlim(mean_x - max_range, mean_x + max_range)
ax.set_ylim(mean_y - max_range, mean_y + max_range)
ax.set_zlim(mean_z - max_range, mean_z + max_range)
ax_pauseB=plt.axes([0.04, 0.02, 0.06, 0.025])
self.pauseB=Button(ax_pauseB,'Play')
self.pauseB.on_clicked(self.Pause_button)
slider_ax = plt.axes([0.18, 0.02, 0.73, 0.025])
self.slider_time = Slider(slider_ax,
"Time",
self.snaplists[0][0].t,
self.snaplists[0][-1].t,
valinit = self.snaplists[0][0].t,
color = '#AAAAAA')
self.slider_time.on_changed(self.slider_time_update)
def update_lines(self):
nsnaps = [0,0]
for j,snaplist,time in zip(range(2),self.snaplists,self.times):
ind = np.nonzero(time < self.t)[0]
nsnaps[j] = max(ind) if len(ind)!=0 else 0
for (line,snaplist,n) in zip(self.line, self.snaplists, nsnaps):
line.set_data(snaplist[n].x, snaplist[n].y)
line.set_3d_properties(snaplist[n].z)
for canv in self.canvas:
canv.draw()
def timer_update(self,lines):
if not self.pause_switch:
self.t = self.t+self.dt
if self.t > self.tmax:
self.t = self.t - self.tmax
self.update_lines()
self.slider_time.set_val(self.t)
def Pause_button(self,event):
self.pause_switch = not self.pause_switch
def slider_time_update(self,val):
self.t = val
#.........这里部分代码省略.........
示例6: profileview
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import set_val [as 别名]
def profileview(model):
plt.rc('font', size=8)
fig, axs = plt.subplots(3, sharex=True)
axs[0].set_title('protonic potential (V)')
axs[1].set_title('oxygen molar fraction')
axs[2].set_title('current density (A/m2)')
axs[2].set_xlabel('distance from membrane (um)')
fig.subplots_adjust(right=0.45)
# the mask is assumed to account for boundary values
mask = ~(model.gdl | model.membrane)
# we denote the distance from the membrane wall x
x = model.distance_from_membrane[mask] * 1E6
# the polarization curve is permanent and unique
pcax = fig.add_axes([.5, .2, .4, .7])
pcax.set_title('polarization curve')
pcax.yaxis.tick_right()
pcax.yaxis.set_label_position("right")
pcax.set_xlabel('geometric current density (A/cm**2)')
pcax.set_ylabel('voltage at gdl (V)')
polcurve, = pcax.plot([], [], 'ko-')
def update(V):
# try networks generate l==1
model.resolve(V, 263, flood=False)
i = model.current_history[-1][mask]
I = i.sum() / model.face_area / 1000
reading = (I, V)
insert_point(reading, polcurve)
pcax.relim()
pcax.autoscale_view()
for ax, yh in zip(axs,
[ model.proton_history,
model.oxygen_history,
model.current_history,
]):
y = yh[-1]
update_ax(ax, x, y)
fig.canvas.draw()
slider = Slider(label='V',
ax=fig.add_axes([.5, .05, .4, .03]),
valmin=0,
valmax=1.2,
)
slider.on_changed(update)
# generate an undersampled polcurve
for V in np.linspace(0.05, 1.0, 10):
slider.set_val(V)
slider.set_val(0.65)
# some extra interactivity
fig.canvas.mpl_connect('button_press_event',
lambda event: slider.set_val(event.ydata)
if pcax is event.inaxes else None)
plt.show()
示例7: Hist4D
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import set_val [as 别名]
class Hist4D(object):
def __init__(self, save_only=False):
self.fig=None
self.cubes_info=None
self.slow=None
self.shigh=None
self.colormap=None
self.save_only = save_only
def draw_cubes(self,_axes, vals, edges):
'''
ax=Axes3D handle
edges=matrix L+1xM+1xN+1 result of histogramdd
vals=matrix LxMxN result of histogramdd
colormap=color map to be matched with nonzero vals
'''
edx, edy, edz = np.meshgrid(edges[0], edges[1], edges[2])
edx_rolled = np.roll(edx, -1, axis=1)
edy_rolled = np.roll(edy, -1, axis=0)
edz_rolled = np.roll(edz, -1, axis=2)
edx_rolled = edx_rolled[:-1, :-1, :-1].ravel()
edy_rolled = edy_rolled[:-1, :-1, :-1].ravel()
edz_rolled = edz_rolled[:-1, :-1, :-1].ravel()
edx = edx[:-1, :-1, :-1].ravel()
edy = edy[:-1, :-1, :-1].ravel()
edz = edz[:-1, :-1, :-1].ravel()
vals = vals.ravel()
vdraw_cube = np.vectorize(self.draw_cube, excluded='_axes')
cubes_handles = vdraw_cube(_axes, edx[vals>0],
edx_rolled[vals>0],
edy[vals>0],
edy_rolled[vals>0],
edz[vals > 0],
edz_rolled[vals > 0],
vals[vals>0]/float(np.max(vals)))
cubes_data = [a for a in zip(vals[vals>0],cubes_handles)]
self.cubes_info=dict()
for k, v in cubes_data:
self.cubes_info[k] = self.cubes_info.get(k, ()) + tuple(v) #+(v,)
def set_sliders(self,splot1,splot2):
maxlim=max(self.cubes_info.keys())
axcolor = 'lightgoldenrodyellow'
#low_vis = self.fig.add_axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
#high_vis = self.fig.add_axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
self.slow = Slider(splot1,'low', 0.0, maxlim, valfmt='%0.0f')
self.shigh = Slider(splot2, 'high', 0.0 , maxlim, valfmt='%0.0f')
self.slow.on_changed(self.update)
self.shigh.on_changed(self.update)
self.slow.set_val(0)
self.shigh.set_val(maxlim)
def update(self,val):
visible = [(k,v) for k, v in self.cubes_info.items() if k >
self.slow.val and k<=
self.shigh.val]
invisible = [v for k, v in self.cubes_info.items() if k <=
self.slow.val or k>
self.shigh.val]
for (k,sublist) in visible:
for item in sublist:
print item.set_alpha
item.set_alpha(k)
for item in [item for sublist in invisible for item in sublist]:
item.set_alpha(0)
total=[v for k,v in self.cubes_info.items()]
self.fig.canvas.draw_idle()
def draw_cube(self,_axes, x1_coord, x2_coord,
y1_coord, y2_coord,
z1_coord, z2_coord,
color_ind):
'''
draw a cube given cube limits and color
'''
_x_coord, _y_coord, _z_coord = np.meshgrid([x1_coord, x2_coord],
[y1_coord, y2_coord],
[z1_coord, z2_coord])
tmp1 = np.concatenate((_x_coord.ravel()[None, :], _y_coord.ravel()[
None, :], _z_coord.ravel()[None, :]), axis=0)
tmp2 = tmp1.copy()
tmp2[:, [0, 1]], tmp2[:, [6, 7]] = tmp2[
:, [6, 7]].copy(), tmp2[:, [0, 1]].copy()
tmp3 = tmp2.copy()
tmp3[:, [0, 2]], tmp3[:, [5, 7]] = tmp3[
:, [5, 7]].copy(), tmp3[:, [0, 2]].copy()
points = np.concatenate((tmp1, tmp2, tmp3), axis=1)
points = points.T.reshape(6, 4, 3)
'''
collection = Poly3DCollection(points,
facecolors=self.colormap(float(color_ind)),
linewidths=0
)
_axes.add_collection3d(collection)
return collection
'''
surf = []
for count in range(6):
surf.append(_axes.plot_surface(points[count, :, 0].reshape(2, 2),
points[count, :, 1].reshape(2, 2),
points[count, :, 2].reshape(2, 2),
#.........这里部分代码省略.........
示例8: Parameters
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import set_val [as 别名]
#.........这里部分代码省略.........
self.update_display()
# toggle eye tracking method
elif event.key == 'm':
if self.params['method'] == 'threshold':
self.params['method'] = 'convolve'
print(" Method: convolve")
elif self.params['method'] == 'convolve':
self.params['method'] = 'threshold'
print(" Method: threshold")
self.get_eye_patches() # update eye patches
self.update_display()
# toggle ellipse fitting method
elif event.key == 'f':
if self.params['shape'] == 'lse_ellipse':
self.params['shape'] = 'min_enclosing'
elif self.params['shape'] == 'min_enclosing':
self.params['shape'] = 'lse_ellipse'
print(" Shape fit: " + self.params['shape'])
self.get_eye_patches()
self.update_display()
# toggle Hough transform ellipse fitting
elif event.key == 'h':
self.params['ht_fit'] = not self.params['ht_fit']
print(" Hough transform: " + str(self.params['ht_fit']))
self.get_eye_patches() # update eye patches
self.update_display()
# change frame
elif event.key == 'right': # move forward one frame
if np.round(self.f_slider.val) < self.nframes-1:
self.f_slider.set_val(self.f_slider.val+1)
elif event.key == 'left': # move back one frame
if np.round(self.f_slider.val) > 0:
self.f_slider.set_val(self.f_slider.val-1)
# continue, close, or re-set
elif event.key == 'c': # confirm parameters and close figure
print("Eye tracking parameters confirmed")
self.done = True
plt.close('all')
elif event.key == 'escape': # quit eye tracking
print("Eye tracking aborted")
plt.close('all')
sys.exit()
elif event.key == 'r': # re-set & return to annotation
print("Parameters re-set")
plt.close('all')
def update_frame(self, val):
"""updates frame and plots based on frame slider value"""
# update frame index
self.frame_ind = np.int(np.round(self.f_slider.val))
# update displays
self.frame = self.stack[self.frame_ind,:,:] # raw frame
self.update_pframes()
self.update_hist()
# diffs plot
self.f_dot.remove()
self.f_dot = self.ax_diffs.scatter(self.frame_ind, self.diffs[self.frame_ind],
s=4, color=[1,0,1])
self.get_eye_patches()
示例9: viscm_editor
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import set_val [as 别名]
#.........这里部分代码省略.........
if xp is None:
xp = [-2.0591553836234482, 59.377014829142524, 43.552546744036135, 4.7670857511283202, -9.5059638942617539]
if yp is None:
yp = [-25.664893617021221, -21.941489361702082, 38.874113475177353, 20.567375886524871, 32.047872340425585]
self.bezier_model = BezierModel(xp, yp)
self.cmap_model = BezierCMapModel(
self.bezier_model, self.jp_min_slider.val, self.jp_max_slider.val, uniform_space
)
self.highlight_point_model = HighlightPointModel(self.cmap_model, 0.5)
self.bezier_builder = BezierBuilder(axes["bezier"], self.bezier_model)
self.bezier_gamut_viewer = GamutViewer2D(axes["bezier"], self.highlight_point_model, uniform_space)
tmp = HighlightPoint2DView(axes["bezier"], self.highlight_point_model)
self.bezier_highlight_point_view = tmp
# draw_pure_hue_angles(axes['bezier'])
axes["bezier"].set_xlim(-100, 100)
axes["bezier"].set_ylim(-100, 100)
self.cmap_view = CMapView(axes["cm"], self.cmap_model)
self.cmap_highlighter = HighlightPointBuilder(axes["cm"], self.highlight_point_model)
print("Click sliders at bottom to change min/max lightness")
print("Click on colorbar to adjust gamut view")
print("Click-drag to move control points, ")
print(" shift-click to add, control-click to delete")
def plot_3d_gamut(self, event):
fig, ax = plt.subplots(subplot_kw=dict(projection="3d"))
self.wireframe_view = WireframeView(ax, self.cmap_model, self.highlight_point_model, self._uniform_space)
plt.show()
def save_colormap(self, event):
import textwrap
template = textwrap.dedent(
"""
from matplotlib.colors import ListedColormap
from numpy import nan, inf
# Used to reconstruct the colormap in viscm
parameters = {{'xp': {xp},
'yp': {yp},
'min_Jp': {min_Jp},
'max_Jp': {max_Jp}}}
cm_data = {array_list}
test_cm = ListedColormap(cm_data, name=__file__)
if __name__ == "__main__":
import matplotlib.pyplot as plt
import numpy as np
try:
from viscm import viscm
viscm(test_cm)
except ImportError:
print("viscm not found, falling back on simple display")
plt.imshow(np.linspace(0, 100, 256)[None, :], aspect='auto',
cmap=test_cm)
plt.show()
"""
)
rgb, _ = self.cmap_model.get_sRGB(num=256)
with open("/tmp/new_cm.py", "w") as f:
array_list = np.array2string(rgb, max_line_width=78, prefix="cm_data = ", separator=",")
xp, yp = self.cmap_model.bezier_model.get_control_points()
data = dict(
array_list=array_list, xp=xp, yp=yp, min_Jp=self.cmap_model.min_Jp, max_Jp=self.cmap_model.max_Jp
)
f.write(template.format(**data))
print("*" * 50)
print("Saved colormap to /tmp/new_cm.py")
print("*" * 50)
def show_viscm(self, event):
cm = LinearSegmentedColormap.from_list("test_cm", self.cmap_model.get_sRGB(num=256)[0])
self.prop_windows.append(viscm(cm, name="test_cm"))
plt.show()
def _jp_update(self, val):
jp_min = self.jp_min_slider.val
jp_max = self.jp_max_slider.val
smallest, largest = min(jp_min, jp_max), max(jp_min, jp_max)
if (jp_min > smallest) or (jp_max < largest):
self.jp_min_slider.set_val(smallest)
self.jp_max_slider.set_val(largest)
self.cmap_model.set_Jp_minmax(smallest, largest)
示例10: view_patches_bar
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import set_val [as 别名]
#.........这里部分代码省略.........
frame dimensions
YrA: np.ndarray
ROI filtered residual as it is given from update_temporal_components
If not given, then it is computed (K x T)
img: np.ndarray
background image for contour plotting. Default is the image of all spatial components (d1 x d2)
"""
plt.ion()
nr, T = C.shape
A2 = A.copy()
A2.data **= 2
nA2 = np.sqrt(np.array(A2.sum(axis=0))).squeeze()
#A = A*spdiags(1/nA2,0,nr,nr)
#C = spdiags(nA2,0,nr,nr)*C
b = np.squeeze(b)
f = np.squeeze(f)
if YrA is None:
Y_r = np.array(A.T * np.matrix(Yr) - (A.T * np.matrix(b[:, np.newaxis])) * np.matrix(
f[np.newaxis]) - (A.T.dot(A)) * np.matrix(C) + C)
else:
Y_r = YrA + C
A = A * spdiags(1 / nA2, 0, nr, nr)
A = A.todense()
imgs = np.reshape(np.array(A), (d1, d2, nr), order='F')
if img is None:
img = np.mean(imgs[:, :, :-1], axis=-1)
bkgrnd = np.reshape(b, (d1, d2), order='F')
fig = plt.figure(figsize=(10, 10))
axcomp = plt.axes([0.05, 0.05, 0.9, 0.03])
ax1 = plt.axes([0.05, 0.55, 0.4, 0.4])
# ax1.axis('off')
ax3 = plt.axes([0.55, 0.55, 0.4, 0.4])
# ax1.axis('off')
ax2 = plt.axes([0.05, 0.1, 0.9, 0.4])
# axcolor = 'lightgoldenrodyellow'
# axcomp = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
s_comp = Slider(axcomp, 'Component', 0, nr, valinit=0)
vmax = np.percentile(img, 98)
def update(val):
i = np.int(np.round(s_comp.val))
print 'Component:' + str(i)
if i < nr:
ax1.cla()
imgtmp = imgs[:, :, i]
ax1.imshow(imgtmp, interpolation='None', cmap=plt.cm.gray)
ax1.set_title('Spatial component ' + str(i + 1))
ax1.axis('off')
ax2.cla()
ax2.plot(np.arange(T), np.squeeze(np.array(Y_r[i, :])), 'c', linewidth=3)
ax2.plot(np.arange(T), np.squeeze(np.array(C[i, :])), 'r', linewidth=2)
ax2.set_title('Temporal component ' + str(i + 1))
ax2.legend(labels=['Filtered raw data', 'Inferred trace'])
ax3.cla()
ax3.imshow(img, interpolation='None', cmap=plt.cm.gray, vmax=vmax)
imgtmp2 = imgtmp.copy()
imgtmp2[imgtmp2 == 0] = np.nan
ax3.imshow(imgtmp2, interpolation='None', alpha=0.5, cmap=plt.cm.hot)
else:
ax1.cla()
ax1.imshow(bkgrnd, interpolation='None')
ax1.set_title('Spatial background background')
ax2.cla()
ax2.plot(np.arange(T), np.squeeze(np.array(f)))
ax2.set_title('Temporal background')
def arrow_key_image_control(event):
if event.key == 'left':
new_val = np.round(s_comp.val - 1)
if new_val < 0:
new_val = 0
s_comp.set_val(new_val)
elif event.key == 'right':
new_val = np.round(s_comp.val + 1)
if new_val > nr:
new_val = nr
s_comp.set_val(new_val)
else:
pass
s_comp.on_changed(update)
s_comp.set_val(0)
id2 = fig.canvas.mpl_connect('key_release_event', arrow_key_image_control)
plt.show()
示例11: BasicDendrogramViewer
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import set_val [as 别名]
#.........这里部分代码省略.........
indices = (self.slice, iy, ix)
# Select the structure
structure = self.dendrogram.structure_at(indices)
self.hub.select(input_key, structure)
# Re-draw
event.canvas.draw()
def line_picker(self, event):
# Only do this if no tools are currently selected
if event.canvas.toolbar.mode != '':
return
if event.mouseevent.button not in self.selected_label:
return
input_key = event.mouseevent.button
# event.ind gives the indices of the paths that have been selected
# Find levels of selected paths
peaks = [event.artist.structures[i].get_peak(subtree=True)[1] for i in event.ind]
# Find position of minimum level (may be duplicates, let Numpy decide)
ind = event.ind[np.argmax(peaks)]
# Extract structure
structure = event.artist.structures[ind]
# If 3-d, select the slice
if self.slice_slider is not None:
peak_index = structure.get_peak(subtree=True)
self.slice_slider.set_val(peak_index[0][0])
# Select the structure
self.hub.select(input_key, structure)
# Re-draw
event.canvas.draw()
def _update_lines(self, selection_id):
structures = self.hub.selections[selection_id]
select_subtree = self.hub.select_subtree[selection_id]
structure = structures[0]
# Remove previously selected collection
if selection_id in self.selected_lines:
self.ax_dendrogram.collections.remove(self.selected_lines[selection_id])
del self.selected_lines[selection_id]
if structure is None:
self.selected_label[selection_id].set_text("No structure selected")
self.remove_contour(selection_id)
self.fig.canvas.draw()
return
self.remove_all_contours()
if len(structures) <= 1:
label_text = "Selected structure: {0}".format(structure.idx)
elif len(structures) <=3:
label_text = "Selected structures: {0}".format(', '.join([str(structure.idx) for structure in structures]))
else:
label_text = "Selected structures: {0}...".format(', '.join([str(structure.idx) for structure in structures[:3]]))
示例12: Slider
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import set_val [as 别名]
RmaxV = Slider(Rmax, 'Rmax', 1, 254, valinit=rgbinit[0])
RminV = Slider(Rmin, 'Rmin', 1, 254, valinit=rgbinit[1])
GmaxV = Slider(Gmax, 'Gmax', 1, 254, valinit=rgbinit[2])
GminV = Slider(Gmin, 'Gmin', 1, 254, valinit=rgbinit[3])
BmaxV = Slider(Bmax, 'Bmax', 1, 254, valinit=rgbinit[4])
BminV = Slider(Bmin, 'Bmin', 1, 254, valinit=rgbinit[5])
RmaxV.on_changed(sliceupdateRmax)
RminV.on_changed(sliceupdateRmin)
GmaxV.on_changed(sliceupdateGmax)
GminV.on_changed(sliceupdateGmin)
BmaxV.on_changed(sliceupdateBmax)
BminV.on_changed(sliceupdateBmin)
ff=1
else:
RmaxV.set_val(rgbinit[0])
RminV.set_val(rgbinit[1])
GmaxV.set_val(rgbinit[2])
GminV.set_val(rgbinit[3])
BmaxV.set_val(rgbinit[4])
BminV.set_val(rgbinit[5])
file = open("rgb.txt", "w")
file.write(str(rgbinit))
file.close()
print rgbinit
plt.pause(0.001)
plt.show(block=False)
#print samp.val,sfreq.val
示例13: view_patches_bar
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import set_val [as 别名]
#.........这里部分代码省略.........
temporal background (vector of length T)
d1,d2: np.ndarray
frame dimensions
YrA: np.ndarray
ROI filtered residual as it is given from update_temporal_components
If not given, then it is computed (K x T)
img: np.ndarray
background image for contour plotting. Default is the image of all spatial components (d1 x d2)
"""
pl.ion()
if 'csc_matrix' not in str(type(A)):
A = csc_matrix(A)
if 'array' not in str(type(b)):
b = b.toarray()
nr, T = C.shape
nb = f.shape[0]
nA2 = np.sqrt(np.array(A.power(2).sum(axis=0))).squeeze()
if YrA is None:
Y_r = spdiags(old_div(1, nA2), 0, nr, nr) * (A.T.dot(Yr) -
(A.T.dot(b)).dot(f) - (A.T.dot(A)).dot(C)) + C
else:
Y_r = YrA + C
if img is None:
img = np.reshape(np.array(A.mean(axis=1)), (d1, d2), order='F')
fig = pl.figure(figsize=(10, 10))
axcomp = pl.axes([0.05, 0.05, 0.9, 0.03])
ax1 = pl.axes([0.05, 0.55, 0.4, 0.4])
ax3 = pl.axes([0.55, 0.55, 0.4, 0.4])
ax2 = pl.axes([0.05, 0.1, 0.9, 0.4])
s_comp = Slider(axcomp, 'Component', 0, nr + nb - 1, valinit=0)
vmax = np.percentile(img, 95)
def update(val):
i = np.int(np.round(s_comp.val))
print(('Component:' + str(i)))
if i < nr:
ax1.cla()
imgtmp = np.reshape(A[:, i].toarray(), (d1, d2), order='F')
ax1.imshow(imgtmp, interpolation='None', cmap=pl.cm.gray, vmax=np.max(imgtmp)*0.5)
ax1.set_title('Spatial component ' + str(i + 1))
ax1.axis('off')
ax2.cla()
ax2.plot(np.arange(T), Y_r[i], 'c', linewidth=3)
ax2.plot(np.arange(T), C[i], 'r', linewidth=2)
ax2.set_title('Temporal component ' + str(i + 1))
ax2.legend(labels=['Filtered raw data', 'Inferred trace'])
ax3.cla()
ax3.imshow(img, interpolation='None', cmap=pl.cm.gray, vmax=vmax)
imgtmp2 = imgtmp.copy()
imgtmp2[imgtmp2 == 0] = np.nan
ax3.imshow(imgtmp2, interpolation='None',
alpha=0.5, cmap=pl.cm.hot)
ax3.axis('off')
else:
ax1.cla()
bkgrnd = np.reshape(b[:, i - nr], (d1, d2), order='F')
ax1.imshow(bkgrnd, interpolation='None')
ax1.set_title('Spatial background ' + str(i + 1 - nr))
ax1.axis('off')
ax2.cla()
ax2.plot(np.arange(T), np.squeeze(np.array(f[i - nr, :])))
ax2.set_title('Temporal background ' + str(i + 1 - nr))
def arrow_key_image_control(event):
if event.key == 'left':
new_val = np.round(s_comp.val - 1)
if new_val < 0:
new_val = 0
s_comp.set_val(new_val)
elif event.key == 'right':
new_val = np.round(s_comp.val + 1)
if new_val > nr + nb:
new_val = nr + nb
s_comp.set_val(new_val)
else:
pass
s_comp.on_changed(update)
s_comp.set_val(0)
fig.canvas.mpl_connect('key_release_event', arrow_key_image_control)
pl.show()
示例14: plot_biplot
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import set_val [as 别名]
def plot_biplot(x, information, rhomin, rhomax):
## Formatting input
if callable(information):
n = 100
width = 20
# x = np.linspace(0, 1, n)
y = information(x)
else:
n = len(information)
width = int(n/5)
# x = np.arange(n)
y = information
array = np.repeat(y, width).reshape((len(y), width))
# Font type for all plots
rc('font',**{'family':'serif','serif':['Palation'], 'size':24, 'weight':'bold'})
rc('text', usetex=True)
mpl.rcParams['text.latex.preamble']=[r"\usepackage{amsmath}"]
# Creating plot
# fig = plt.figure(figsize=(18,10))
fig1, ax1 = plt.subplots(figsize=(2, 10))
# gs = gridspec.GridSpec(8, 4)
# ax1 = fig.add_subplot(gs[1:, 0])
# ax1 = fig.add_axes([0.05, 0.05, 0.05, 0.8])
# ax2 = fig.add_axes([0.2, 0.05, 0.75, 0.8])
#ax1 = fig.add_subplot(111)
#ax2 = fig.add_subplot(111)
colormap_chosen = mpl.colors.LinearSegmentedColormap.from_list('mycolors',['red','yellow']) #['yellow','yellow','#F7F8E0','yellow','red','#8A0808']
colormap_chosen = 'OrRd_r'#'gist_heat' #hot
cm = plt.get_cmap(colormap_chosen)
cNorm = colors.Normalize(vmin=rhomin, vmax=rhomax)
ax1.imshow(array, cmap=cm, norm=cNorm)
# ax2 = fig.add_subplot(gs[1:, 1:5])
fig1 = plt.gcf()
fig2, ax2 = plt.subplots(figsize=(10, 8))
x_0, rho_0 = evolver.rho_aprox(0.5)
ax2.plot(rho_0, x_0, linewidth=5, linestyle="-", c="grey", zorder=1, alpha=0.3)
ax2.plot(information, x, linewidth=8, linestyle="-", c="black", zorder=1)
ax2.plot(information, x, linewidth=5, linestyle="-", c="white", zorder=1)
##### TRYING TO MAKE LINES WITH COLOR GRADIENTS
# ax2.scatter(information,x,c=range(len(information)), marker='_', s=30)
# path = mpath.Path(np.column_stack([y, x]))
# verts = path.interpolated(steps=3).vertices
# xcolor, ycolor = verts[:, 0], verts[:, 1]
colorline(ax2, y, x, z=rhomin*(rhomin-y)/(rhomin-rhomax) + rhomax*(rhomax-y)/(rhomax-rhomin), cmap=cm, norm=cNorm, linewidth=5, alpha=1)
# gs.update(wspace=0.5, hspace=0.5)
# Stetic tuning of plot
ax2.set_ylim([min(x),max(x)])
ax2.set_xlim([990,1093])
ax2.set_xlabel(r"\textbf{Density / g L}$\boldsymbol{^{-1}}$")
ax2.set_ylabel(r"\textbf{Height / mm}",rotation=270, labelpad= 10)#fontsize=20,
ax2.yaxis.set_label_position("right")
ax2.tick_params(labeltop=True)
ax2.grid(True)
plt.setp(ax2.get_xticklabels(), fontsize=18)
# Final Configuration
plt.setp(ax1.get_xticklabels(), visible=False)
plt.setp(ax1.get_yticklabels(), visible=False)
plt.setp(ax2.get_yticklabels(), visible=False)
ax1.get_xaxis().set_visible(False)
for axis in ['top','bottom','left','right']:
ax1.spines[axis].set_linewidth(5)
# fig = plt.gcf()
fig2 = plt.gcf()
fig3, axslider = plt.subplots(figsize=(10, 1))
#axslider = plt.axes([0.3, 0.94, 0.5, 0.04], axisbg=None)
# axslider = fig.add_subplot(gs[0,1:3])
samp = Slider(axslider, 'Time (min)', 0., maxtime, valinit=0,color='grey',alpha=0.3,valfmt='%i'.ljust(5))
samp.set_val(float(time)/60.)
fig3 = plt.gcf()
return fig1, fig2, fig3
示例15: SelectFromCollection
# 需要导入模块: from matplotlib.widgets import Slider [as 别名]
# 或者: from matplotlib.widgets.Slider import set_val [as 别名]
#.........这里部分代码省略.........
valinit = len(np.nonzero(self.mmc.classvec_ws)[0]) / len(mmc.working_set))
def sliderupdate(val):
val = int(val * len(mmc.working_set))
nonzeroc = len(np.nonzero(self.mmc.classvec_ws)[0])
if val > nonzeroc:
claims = val - nonzeroc
newclazz = 1
elif val < nonzeroc:
claims = nonzeroc - val
newclazz = 0
else: return
print('Claimed', claims, 'points for class', newclazz)
self.claims = claims
mmc.claim_n_points(claims, newclazz)
self.redrawall()
self.in_selection_slider.on_changed(sliderupdate)
#Initialize the display for the RLS objective funtion
self.objfun_display_axis = fig.add_axes([0.1, 0.96, 0.8, 0.02])
self.objfun_display_axis.imshow(mmc.compute_steepness_vector()[np.newaxis, :], cmap = plt.get_cmap("Oranges"))
self.objfun_display_axis.set_aspect('auto')
self.objfun_display_axis.set_yticklabels([])
self.objfun_display_axis.yaxis.set_tick_params(size = 0)
def onselect(self, verts):
#Select a new working set
self.path = Path(verts)
self.selectedset = set(np.nonzero(self.path.contains_points(self.collection))[0])
print('Selected ' + str(len(self.selectedset)) + ' points')
newws = list(self.selectedset - self.lockedset)
self.mmc.new_working_set(newws)
self.redrawall()
def onkeypressed(self, event):
print('You pressed', event.key)
if event.key == '1':
print('Assigned all selected points to class 1')
newclazz = 1
mmc.claim_all_points_in_working_set(newclazz)
if event.key == '0':
print('Assigned all selected points to class 0')
newclazz = 0
mmc.claim_all_points_in_working_set(newclazz)
if event.key == 'a':
print('Selected all points')
newws = list(set(range(len(self.collection))) - self.lockedset)
self.mmc.new_working_set(newws)
self.lasso.line.set_visible(False)
if event.key == 'c':
changecount = mmc.cyclic_descent_in_working_set()
print('Performed ', changecount, 'cyclic descent steps')
if event.key == 'l':
print('Locked the class labels of selected points')
self.lockedset = self.lockedset | self.selectedset
newws = list(self.selectedset - self.lockedset)
self.mmc.new_working_set(newws)
if event.key == 'u':
print('Unlocked the selected points')
self.lockedset = self.lockedset - self.selectedset
newws = list(self.selectedset - self.lockedset)
self.mmc.new_working_set(newws)
if event.key == 'p':
print('Compute predictions and AUC on data')
preds = self.mmc.predict(Xmat)
print(auc(mmc.Y[:, 0], preds[:, 0]))
self.redrawall()
def redrawall(self):
#Color all class one labeled pixels red
oneclazz = np.nonzero(self.mmc.classvec)[0]
col_row = self.collection[oneclazz]
rowcs, colcs = col_row[:, 1], col_row[:, 0]
red = np.array([255, 0, 0])
for i in range(-self.windowsize, self.windowsize + 1):
for j in range(-self.windowsize, self.windowsize + 1):
self.img[rowcs+i, colcs+j, :] = red
#Return the original color of the class zero labeled pixels
zeroclazz = np.nonzero(self.mmc.classvec - 1)[0]
col_row = self.collection[zeroclazz]
rowcs, colcs = col_row[:, 1], col_row[:, 0]
for i in range(-self.windowsize, self.windowsize + 1):
for j in range(-self.windowsize, self.windowsize + 1):
self.img[rowcs+i, colcs+j, :] = self.img_orig[rowcs+i, colcs+j, :]
self.imdata.set_data(self.img)
#Update the slider position according to labeling of the current working set
sliderval = 0
if len(mmc.working_set) > 0:
sliderval = len(np.nonzero(self.mmc.classvec_ws)[0]) / len(mmc.working_set)
self.in_selection_slider.set_val(sliderval)
#Update the RLS objective function display
self.objfun_display_axis.imshow(mmc.compute_steepness_vector()[np.newaxis, :], cmap=plt.get_cmap("Oranges"))
self.objfun_display_axis.set_aspect('auto')
#Final stuff
self.lasso.canvas.draw_idle()
plt.draw()
print_instructions()