本文整理汇总了Python中matplotlib.pyplot.ion函数的典型用法代码示例。如果您正苦于以下问题:Python ion函数的具体用法?Python ion怎么用?Python ion使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ion函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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
示例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()
示例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()
示例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')
示例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'
示例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 = []
示例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
示例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'
示例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()
示例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)
示例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()
示例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
示例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()
示例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()