本文整理汇总了Python中matplotlib.pyplot.ion函数的典型用法代码示例。如果您正苦于以下问题:Python ion函数的具体用法?Python ion怎么用?Python ion使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ion函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: mask_spectrum
def mask_spectrum(flux_to_fit,interactive=True,mask_lower_limit=None,mask_upper_limit=None):
"""
Interactively and iteratively creates a Boolean mask for a spectrum.
"""
if interactive:
plt.ion()
continue_parameter = 'no'
mask_switch = 'yes'
while mask_switch == 'yes':
pixel_array = np.arange(len(flux_to_fit))
plt.figure()
plt.step(pixel_array,flux_to_fit)
mask_lower_limit_string = raw_input("Enter mask lower limit (in pixels): ")
mask_lower_limit = float(mask_lower_limit_string)
mask_upper_limit_string = raw_input("Enter mask upper limit (in pixels): ")
mask_upper_limit = float(mask_upper_limit_string)
mask = (pixel_array >= mask_lower_limit) & (pixel_array <= mask_upper_limit)
flux_to_fit_masked = np.ma.masked_where(mask,flux_to_fit)
plt.step(pixel_array,flux_to_fit_masked)
continue_parameter = raw_input("Happy? (yes or no]): ")
plt.close()
if continue_parameter == 'yes':
mask_switch = 'no'
else:
pixel_array = np.arange(len(flux_to_fit))
mask = (pixel_array >= mask_lower_limit) & (pixel_array <= mask_upper_limit)
return mask
开发者ID:ernewton,项目名称:lyapy,代码行数:32,代码来源:lyapy.py
示例2: Visualize
def Visualize(self,path=None,filename=None,viz_type='difference'):
if path is None:
path = self.result_path
if filename is None:
filename = '/results'
im = []
if self.n<=1:
fig = mpl.figure()
x = np.linspace(0,1,self.m)
counter = 1
for step in sorted(glob.glob(path+filename+'*.txt')):
tmp = np.loadtxt(step)
if viz_type=='difference':
im.append(mpl.plot(x,(self.exact(x,np.zeros(self.m),counter*self.dt)-tmp),'b-'))
else:
im.append(mpl.plot(x,tmp,'b-'))
counter += 1
ani = animation.ArtistAnimation(fig,im)
mpl.show()
else:
X,Y = np.meshgrid(np.linspace(0,1,self.m),np.linspace(0,1,self.n))
mpl.ion()
fig = mpl.figure()
ax = fig.add_subplot(111,projection='3d')
counter = 1
for step in sorted(glob.glob(path+filename+'*.txt')):
tmp = np.loadtxt(step)
wframe = ax.plot_wireframe(X,Y,(self.exact(X,Y,(counter*self.dt))-tmp))
mpl.draw()
if counter==1:
pass
# ax.set_autoscaley_on(False)
ax.collections.remove(wframe)
counter +=1
开发者ID:fepettersen,项目名称:thesis,代码行数:34,代码来源:new_experiment.py
示例3: task1
def task1():
'''demonstration'''
#TASK 0: Demo
L = 1000 #length, using boundary condition u(x+L)=u(x)
dx = 1.
dt = 0.1
t_max = 100
c = +10
b = (c*dt/dx)**2
#init fields
x = arange(0,L+dx/2.,dx) #[0, .... , L], consider 0 = L
#starting conditions
field_t = exp(-(x-10)**2) #starting condition at t0
field_tmdt = exp(-(x-c*dt-10)**2) #starting condition at t0-dt
eq1 = wave_eq(field_t, field_tmdt, b)
plt.ion()
plot, = plt.plot(x, field_t)
for t in arange(0,t_max,dt):
print 'outer loop, t=',t
eq1.step()
plot.set_ydata(eq1.u)
plt.draw()
开发者ID:RafiKueng,项目名称:Intro-To-Comp.-Physics,代码行数:29,代码来源:waveeq.py
示例4: ToSVGString
def ToSVGString(graph):
"""
Convert as SVG file.
Parameters
----------
graph : object
A Graph or Drawable object.
Returns a SVG representation as string
"""
if sys.version_info[0] >= 3:
output = io.StringIO()
else:
output = io.BytesIO()
# save interactive mode state
ision = plt.isinteractive()
plt.ioff()
view = View(graph)
view.save(output, format='svg')
view.close()
# restore interactive mode state
if ision:
plt.ion()
return output.getvalue()
开发者ID:adutfoy,项目名称:openturns,代码行数:29,代码来源:viewer.py
示例5: plot_goals
def plot_goals(self):
fig = plt.figure()
#fig = plt.gcf()
fig.set_size_inches(14,11,forward=True)
ax = fig.add_subplot(111, projection='3d')
X = self.clustered_goal_data[:,0,3]
Y = self.clustered_goal_data[:,1,3]
Z = self.clustered_goal_data[:,2,3]
#print X,len(X),Y,len(Y),Z,len(Z)
c = 'b'
surf = ax.scatter(X, Y, Z,s=40, c=c,alpha=.5)
#surf = ax.scatter(X, Y,s=40, c=c,alpha=.6)
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.set_zlabel('Z Axis')
ax.set_title(''.join(['Plot of goals from ',self.subject,'. Data: (',str(self.data_start),' - ',str(self.data_finish),')']))
#fig.colorbar(surf, shrink=0.5, aspect=5)
rospack = rospkg.RosPack()
pkg_path = rospack.get_path('hrl_base_selection')
ax.set_xlim(-.2,.2)
ax.set_ylim(-.2,.2)
ax.set_zlim(-.2,.2)
#plt.savefig(''.join([pkg_path, '/images/goals_plot_',self.model,'_',self.subject,'_numbers_',str(self.data_start),'_',str(self.data_finish),'.png']), bbox_inches='tight')
plt.ion()
plt.show()
ut.get_keystroke('Hit a key to proceed next')
开发者ID:gt-ros-pkg,项目名称:hrl-assistive,代码行数:29,代码来源:data_reader_cma.py
示例6: main
def main():
conn = krpc.connect()
vessel = conn.space_center.active_vessel
streams = init_streams(conn,vessel)
print vessel.control.throttle
plt.axis([0, 100, 0, .1])
plt.ion()
plt.show()
t0 = time.time()
timeSeries = []
vessel.control.abort = False
while not vessel.control.abort:
t_now = time.time()-t0
tel = Telemetry(streams,t_now)
timeSeries.append(tel)
timeSeriesRecent = timeSeries[-40:]
plt.cla()
plt.semilogy([tel.t for tel in timeSeriesRecent], [norm(tel.angular_velocity) for tel in timeSeriesRecent])
#plt.semilogy([tel.t for tel in timeSeriesRecent[1:]], [quat_diff_test(t1,t2) for t1,t2 in zip(timeSeriesRecent,timeSeriesRecent[1:])])
#plt.axis([t_now-6, t_now, 0, .1])
plt.draw()
plt.pause(0.0000001)
#time.sleep(0.0001)
with open('log.json','w') as f:
f.write(json.dumps([tel.__dict__ for tel in timeSeries],indent=4))
print 'The End'
开发者ID:janismac,项目名称:SmallProjects,代码行数:31,代码来源:main.py
示例7: __init__
def __init__(self,master,title):
Toplevel.__init__(self,master)
self.master = master
from __init__ import MATPLOTLIB_BACKEND
if MATPLOTLIB_BACKEND != None:
print "manipulator: Setting matplotlib backend to \"TkAgg\"."
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from matplotlib import pyplot
self.title(title)
self.resizable(True,True)
self.fig = pyplot.figure()
pyplot.ion()
self.canvas = FigureCanvasTkAgg(self.fig, master=self)
self.canvas.show()
self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
self.canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)
self.update()
self.experiments = []
开发者ID:elihuihms,项目名称:itcsimlib,代码行数:27,代码来源:manipulator.py
示例8: plot_astcat
def plot_astcat(infile, astcat, rmarker=10., racol=0, deccol=1, hext=0):
# Turn on interactive, so that plot occurs first and then query
plt.ion()
""" Load fits file """
fitsim = im.Image(infile)
hdr = fitsim.hdulist[hext].header
""" Select astrometric objects within the FOV of the detector """
mra,mdec,mx,my,astmask = select_good_ast(astcat,hdr,racol,deccol)
""" Plot the fits file and mark the astrometric objects """
fig = plt.figure(1)
fitsim.display(cmap='heat')
plt.plot(mx,my,'o',ms=rmarker,mec='g',mfc='none',mew=2)
plt.xlim(0,nx)
plt.ylim(0,ny)
plt.draw()
#cid = fig.canvas.mpl_connect('button_press_event', on_click)
"""
Be careful of the +1 offset between SExtractor pixels and python indices
"""
return fitsim
开发者ID:MCTwo,项目名称:CodeCDF,代码行数:27,代码来源:astrom_simple.py
示例9: streamVisionSensor
def streamVisionSensor(visionSensorName,clientID,pause=0.0001):
#Get the handle of the vision sensor
res1,visionSensorHandle=vrep.simxGetObjectHandle(clientID,visionSensorName,vrep.simx_opmode_oneshot_wait)
#Get the image
res2,resolution,image=vrep.simxGetVisionSensorImage(clientID,visionSensorHandle,0,vrep.simx_opmode_streaming)
#Allow the display to be refreshed
plt.ion()
#Initialiazation of the figure
time.sleep(0.5)
res,resolution,image=vrep.simxGetVisionSensorImage(clientID,visionSensorHandle,0,vrep.simx_opmode_buffer)
im = I.new("RGB", (resolution[0], resolution[1]), "white")
#Give a title to the figure
fig = plt.figure(1)
fig.canvas.set_window_title(visionSensorName)
#inverse the picture
plotimg = plt.imshow(im,origin='lower')
#Let some time to Vrep in order to let him send the first image, otherwise the loop will start with an empty image and will crash
time.sleep(1)
while (vrep.simxGetConnectionId(clientID)!=-1):
#Get the image of the vision sensor
res,resolution,image=vrep.simxGetVisionSensorImage(clientID,visionSensorHandle,0,vrep.simx_opmode_buffer)
#Transform the image so it can be displayed using pyplot
image_byte_array = array.array('b',image)
im = I.frombuffer("RGB", (resolution[0],resolution[1]), image_byte_array, "raw", "RGB", 0, 1)
#Update the image
plotimg.set_data(im)
#Refresh the display
plt.draw()
#The mandatory pause ! (or it'll not work)
plt.pause(pause)
print 'End of Simulation'
开发者ID:jeremyfix,项目名称:Project-NAO-Control,代码行数:31,代码来源:vision_sensor.py
示例10: plot_server
def plot_server():
rospy.init_node('plotter')
s = rospy.Service('plot', Plot, handle_plot)
plt.ion()
print "Ready to plot things!", plt.isinteractive()
rospy.spin()
开发者ID:Kenkoko,项目名称:ua-ros-pkg,代码行数:7,代码来源:plotter.py
示例11: __init__
def __init__(self):
self.map = np.loadtxt('wean.dat', delimiter=' ')
self.occ = np.loadtxt('occu.dat', delimiter=' ')
self.unocc = np.loadtxt('unoccu.dat', delimiter=' ')
self.unocc_dict = {tuple(el):1 for el in self.unocc}
self.unocc_corr = np.loadtxt('unoccu_corr.dat', delimiter=' ')
#self.X_t = np.loadtxt('part_init.dat', delimiter=' ')
self.num_p = 1e4
self.sense = np.loadtxt('sense4.dat', delimiter=' ')
self.isodom = np.loadtxt('is_odom4.dat', delimiter=' ')
self.mindist = np.loadtxt('min_d.dat', delimiter=' ')
self.a = np.array([.01,.01,0.01,0.01])
self.c_lim = 10
self.lsr_max = 1000
self.zmax = 0.25
self.zrand = 0.25
self.sig_h = 5
self.zhit = .75
self.q = 1
self.srt = 10
self.end = 170
self.step = 10
plt.imshow(self.map)
plt.ion()
self.scat = plt.quiver(0,0,1,0)
开发者ID:jimitgandhi66,项目名称:My_projects,代码行数:25,代码来源:particle_eitan.py
示例12: follow_channels
def follow_channels(self, channel_list):
"""
Tracks and plots a specified set of channels in real time.
Parameters
----------
channel_list : list
A list of the channels for which data has been requested.
"""
if not pyplot_available:
raise ImportError('pyplot needs to be installed for '
'this functionality.')
plt.clf()
plt.ion()
while True:
self.update_channels(channel_list)
plt.clf()
for channel_name in self.channels:
plt.plot(
self.channels[channel_name].epoch_record,
self.channels[channel_name].val_record,
label=channel_name
)
plt.legend()
plt.ion()
plt.draw()
开发者ID:jewfro-cuban,项目名称:pylearn2,代码行数:26,代码来源:live_monitoring.py
示例13: plot_dataframe
def plot_dataframe(data, error=False, log=False):
'''
plot data frame columns in a long plot
'''
try:
ioff()
fig, ax = plt.subplots(
(len(data.columns)), figsize=(10, 50), sharex=True)
close('all')
ion()
except:
print 'you may be in a non interactive environment'
if not error:
for i, j in zip(data.columns, ax):
if i != 'name':
j.plot(data.index, data[i].values)
j.set_ylabel(str(i))
if error:
for i, j in zip(data.columns, ax):
if i != 'name':
j.errorbar(
data.index, data[i].values, yerr=sqrt(data[i].values))
j.set_ylabel(str(i))
if log:
for i, j in zip(data.columns, ax):
if i != 'name':
j.set_yscale('log')
return fig, ax
开发者ID:giulioungaretti,项目名称:SPring8,代码行数:28,代码来源:Functions.py
示例14: complexHist
def complexHist(array):
"""Display the points (array) on a real and imaginary axis."""
from matplotlib.ticker import NullFormatter
# scale the amplitudes to 0->1024
arrayAmp = np.abs(array)/np.max(np.abs(array))
#arrayAmp = arrayAmp - np.min(arrayAmp)
#arrayAmp = arrayAmp / np.max(arrayAmp)
arrayAmp = 1000.0*arrayAmp/(1000.0*arrayAmp + 1)
array2 = arrayAmp * np.exp(-1.0J * np.angle(array))
x = []
y = []
for i in range(1000):
i = random.randrange(0,array.shape[1])
j = random.randrange(0,array.shape[0])
x.append(array2.real[i,j])
y.append(array2.imag[i,j])
plt.clf()
plt.ion()
rect_scatter = [0.0,0.0,1.0,1.0]
axScatter = plt.axes(rect_scatter)
axScatter.scatter(x,y,s=1,c='grey',marker='o')
axScatter.set_xlim((-1.0,1.0))
axScatter.set_ylim((-1.0,1.0))
#plt.plot(x,y,'k,')
plt.draw()
开发者ID:andyofmelbourne,项目名称:DiffFromCC,代码行数:27,代码来源:MorgansFunctions.py
示例15: plotsolution
def plotsolution(numnodes,coordinates,routes):
plt.ion() # interactive mode on
G=nx.Graph()
nodes = range(1,numnodes+1)
nodedict = {}
for i in nodes:
nodedict[i] = i
nodecolorlist = ['b' for i in nodes]
nodecolorlist[0] = 'r'
# nodes
nx.draw_networkx_nodes(G, coordinates, node_color=nodecolorlist, nodelist=nodes)
# labels
nx.draw_networkx_labels(G,coordinates,font_size=9,font_family='sans-serif',labels = nodedict)
edgelist = defaultdict(list)
colors = ['Navy','PaleVioletRed','Yellow','Darkorange','Chartreuse','CadetBlue','Tomato','Turquoise','Teal','Violet','Silver','LightSeaGreen','DeepPink', 'FireBrick','Blue','Green']
for i in (routes):
edge1 = 1
for j in routes[i][1:]:
edge2 = j
edgelist[i].append((edge1,edge2))
edge1 = edge2
nx.draw_networkx_edges(G,coordinates,edgelist=edgelist[i],
width=6,alpha=0.5,edge_color=colors[i]) #,style='dashed'
plt.savefig("path.png")
plt.show()
开发者ID:adity,项目名称:Vehicle-Routing,代码行数:33,代码来源:plotsolution.py
示例16: plot_tree
def plot_tree(self, root=None, **kwargs):
"""
Draw branches
"""
if root and not self.root:
self.set_root(root)
if self.interactive: pyplot.ioff()
self.yaxis.set_visible(False)
self.create_branch_artists()
self.mark_named()
## self.home()
self.set_name(self.name)
self.adjust_xspine()
if self.interactive: pyplot.ion()
def fmt(x, pos=None):
if x<0: return ""
return ""
#self.yaxis.set_major_formatter(FuncFormatter(fmt))
return self
开发者ID:ChriZiegler,项目名称:ivy,代码行数:25,代码来源:treevis.py
示例17: main
def main():
print """Legend:
Yellow star\t -\t True position of robot
Blue arrows\t -\t Particle cloud
Yellow dots\t -\t Sonar pings
Green boxes\t -\t Obstacles
Red star\t -\t Goal"""
these_parameters = robot.Parameters(vel_max=1
, omega_max=0.1
, displacement_slowdown=5
, avoid_threshold=5
)
true_pose = (80, 90, pi)
this_goal = robot.Goal(location=(20, 20, 0)
, radius=3)
this_map = mapdef()
this_sonar = ogmap.Sonar(num_theta=20
, gauss_var=2
)
this_robot = RobotMapper(these_parameters
, this_sonar
)
this_robot.situate(this_map
, true_pose
, this_goal
)
plt.ion()
this_robot.automate(num_steps=10)
if robot.check_success(this_goal, this_robot):
print "SUCCESS"
else:
print "FAILURE"
开发者ID:MacLeek,项目名称:probrob,代码行数:35,代码来源:robot_mapper.py
示例18: __init__
def __init__(self, model, n_rows, n_cols):
plt.ion()
self.n_rows, self.n_cols = n_rows, n_cols
self.n_comp = model.W.shape[1]
self.sub_rows, self.sub_columns = self.determine_subplots()
self.figure, self.axes = plt.subplots(self.sub_rows, self.sub_columns)
self.figure.suptitle(u"Loss and components -- NMF w/ {0}".format(model.loss_name), size=10)
self.ax_loss = self.axes[0, 0]
self.ax_loss.set_title(u"Loss", size=8)
self.lines, = self.ax_loss.plot([], [], u'o')
self.images = []
for i in range(self.sub_rows * self.sub_columns - 1):
sub_i, sub_j = (1 + i) % self.sub_rows, (1 + i) / self.sub_rows
subplot = self.axes[sub_i, sub_j]
if i < self.n_comp:
self.images.append(subplot.imshow(self.prepare_image(model.W[:, i]), cmap=u"Greys"))
subplot.set_title(u"W[:, %d]" % i, size=8)
subplot.set_axis_off()
else:
# Disable empty subplots
subplot.set_visible(False)
self.ax_loss.set_autoscaley_on(True)
self.ax_loss.set_xlim(0, model.iterations)
self.ax_loss.grid()
self.ax_loss.get_xaxis().set_visible(False)
self.ax_loss.get_yaxis().set_visible(False)
开发者ID:mikimaus78,项目名称:NMFViz,代码行数:26,代码来源:nmf_viz.py
示例19: process_statspecs
def process_statspecs(directive, part=None, designname=None):
"""
Main processor for the staplestatter directive. Responsible for:
1) Initialize figure and optionally axes as specified by the directive instructions.
2) Loop over all statspecs and call process_statspec.
3) Aggregate and return a list of stats/scores.
"""
if part is None:
part = cadnano_api.p()
if designname is None:
designname = os.path.splitext(os.path.basename(part.document().controller().filename()))[0]
print("designname:", designname)
statspecs = directive['statspecs']
figspec = directive.get('figure', dict())
if figspec.get('newfigure', False) or len(pyplot.get_fignums()) < 1:
fig = pyplot.figure(**figspec.get('figure_kwargs', {}))
else:
fig = pyplot.gcf() # Will make a new figure if no figure has been created.
# Here you can add more "figure/axes" specification logic:
adjustfuncs = ('title', 'size_inches', 'dpi')
for cand in adjustfuncs:
if cand in figspec and figspec[cand]:
getattr(fig, 'set_'+cand)(figspec[cand]) # equivalent to fig.title(figspec['title'])
pyplot.ion()
allscores = list()
for _, statspec in enumerate(statspecs):
scores = process_statspec(statspec, part=part, designname=designname, fig=fig)
allscores.append(scores)
if 'printspec' in statspec:
print("Printing highest scores with: statspec['printspec']")
get_highest_scores(scores, **statspec['printspec']) # This logic is subject to change.
return dict(figure=fig, scores=allscores)
开发者ID:scholer,项目名称:staplestatter,代码行数:34,代码来源:staplestatter.py
示例20: doLeutiEvaluation
def doLeutiEvaluation(self, figureId=-1):
if len(self.plotLeutiDistances) > 0:
plt.ion()
plt.show(block=False)
if figureId == -1:
figure()
elif figureId >= 0:
figure(figureId)
spacings = self.plotLeutiDistances
if self.leutiSpacing > 0:
spacings = np.ones(len(self.plotLeutiDistances)) * self.leutiSpacing
leutiOutputPos, leutiOutputAtt, leutiOutputYaw, leutiOutputIncl = self.td.computeLeutiScore(
"pos", "att", "vel", self.tdgt, "pos", "att", self.plotLeutiDistances, spacings, 0.0
)
p = np.arange(len(self.plotLeutiDistances))
if figureId >= -1:
boxplot(leutiOutputPos, positions=p, widths=0.8)
ax = axes()
ax.set_xticklabels(self.plotLeutiDistances)
ax.set_xlabel("Travelled Distance [m]")
ax.set_ylabel("Position Error [m]")
med = np.zeros(len(leutiOutputPos))
for i in range(len(leutiOutputPos)):
med[i] = median(leutiOutputPos[i])
s = np.array(self.plotLeutiDistances) ** 0.5
score = s.dot(med) / s.dot(s)
fit = score * s
if figureId >= -1:
plot(p, fit)
title("Error Plot for Position, score = " + str(score))
return [leutiOutputPos, leutiOutputAtt, leutiOutputYaw, leutiOutputIncl, score]
开发者ID:ygling2008,项目名称:trajectory_toolkit,代码行数:33,代码来源:VIEvaluator.py
注:本文中的matplotlib.pyplot.ion函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论