def zoom_selected(self, event): """zoom currently selected area""" current_area = self.get_current_area(event) pylab.get_current_fig_manager().toolbar.push_current() pylab.gca().set_xlim(current_area[0][0], current_area[1][0]) pylab.gca().set_ylim(current_area[0][1], current_area[1][1]) pylab.get_current_fig_manager().toolbar.draw()
def onpick(self,event): if event.mouseevent.button==3 and not self.shift_is_held and pyl.get_current_fig_manager().toolbar._active==None: for ii in range(len(self.patchList)): if event.artist==self.patchList[ii]: k=ii break self.remPatch(k) #self.patchList[k].remove() pyl.draw() elif event.mouseevent.button==1 and self.shift_is_held and pyl.get_current_fig_manager().toolbar._active==None: for ii in range(len(self.patchList)): if event.artist==self.patchList[ii]: k=ii break self.press=(self.patchList[k].center[0],self.patchList[k].center[1],event.mouseevent.xdata,event.mouseevent.ydata,k,self.patchList[k].height,1) elif event.mouseevent.button==1 and self.ctrl_is_held and pyl.get_current_fig_manager().toolbar._active==None: for ii in range(len(self.patchList)): if event.artist==self.patchList[ii]: k=ii break self.press=(self.patchList[k].center[0],self.patchList[k].center[1],event.mouseevent.xdata,event.mouseevent.ydata,k,self.patchList[k].height,3)
def plot_heatmap(df, replica=None, degree=False): """ This method plots a heatmap of fitness values throughout the genome. unfix BUG of x labels which are not showing well. until fix - use the manual option of defining x limits in the IPython window. :param df: data frame with fitness results :param replica: optional - biological repeat. default None :param degree: optional. default is False. if True pivot the heatmap according degree. used in MS2 :return: a heatmap of fitness values """ if replica != None: df = df[df.Replica == replica] if degree: heat = df.pivot("Degree", "Pos", "Fitness_median") else: heat = df.pivot("Pos", "Fitness_median") sns.heatmap(heat, cmap="RdBu") if degree: plt.title("Fitness values by degree") else: plt.title("Fitness values throughout the genome") pylab.get_current_fig_manager().window.showMaximized() plt.show()
def print_pop(self, last=False, color=None): self.nuance = 12 self.cp = [ "%f" % (.8 - .8 * float(f) / self.nuance) for f in range(self.nuance) ] self.col = 0 if self.graph != []: import pylab if last: pylab.ioff() dr = pylab.show else: pylab.ion() dr = pylab.draw for i in range(len(self.graph)): m1, m2 = self.graph[i].split(":") x = [x_.objectives[m1] for x_ in self.pop_list] y = [x_.objectives[m2] for x_ in self.pop_list] ax = pylab.subplot(1, len(self.graph), i + 1) ax.set_yscale('log') ax.set_xscale('log') if color == None: pylab.plot(x, y, ".") #,color=self.cp[self.col%len(self.cp)]) else: pylab.plot( x, y, ".", color=color) #,color=self.cp[self.col%len(self.cp)]) self.col = self.col + 1 % self.nuance pylab.get_current_fig_manager().canvas.flush_events() dr()
def order_matching(str='', startx=10, starty=10, incx=400, incy=0, wsize=None): """ reorder all pylab windows in am array with str in the title, whether they flash or raise depends on window manager and settings default (no arg or '') is to use all open windows Note that figure(num='myname') is a legal way to name a fig""" labs = [lab for lab in get_fig_nums_labs(str) if str in lab] if len(labs) == 0: print('No figures matching "{s}" found'.format(s=str)) labs = np.sort(labs) x = startx y = starty mgr = pl.get_current_fig_manager() screen_y = mgr.window.winfo_screenheight() screen_x = mgr.window.winfo_screenwidth() for (i, lab) in enumerate(labs): if lab.isdigit(): # must use int otherwise a new figure is opened fig = pl.figure(int(lab)) else: fig = pl.figure(lab) geom = '' mgr = pl.get_current_fig_manager() w, h = mgr.canvas.get_width_height() if wsize is not None: w = wsize[0] h = wsize[1] geom += '{w}x{h}'.format(w=w, h=h) if w + x > screen_x: x = startx y += h geom += '+{x}+{y}'.format(x=x, y=y) mgr.window.wm_geometry(geom) x += incx y += incy mgr.window.tkraise()
def test_find_daily_clusters(plot=True): df_dict = dict() df_dict['x'] = [ 1, 2, 2, 3, 10, 10, 10, 10, 10, 10, .5, .8, 2.5, 2.7, 10, 11, 12, 5, 5.5, 5, 5.5 ] df_dict['y'] = [ 1, .5, 1.5, 1.2, 1, 2, 3, 5, 6, 7, 2, 1.2, .5, .6, 4, 4, 4, 3, 3, 3.3, 3.3 ] df_dict['dayofyear'] = [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3 ] df = pd.DataFrame(df_dict) print "DataFrame:" print df if plot: plt.scatter(df.x, df.y, c=df.dayofyear) get_current_fig_manager().window.raise_() plt.show() plt.close() kd = KDTree(np.column_stack((df.x, df.y))) neighbors_list = kd.query_ball_tree(kd, 1.05) neighbors_dict = dict() for i, arr in enumerate(neighbors_list): neighbors_dict[df.iloc[i].name] = set() for j in arr: neighbors_dict[df.iloc[i].name].add(df.iloc[j].name) # Get initial clusters on day 1 day1fires = df[df.dayofyear == 1] clust2nodes, nodes2clust, merge_dict = find_daily_clusters( day1fires, neighbors_dict) print "clust2nodes, day 1:" + str(clust2nodes) print "node2clusts, day 1:" + str(nodes2clust) print "merge_dict, day 1:" + str(merge_dict) day2fires = df[df.dayofyear == 2] clust2nodes, node2clusts, merge_dict = find_daily_clusters( day2fires, neighbors_dict, clust2nodes=clust2nodes, nodes2clust=nodes2clust, merge_dict=merge_dict) print "clust2nodes, day 2:" + str(clust2nodes) print "node2clusts, day 2:" + str(nodes2clust) print "merge_dict, day 2:" + str(merge_dict) day3fires = df[df.dayofyear == 3] clust2nodes, node2clusts, merge_dict = find_daily_clusters( day3fires, neighbors_dict, clust2nodes=clust2nodes, nodes2clust=nodes2clust, merge_dict=merge_dict) print "clust2nodes, day 3:" + str(clust2nodes) print "node2clusts, day 3:" + str(nodes2clust) print "merge_dict, day 3:" + str(merge_dict)
def drawModel(self): if self.modelFigure == None or self.modelFigure.canvas.manager.window == None: self.modelFigure = PL.figure() PL.get_current_fig_manager().window.geometry("+420+30") self.modelFigure.canvas.set_window_title(self.titleText) PL.ion() self.modelDrawFunc() self.modelFigure.canvas.manager.window.update()
def plot(arg): update_values(arg) axis = pylab.arange(len(pitch_value) - max_plot, len(pitch_value), 1) pitch_acc_graph[0].set_data(axis, pylab.array(pitch_acc_value[-max_plot:])) pitch_rot_graph[0].set_data(axis, pylab.array(pitch_rot_value[-max_plot:])) pitch_graph[0].set_data(axis, pylab.array(pitch_value[-max_plot:])) ax.axis([axis.min(), axis.max(), min_y, max_y]) pylab.get_current_fig_manager().canvas.draw()
def plot(arg): update_values(arg) axis=pylab.arange(len(pitch_value)-max_plot,len(pitch_value),1) pitch_acc_graph[0].set_data(axis,pylab.array(pitch_acc_value[-max_plot:])) pitch_rot_graph[0].set_data(axis,pylab.array(pitch_rot_value[-max_plot:])) pitch_graph[0].set_data(axis,pylab.array(pitch_value[-max_plot:])) ax.axis([axis.min(),axis.max(),min_y,max_y]) pylab.get_current_fig_manager().canvas.draw()
def set_figure_size_and_location(x=50,y=50,width=400,height=400): if matplotlib_backend in ['WX','WXAgg']: thismanager = get_current_fig_manager() thismanager.window.SetPosition((x, y)) thismanager.window.SetSize((width,height)) elif matplotlib_backend in ['Qt4Agg','Qt5Agg']: thismanager = get_current_fig_manager() thismanager.window.setGeometry(x,y,width,height) else: raise NotImplementedError(matplotlib_backend)
def set_figure_size_and_location(x=50, y=50, width=400, height=400): if matplotlib_backend in ['WX', 'WXAgg']: thismanager = get_current_fig_manager() thismanager.window.SetPosition((x, y)) thismanager.window.SetSize((width, height)) elif matplotlib_backend == 'Qt4Agg': thismanager = get_current_fig_manager() thismanager.window.setGeometry(x, y, width, height) else: raise NotImplementedError(matplotlib_backend)
def plot_boxplot_dinucleotides_by_type(df, time): grouped = df.groupby(["Degree", "Di_nucleotide", "Replica", "Type"]).apply(lambda x: x) sns.boxplot(x="Type", y="Freq", hue="Di_nucleotide", data=grouped) plt.yscale("log") plt.ylim(0.0000001, 1) plt.title( "Mutations frequencies as a function of genomic context Passage{}". format(time)) sns.plt.legend(loc='upper left', bbox_to_anchor=(1.0, 0.7)) pylab.get_current_fig_manager().window.showMaximized() plt.show()
def keypress(event): """ Handle key shortcut in a window called from: click, display input: event structure output: None """ from pylab import close,gcf,figure,gca,text,title,show event.key = event.key.lower() if event.key == 'q': close('all') elif event.key == 'x': close('all') elif event.key == 'p': dumpfile('ps') elif event.key == 'd': dumpfile('pdf') elif event.key == 'n': dumpfile('png') elif event.key == 'j': dumpfile('jpg') elif event.key == 'o' or event.key == 'l': 'toggle lin/log' from pylab import get_current_fig_manager tb = get_current_fig_manager().toolbar options.log = not options.log; if options.log == True: tb.set_message('Log intensity scale selected for next plots'); else: tb.set_message('Linear intensity scale selected for next plots'); elif event.key == 'c': 'toggle contour/normal' from pylab import get_current_fig_manager tb = get_current_fig_manager().toolbar options.contour = not options.contour; if options.contour == True: tb.set_message('Contour mode selected for next 2D plots'); else: tb.set_message('Normal mode selected for next 2D plots'); elif event.key == 'h': 'usage/help' h=figure() text(0.05,0.05,usage) title(os.path.basename(sys.argv[0]) + ": plotting tool for McCode data set",fontweight='bold') show() elif event.key == 'right' or event.key == 'pagedown': 'show next scan step/monitor' display_scanstep(File, +1) elif event.key == 'left' or event.key == 'backspace' or event.key == 'pageup': 'show previous scan step/monitor' display_scanstep(File, -1)
def plot(arg): update_values(arg) axis = pylab.arange(len(accx_value) - max_plot, len(accx_value), 1) accx_graph[0].set_data(axis, pylab.array(accx_value[-max_plot:])) accy_graph[0].set_data(axis, pylab.array(accy_value[-max_plot:])) accz_graph[0].set_data(axis, pylab.array(accz_value[-max_plot:])) rotx_graph[0].set_data(axis, pylab.array(rotx_value[-max_plot:])) roty_graph[0].set_data(axis, pylab.array(roty_value[-max_plot:])) rotz_graph[0].set_data(axis, pylab.array(rotz_value[-max_plot:])) ax.axis([axis.min(), axis.max(), min_y, max_y]) pylab.get_current_fig_manager().canvas.draw()
def plot(arg): update_values(arg) axis=pylab.arange(len(accx_value)-max_plot,len(accx_value),1) accx_graph[0].set_data(axis,pylab.array(accx_value[-max_plot:])) accy_graph[0].set_data(axis,pylab.array(accy_value[-max_plot:])) accz_graph[0].set_data(axis,pylab.array(accz_value[-max_plot:])) rotx_graph[0].set_data(axis,pylab.array(rotx_value[-max_plot:])) roty_graph[0].set_data(axis,pylab.array(roty_value[-max_plot:])) rotz_graph[0].set_data(axis,pylab.array(rotz_value[-max_plot:])) ax.axis([axis.min(),axis.max(),min_y,max_y]) pylab.get_current_fig_manager().canvas.draw()
def refresh_raster_plot(clk): if matplotlib.is_interactive(): if myopts["showlast"] is None: st, sn, nmax = get_plot_coords() line.set_xdata(st) line.set_ydata(sn) ax.set_xlim(0, amax(st)) else: st, sn, nmax = get_plot_coords(clk._t - float(myopts["showlast"]), clk._t) ax.set_xlim((clk.t - myopts["showlast"]) / ms, clk.t / ms) line.set_xdata(array(st)) line.set_ydata(sn) if myopts["redraw"]: pylab.draw() pylab.get_current_fig_manager().canvas.flush_events()
def refresh_raster_plot(clk): if matplotlib.is_interactive(): if myopts['showlast'] is None: st, sn, nmax = get_plot_coords() line.set_xdata(st) line.set_ydata(sn) ax.set_xlim(0, amax(st)) else: st, sn, nmax = get_plot_coords(clk._t - float(myopts['showlast']), clk._t) ax.set_xlim((clk.t - myopts['showlast']) / ms, clk.t / ms) line.set_xdata(array(st)) line.set_ydata(sn) if myopts['redraw']: pylab.draw() pylab.get_current_fig_manager().canvas.flush_events()
def plot_count_dinucleotides_by_degree(df, time): grouped = df.groupby(["Degree", "Di_nucleotide", "Replica"]).size().reset_index(name="Count") sns.set(style="ticks") nuc_order = list(set(grouped['Di_nucleotide'])) grid = sns.FacetGrid(grouped, col="Degree", row="Replica", row_order=['A', 'B'], hue="Degree", palette="YlGnBu") # palette="RdYlGn" grid.map(sns.barplot, "Di_nucleotide", "Count", order=nuc_order) grid.fig.suptitle("Count by degree Passage {}".format(time), fontsize=18) pylab.get_current_fig_manager().window.showMaximized() plt.show()
def __init__(self, skeleton, azim, size=6, i=8): # self.fig.tight_layout() # prevent wired error _ = Axes3D.__class__.__name__ radius = 1.7 self.fig_3d = plt.figure(figsize=(size, size)) self.ax_3d = self.fig_3d.add_subplot(1, 1, 1, projection='3d') self.ax_3d.view_init(elev=15., azim=azim) self.ax_3d.set_xlim3d([-radius / 2, radius / 2]) self.ax_3d.set_zlim3d([0, radius]) self.ax_3d.set_ylim3d([-radius / 2, radius / 2]) self.ax_3d.set_xticklabels([]) self.ax_3d.set_yticklabels([]) self.ax_3d.set_zticklabels([]) self.ax_3d.dist = 12.5 self.ax_3d.set_title('Reconstruction') self.initialized = False self.image = None self.lines_3d = [] self.pos_list = [] self.point = None self.parents = skeleton.parents() self.joints_right = skeleton.joints_right() self.i = i thismanager = get_current_fig_manager() thismanager.window.wm_geometry("+0+1000")
def move_current_figure(x, y): """Flytta aktiv figur, till *x* och *y* koordinaten men tillat inte att det hamnar utanfor skarmkanten. """ move_fig(pylab.get_current_fig_manager(), x, y)
def initWidgets(self): self.fig = plt.figure(1) self.img = subplot(111) self.manager=get_current_fig_manager() self.img = subplot(2,1,2) self.TempGraph=subplot(2,1,1) row=0 self.grid() self.lblPower=tk.Label(self,text="Power") self.lblPower.grid(row=row,column=0) self.sclPower=tk.Scale(self,from_=0,to_=100,orient=tk.HORIZONTAL) self.sclPower.grid(row=row,column=1,columnspan=3) row=row+1 self.lblTime=tk.Label(self,text="Time={0}".format(self.time)) self.lblTime.grid(row=row,column=0) #lastrow row=row+1 self.btnOne=tk.Button(master=self,text="Run") self.btnOne["command"]=self.Run self.btnOne.grid(row=row,column=0) self.btnTwo=tk.Button(master=self,text="Soak") self.btnTwo["command"]=self.Soak self.btnTwo.grid(row=row,column=2) self.QUIT=tk.Button(master=self,text="QUIT") self.QUIT["command"]=self.quit self.QUIT.grid(row=row,column=3)
def initWidgets(self): self.fig = plt.figure(1) self.manager=get_current_fig_manager() self.img = subplot(2,1,1) self.TempGraph=subplot(2,1,2) x1=sp.linspace(0.0,5.0) y1=sp.cos(2*sp.pi*x1)*sp.exp(-x1) plt.plot(x1,y1) row=0 self.grid() self.lblPower=tk.Label(self,text="Power") self.lblPower.grid(row=row,column=0) self.sclPower=tk.Scale(self,from_=0,to_=100000,orient=tk.HORIZONTAL) self.sclPower.grid(row=row,column=1,columnspan=3) #lastrow row=row+1 self.btnOne=tk.Button(master=self,text="Run") self.btnOne["command"]=self.Run self.btnOne.grid(row=row,column=0) self.btnTwo=tk.Button(master=self,text="Soak") self.btnTwo["command"]=self.Soak self.btnTwo.grid(row=row,column=2) self.QUIT=tk.Button(master=self,text="QUIT") self.QUIT["command"]=self.quit self.QUIT.grid(row=row,column=3)
def onselect(xmin, xmax): global yyy # this runs after the selection has been made tb = pl.get_current_fig_manager().toolbar if tb.mode == '': # find indices of selection indmin, indmax = npy.searchsorted(x, (xmin, xmax)) indmax = min(len(x)-1, indmax) # add selected range to list ranges.append([indmin,indmax]) thisx = x[indmin:indmax] thisy = y[indmin:indmax] # fit polynomial to selected data n = input('Order of polynomial to fit ? : ') xx,yy = fit_data(thisx,thisy,n) polys.append(yy) # plot polynomial on middle plot over raw data ax2.plot(xx,yy,'r-') yyy = y.copy() # subtract selected ranges from lightcurve for r in range(len(ranges)): yyy[ranges[r][0]:ranges[r][1]] -= polys[r] line3.set_data(x,yyy) #ax3.plot(x,yyy,'.') fig.canvas.draw()
def chargingRatePlot(filePath='/tmp/some.file', plotLabel = 'New Plot'): ''' Plots a graph A(t) where: A - current measured from multimeter t - time stamp Throws IOError exeption if file doesn't exist returns None ''' try: # check if file exists, throws exeption otherwise times, measurements = getMeasurements(filePath) average = sum(measurements) / len(measurements) print('avg = ' + str(average)) # plotting related stuff pylab.figure(str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")), figsize=(22.0, 9.0)) pylab.title(plotLabel) pylab.xlabel('time, hour') pylab.ylabel('current, A') pylab.grid(True) legend_label = 'avg=' + str("{0:.4f}".format(average)) + 'A' pylab.plot(times, measurements, '-b', label=legend_label) mng = pylab.get_current_fig_manager() # get figure manager for # mng.resize(*mng.window.maxsize()) # setting window size to max mng.full_screen_toggle() pylab.legend(loc='best') # should be placed after pylab.plot() pylab.savefig(plotLabel + ' ' + legend_label + '.png', format='png', dpi=200) pylab.show() except IOError: print "File does not exist! Check file in " + str(filePath)
def refresh_raster_plot(clk): if matplotlib.is_interactive(): if myopts['showlast'] is None: st, sn, nmax = get_plot_coords() line.set_xdata(st) line.set_ydata(sn) ax.set_xlim(0, amax(st)) else: st, sn, nmax = get_plot_coords(clk._t - float(myopts['showlast']), clk._t) ax.set_xlim((clk.t - myopts['showlast']) / ms, clk.t / ms) line.set_xdata(array(st)) line.set_ydata(sn) if myopts['redraw']: pylab.draw() pylab.pause(0.001) # prevents the NotImplementedError pylab.get_current_fig_manager().canvas.flush_events()
def plot_all_pressures(self): conn = psycopg2.connect("dbname=will user=levlab host=levlabserver2.stanford.edu") cur = conn.cursor() sensor_query = '''SELECT {0}.name FROM {0} WHERE {0}.fault=FALSE and {0}.unit='Torr';'''.format(GAUGE_TABLE) cur.execute(sensor_query) sensors = cur.fetchall() databysensors = dict() notesbysensors = dict() for sensor in sensors: sensorname = sensor[0] data_query = '''SELECT {0}.time, {0}.value FROM {0}, {1} WHERE {0}.value > 0 and {0}.id = {1}.id and {1}.name = %s and {1}.unit='Torr' and {0}.time > %s;'''.format(PRESSURES_TABLE, GAUGE_TABLE) cur.execute(data_query, (sensorname, STARTDATETIME,)) databysensors[sensorname]=cur.fetchall() notesbysensors[sensorname]=cur.fetchall() cur.close() conn.close() fig = pylab.figure(2,figsize=(12,6)) ax1 = fig.add_subplot(111) ax1.set_yscale('log') for sensor in sensors: x = [data[0] for data in databysensors[sensor[0]]] y = [data[1] for data in databysensors[sensor[0]]] ax1.plot_date(x, y,'-', label = sensor[0]) ax1.fmt_xdate = matplotlib.dates.DateFormatter('%H%M') ax1.legend(loc = 'lower left') ax1.set_xlabel('Time') ax1.set_ylabel('Pressure / Torr') fig.autofmt_xdate() wm = pylab.get_current_fig_manager() wm.window.state('zoomed')
def plot_all_TCs(self): conn = psycopg2.connect("dbname=will user=levlab host=levlabserver2.stanford.edu") cur = conn.cursor() sensor_query = '''SELECT {0}.name FROM {0} WHERE {0}.fault=FALSE and {0}.unit='C';'''.format(THERMOCOUPLE_TABLE) cur.execute(sensor_query) sensors = cur.fetchall() print sensors databysensors = dict() notesbysensors=dict() for sensor in sensors: sensorname = sensor[0] data_query = '''SELECT {0}.time, {0}.value FROM {0}, {1} WHERE {0}.sensorid = {1}.id and {1}.name = %s and {0}.value < 1000 and {1}.unit='C' and {0}.time > %s;'''.format(DATA_TABLE, THERMOCOUPLE_TABLE) cur.execute(data_query, (sensorname, STARTDATETIME)) databysensors[sensorname]=cur.fetchall() notesbysensors[sensorname]=cur.fetchall() cur.close() conn.close() fig = pylab.figure(1,figsize = (12,6)) ax1 = fig.add_subplot(111) for sensor in sensors: x = [data[0] for data in databysensors[sensor[0]]] y = [data[1] for data in databysensors[sensor[0]]] ax1.plot_date(x, y, '-', label = sensor[0]) ax1.fmt_xdate = matplotlib.dates.DateFormatter('%H%M') ax1.legend(loc = 'upper left') ax1.set_xlabel('Time') ax1.set_ylabel('Temperature / C') ax1.set_title('Oven Section Temperature Data, August 2014') fig.autofmt_xdate() wm = pylab.get_current_fig_manager() wm.window.state('zoomed')
def displayDelaunayMesh(points, radius, mask, xrange): # print("displayDelaunayMesh points:", points) triangulation, points = generateDelaunay(points, radius, mask, xrange) # triangles = tri.simplices # for triangle in triangles: # Bridson_Common.logDebug(__name__, "Triangle:", triangle) # print("Points:", points) if Bridson_Common.debug: Bridson_Common.logDebug(__name__, "tri", triangulation) plt.figure() plt.subplot(1, 1, 1, aspect=1) plt.title('Display Triangulation') # plt.triplot(points[:,0], points[:,1], tri.simplices.copy()) # Plot the lines representing the mesh. if Bridson_Common.invert: plt.triplot(points[:, 1], xrange - points[:, 0], triangulation.triangles) else: plt.triplot(points[:, 1], points[:, 0], triangulation.triangles) # Plot the points on the border. if Bridson_Common.invert: plt.plot(points[:, 1], xrange - points[:, 0], 'o') else: plt.plot(points[:, 1], points[:, 0], 'o') thismanager = pylab.get_current_fig_manager() thismanager.window.wm_geometry("+640+560") # print("displayDelaunayMesh: Pickling String for triangulation:", pickle.dumps(triangulation)) return triangulation, points
def onclick(self, event): # when none of the toolbar buttons is activated and the user clicks in the # plot somewhere, compute the median value of the spectrum in a 10angstrom # window around the x-coordinate of the clicked point. The y coordinate # of the clicked point is not important. Make sure the continuum points # `feel` it when it gets clicked, set the `feel-radius` (picker) to 5 points toolbar = pl.get_current_fig_manager().toolbar if event.button == 1 and toolbar.mode == '': window = ((event.xdata-self.winwidth)<=self.wave) &\ (self.wave<=(event.xdata+self.winwidth)) y = np.nanmedian(self.flux[window]) if y != y: print("clicked out of range") return if near_balmer(event.xdata): self.ax.plot(event.xdata, y, 'bs', ms=10, picker=5, label='cont_pnt') print("Blue point near balmer line") else: self.ax.plot(event.xdata, y, 'rs', ms=10, picker=5, label='cont_pnt') pl.draw()
def __init__(self): self.win = gtk.Window() #win.connect("destroy", lambda x: gtk.main_quit()) self.win.connect("delete-event", self.hideinsteadofdelete) self.win.set_default_size(400,300) self.win.set_title("Embedding in GTK") vbox = gtk.VBox() self.win.add(vbox) self.f = Figure(figsize=(5,4), dpi=100) sw = gtk.ScrolledWindow() vbox.pack_start(sw) #self.win.add (sw) # A scrolled window border goes outside the scrollbars and viewport sw.set_border_width (10) # policy: ALWAYS, AUTOMATIC, NEVER sw.set_policy (hscrollbar_policy=gtk.POLICY_AUTOMATIC, vscrollbar_policy=gtk.POLICY_ALWAYS) self.canvas = FigureCanvas(self.f) # a gtk.DrawingArea #vbox.pack_start(canvas) self.canvas.set_size_request(300,200) sw.add_with_viewport (self.canvas) manager = get_current_fig_manager() # you can also access the window or vbox attributes this way toolbar = manager.toolbar #vbox.pack_start(canvas) toolbar = NavigationToolbar(self.canvas, self.win) vbox.pack_start(toolbar, False, False) self.win.show_all()
def grafico(request, graph_id): query_results = Graphs.objects.all() query_results = query_results.filter(id=graph_id).first() fig, axs = pyplot.subplots(2, 1) size = 0.6 axs[1].scatter(query_results.xplot, query_results.yplot, label='Actual', s=size) axs[1].scatter(query_results.xplot, query_results.yhatplot, label='Predicted', s=size) axs[1].set_title('Final model') axs[0].scatter(query_results.xplot, query_results.yplot, label='Actual', s=size) axs[0].scatter(query_results.initial_xplot, query_results.initial_yhatplot, label='Predicted', s=size) axs[0].set_title('Initial model') buffer = io.BytesIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() graphIMG = PIL.Image.frombytes('RGB', canvas.get_width_height(), canvas.tostring_rgb()) graphIMG.save(buffer, "PNG") pylab.close() return HttpResponse(buffer.getvalue(), content_type="Image/png")
def arrange_figures(layout=None, screen=2, xgap=10, ygap=30, offset=0, figlist=None): """Automatiskt arrangera alla figurer i ett icke overlappande monster *layout* Anvands inte just nu *screen* [=2] anger vilken skarm man i forsta hand vill ha fonstren pa. *xgap* Gap i x-led mellan fonster *ygap* Gap i y-led mellan fonster *offset* Nar skarmen ar fylld borjar man om fran ovre hogra hornet men med en offset i x och y led. *figlist* Lista med figurnummer som skall arrangeras """ #Hamta information om total skarmbredd over alla anslutna skarmar if not is_in_ipython(): return # pylab.show() pylab.ioff() x0 = 0 + offset y0 = 0 + offset if screen == 2: x0 = (pylab.get_current_fig_manager().window.winfo_screenwidth() + offset) if figlist is None: figlist = sorted([x for x in Gcf.figs.items()]) x = x0 y = y0 maxheight = 0 while figlist: fig = _, f = figlist[0] figlist = figlist[1:] if fig_fits_w(f, x): move_fig(f, x, y) x = x + f.window.winfo_width() + xgap maxheight = max(maxheight, f.window.winfo_height()) else: x = x0 y = y + maxheight + ygap maxheight = 0 if fig_fits_h(f, y): move_fig(f, x, y) x = x + f.window.winfo_width() + xgap else: arrange_figures(offset=DELTAOFFSET, xgap=xgap, ygap=ygap, screen=screen, figlist=[fig] + figlist) break pylab.ion()
def gui(self, log=False, maximize=False): """ @param log: show z in log scale """ if self.fig is None: self.fig = pylab.plt.figure() # add 3 subplots at the same position for debye-sherrer image, contour-plot and massif contour self.ax = self.fig.add_subplot(111) self.ct = self.fig.add_subplot(111) self.msp = self.fig.add_subplot(111) if log: self.ax.imshow(numpy.log(1.0 + self.data - self.data.min()), origin="lower", interpolation="nearest") else: self.ax.imshow(self.data, origin="lower", interpolation="nearest") self.ax.autoscale_view(False, False, False) self.fig.show() if maximize: mng = pylab.get_current_fig_manager() # print mng.window.maxsize() # *mng.window.maxsize()) win_shape = (1920, 1080) event = Event(*win_shape) try: mng.resize(event) except TypeError: mng.resize(*win_shape) self.fig.canvas.draw() self.fig.canvas.mpl_connect('button_press_event', self.onclick)
def __init__(self, x, y): f = matplotlib.figure.Figure(figsize=(5, 4), dpi=100) # f = matplotlib.figure.Figure(dpi=100) ax = f.add_subplot(111) canvas = ax.figure.canvas line, = p.plot(x, y, animated=True, lw=2) canvas = FigureCanvasTkAgg(f, master=root) canvas.show() canvas.get_tk_widget().grid() toolbar = NavigationToolbar2TkAgg(canvas, root) toolbar.update() canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) p.subplots_adjust(left=-0.1, bottom=0.0) manager = p.get_current_fig_manager() manager.window.after(100, self.run) self.canvas = canvas self.ax = ax self.line = line self.x = x self.y = y
def plot_data(yRange=None): ''' Plots and saves the cell measurement data. Returns nothing. ''' fig = plt.figure(figsize=(18,12)) ax = plt.subplot(111) plt.errorbar(range(len(avgCells.index)), avgCells[column], yerr=stdCells[column], fmt='o') ax = plt.gca() ax.set(xticks=range(len(avgCells.index)), xticklabels=avgCells.index) xlims = ax.get_xlim() ax.set_xlim([lim-1 for lim in xlims]) # adjust yRange if it was specified if yRange!=None: ax.set_ylim(yRange) fileName = column + ' exlcuding outliers' else: fileName = column plt.subplots_adjust(bottom=0.2, right=0.98, left=0.05) plt.title(column) plt.ylabel('mm') locs, labels = plt.xticks() plt.setp(labels, rotation=90) mng = plt.get_current_fig_manager() mng.window.state('zoomed') #plt.show() path1 = 'Y:/Test data/ACT02/vision inspection/plot_100_cells/' path2 = 'Y:/Nate/git/nuvosun-python-lib/vision system/plot_100_cells/' fig.savefig(path1 + fileName, bbox_inches = 'tight') fig.savefig(path2 + fileName, bbox_inches = 'tight') plt.close()
def quiver_image(X, Y, U, V): pylab.figure(1) pylab.quiver(X, Y, U, V) canvas = pylab.get_current_fig_manager().canvas canvas.draw() pil_image = Image.fromstring('RGB', canvas.get_width_height(), canvas.tostring_rgb()) return pil_image
def run(): colors = [ 'b', 'g', 'r', 'c', 'm', 'y', 'k', 'b--', 'g--', 'r--', 'c--', 'm--', 'y--', 'k--', 'bo', 'go', 'ro', 'co', 'mo', 'yo', 'ko', 'b+', 'g+', 'r+', 'c+', 'm+', 'y+', 'k+', 'b*', 'g*', 'r*', 'c*', 'm*', 'y*', 'k*', 'b|', 'g|', 'r|', 'c|', 'm|', 'y|', 'k|', ] plots = defaultdict(list) heap_size = [] order = ['Heap change'] manager = pylab.get_current_fig_manager() manager.resize(1400, 1350) pylab.ion() for entry in read_data(): heap_size.append(entry["after"]["size_bytes"]) pylab.subplot(2, 1, 1) pylab.plot(heap_size, 'r', label='Heap size') pylab.legend(["Heap size"], loc=2) pylab.subplot(2, 1, 2) plots["Heap change"].append(entry["change"]["size_bytes"]) for thing in entry["change"]["details"]: if thing["what"] not in order: order.append(thing["what"]) plots[thing["what"]].append(thing["size_bytes"]) for what, color in zip(order, colors): pylab.plot(plots[what], color, label=what) pylab.legend(order, loc=3) pylab.draw()
def defList(self, sList,sTitle ): t = numpy.arange(0.0, len(sList), 1) s = sList figure(num=sTitle,figsize=(12,10)) thismanager = get_current_fig_manager() plot(t, s, color="red", linewidth=1, linestyle="-")
def __init__(self, tree, size_method, color_method, string_method=str, iter_method=iter, margin=0.0): """create a tree map from tree, using itermethod(node) to walk tree, size_method(node) to get object size and color_method(node) to get its color. Optionally provide a string method called on a node to show which node has been clicked (default str) and a margin (proportion in [0,0.5)""" self.size_method = size_method self.iter_method = iter_method self.color_method = color_method self.string_method = string_method self.areas = {} self.margin = margin self.ax = pylab.subplot(111) pylab.subplots_adjust(left=0, right=1, top=1, bottom=0) self.addnode(tree) pylab.disconnect(pylab.get_current_fig_manager().toolbar._idDrag) pylab.connect('motion_notify_event', self.show_node_label) pylab.connect('button_press_event', self.zoom_selected)
def show(): def process(filename: str = None) -> None: image = Image.open(filename) ax[j][i].set_title("Knn = " + str(valueKNN[j - 1]), color='red') ax[j][i].imshow(image, cmap='gray') fig, ax = plt.subplots(nrows=6, ncols=10) for x in range(6): for y in range(10): ax[x][y].set_axis_off() j, i = [0, 0] image = Image.open('Faces/TestSet/' + str(TestPicture) + '.jpg') ax[j][i].set_title("Test Image", color='Green') ax[j][i].set_axis_off() ax[j][i].imshow(image, cmap='gray') j += 1 for K in Knn: for file in K: process('Faces/TrainSet/' + str(file + 1) + '.jpg') i += 1 j = j + 1 i = 0 figManager = plt.get_current_fig_manager() figManager.window.showMaximized() plt.show()
def on_release(self, event): if plt.get_current_fig_manager().toolbar.mode != '': return if event.button == 1: self.x1 = event.xdata self.y1 = event.ydata if self.y0 >= self.y1 and self.x0 >= self.x1: self.curr_mask[int(self.y1):int(self.y0 + 1), int(self.x1):int(self.x0 + 1)] = 0 elif self.y0 >= self.y1 and self.x1 >= self.x0: self.curr_mask[int(self.y1):int(self.y0 + 1), int(self.x0):int(self.x1 + 1)] = 0 elif self.x0 >= self.x1 and self.y1 >= self.y0: self.curr_mask[int(self.y0):int(self.y1 + 1), int(self.x0):int(self.x1 + 1)] = 0 else: self.curr_mask[int(self.y0):int(self.y1 + 1), int(self.x0):int(self.x1 + 1)] = 0 logdata = np.log10(np.abs(self.curr_data)) * np.abs(self.curr_mask) minD = np.min(logdata) maxD = np.max(logdata) if self.delay_only: self.delay_plot.set_data(np.log10(np.abs(self.delayTrans()))) self.canvas2.draw() else: curr_mask = np.copy(self.curr_mask) curr_mask = np.where(curr_mask == 0, np.nan, curr_mask) self.amp_plot.set_data( np.log10(np.abs(self.curr_data)) * np.abs(curr_mask)) self.canvas.draw() self.delay_plot.set_data(np.log10(np.abs(self.delayTrans()))) self.canvas2.draw() self.phs_plot.set_data(np.angle(self.curr_data * curr_mask)) self.canvas3.draw()
def show_query(self, closest, N, query_img): print(self.query_count) cnt = self.query_count % QUERIES_PER_PLOT if cnt == 0: cnt = QUERIES_PER_PLOT if cnt == 1: plt.figure(figsize=(16,12)) thismanager = get_current_fig_manager() thismanager.window.wm_geometry("+50+50") plt.subplot(QUERIES_PER_PLOT, N, (cnt-1)*N + 1) self.show_im(query_img) for i in range(N-1): plt.subplot(QUERIES_PER_PLOT, N, (cnt-1)*N + i+2) self.show_im(self.read_im_by_idx(closest[i])) if self.qidx and i == 0: plt.title(self.qidx+1) # Show anti-examples # plt.subplot(2,N, N + i+1) # self.show_im(closest[-(i+1)]) plt.subplots_adjust(wspace=0.05, hspace=0) if cnt == QUERIES_PER_PLOT: plt.show()
def __init__(self, datatype, filenames, options): self.hfile = list() self.legend_text = list() for f in filenames: self.hfile.append(open(f, "r")) self.legend_text.append(f) self.block_length = options.block self.start = options.start self.sample_rate = options.sample_rate self.datatype = datatype if self.datatype is None: self.datatype = datatype_lookup[options.data_type] self.sizeof_data = self.datatype( ).nbytes # number of bytes per sample in file self.axis_font_size = 16 self.label_font_size = 18 self.title_font_size = 20 self.text_size = 22 # Setup PLOT self.fig = figure(1, figsize=(16, 9), facecolor='w') rcParams['xtick.labelsize'] = self.axis_font_size rcParams['ytick.labelsize'] = self.axis_font_size self.text_file_pos = figtext(0.10, 0.88, "File Position: ", weight="heavy", size=self.text_size) self.text_block = figtext(0.40, 0.88, ("Block Size: %d" % self.block_length), weight="heavy", size=self.text_size) self.text_sr = figtext(0.60, 0.88, ("Sample Rate: %.2f" % self.sample_rate), weight="heavy", size=self.text_size) self.make_plots() self.button_left_axes = self.fig.add_axes([0.45, 0.01, 0.05, 0.05], frameon=True) self.button_left = Button(self.button_left_axes, "<") self.button_left_callback = self.button_left.on_clicked( self.button_left_click) self.button_right_axes = self.fig.add_axes([0.50, 0.01, 0.05, 0.05], frameon=True) self.button_right = Button(self.button_right_axes, ">") self.button_right_callback = self.button_right.on_clicked( self.button_right_click) self.xlim = self.sp_f.get_xlim() self.manager = get_current_fig_manager() connect('key_press_event', self.click) show()
def __init__(self, camera_matrix, dist_coeffs, homography, rvec, tvec, angspeed, center, axis): self.cm = camera_matrix self.dc = dist_coeffs self.homography = homography self.rvec = rvec self.tvec = tvec self.angspeed = angspeed self.center = center self.axis = axis # Socket self.HOST = "localhost" self.PORT = 8888 self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Struct object for the linescan self.linescan_struct = struct.Struct(2048*'H') # Matplotlib plot setup self.fig = pylab.figure(1) self.ax = self.fig.add_subplot(111) self.ax.grid(True) self.ax.set_title('Linescan plotter') self.ax.axis([0, 2048, 1088, 0]) self.range = pylab.arange(0, 2048, 1) self.line1, = self.ax.plot(2048, 1088) self.manager = pylab.get_current_fig_manager() # Mouse input self.cid = self.fig.canvas.mpl_connect('button_press_event', self.on_click) # Buttons # Save button self.save_button_ax = pylab.axes([0.8, 0.91, 0.1, 0.075]) self.save_button = Button(self.save_button_ax, 'Save') self.save_button.on_clicked(self.save_scanlines) # Stop button self.stop_button_ax = pylab.axes([0.23, 0.91, 0.1, 0.075]) self.stop_button = Button(self.stop_button_ax, 'Stop') self.stop_button.on_clicked(self.stop_scan) # Start button self.start_button_ax = pylab.axes([0.125, 0.91, 0.1, 0.075]) self.start_button = Button(self.start_button_ax, 'Start') self.start_button.on_clicked(self.start_scan) # Timer thread self.timer = self.fig.canvas.new_timer(interval=20) self.timer.add_callback(self.callback, ()) self.timer.start() # Scan variables self.scan_range = [] self.scanlines = [] self.scanline_times = [] self.start_scan_time = None self.stop_scan_time = None self.scan_time = None self.scanning = False # Get transforms self.get_laser_to_turntable_transform() # Start pylab.show()
def imshow_val(img, *args, **kwargs): o = MyFormatter(img) imshow(convert_ndarr(img), *args, **kwargs) canvas = get_current_fig_manager().canvas ax = gca() canvas.mpl_connect("motion_notify_event", o.on_move) ax.fmt_xdata = o.fmtx ax.fmt_ydata = o.fmty
def plot_mutation_types_diff(df, degree=None, replica=None): """ This method plots a scatter of mutations fitness values by mutation type - synonymous, non-synonymous or stop :param df: a data frame with mutation type information - "Type" field :param degree: optional. default = None :param replica: optional. default = None :return: a scatter of fitness values according to type """ if degree != None: df = df[df['Degree'] == degree] if replica != None: df = df[df['Replica'] == replica] # remove un coding regions. df = df[df['Type'] != 'non-coding'] # Make a custom sequential palette using the cubehelix system pal = sns.cubehelix_palette(10, 2, 2, light=.6, dark=.2) current_palette_7 = sns.color_palette("hls", 5) x = sns.set_palette(current_palette_7) sns.set_style("darkgrid") sns.lmplot(x="Pos", y="Fitness_median", hue="Type", data=df, fit_reg=False, palette=x, legend=False) plt.title("Fitness values distribution by type") if degree != None and replica != None: plt.title("Fitness values distribution by type {} {}".format( degree, replica)) elif degree != None and replica == None: plt.title( "Fitness values distribution by type {} degrees".format(degree)) else: plt.title( "Fitness values distribution by type replica {}".format(replica)) plt.ylabel("Fitness value") plt.xlabel("Position in the genome (bp)") plt.ylim(-0.06, 1.8) sns.plt.legend(loc='upper left', bbox_to_anchor=(-0.25, 0.94)) pylab.get_current_fig_manager().window.showMaximized() plt.show()
def onclick(self,event): posx=event.xdata posy=event.ydata print pyl.get_current_fig_manager().toolbar._active,posx if pyl.get_current_fig_manager().toolbar._active==None and posx<>None and posy<>None and event.button==1 and not self.shift_is_held and not self.ctrl_is_held: r=self.cratRad*self.getWidthAdjust(posy) ellipse=Ellipse((posx,posy), r,self.cratRad, angle=0., facecolor=self.facecolor, edgecolor=self.edgecolor,zorder=10, linewidth=2, alpha=self.alpha, picker=True) self.sp.add_patch(ellipse) self.patchList.append(ellipse) #self.patchRads.append(cratRadius) pyl.draw()
def press(self, event): tb = pylab.get_current_fig_manager().toolbar if tb.mode == '': x, y = event.xdata, event.ydata if event.inaxes is not None: self.buttonDown = True self.button = event.button self.y = y
def plot_one_budget(KET, s, nm, t_strt): rc('text', usetex=True) font = {'size': 26} rc('font', **font) rc('lines', linewidth=2) # lwd=2 RES = (KET['dKEdt'] + KET['pUpls'] + KET['pUmns'] + KET['pWmns'] + KET['toPE'] + KET['GSP'] + KET['LSP'] - KET['LDiss'] - KET['HDiss']) # fig = plt.figure(nm) # plt = fig.gca() t_scl = 0.5 * KET['t'][t_strt:] * s.f / np.pi plt.plot(t_scl, KET['dKEdt'][t_strt:], 'k', label='$\partial KE/\partial t$') plt.plot(t_scl, KET['GSP'][t_strt:], 'b', label='Geostrophic SP') plt.plot(t_scl, KET['LSP'][t_strt:], 'b--', label='Lateral SP') plt.plot(t_scl, KET['toPE'][t_strt:], color='brown', label="$-wb'$") plt.plot(t_scl, KET['pUpls'][t_strt:], 'r:', label="$p'u|_{right}$") plt.plot(t_scl, KET['pUmns'][t_strt:], 'r', label="$p'u|_{le\!f\!t}$") plt.plot(t_scl, KET['pWmns'][t_strt:], 'r--', label="$p'w|_{bottom}$") plt.plot(t_scl, KET['LDiss'][t_strt:], 'g', label=r"$-(\nu \nabla^2 \vec v')\cdot \vec v'$") plt.plot(t_scl, KET['HDiss'][t_strt:], 'g--', label=r"$-(-\nu_4 \nabla^4 \vec v')\cdot \vec v'$") # plt.plot(t_scl, RES[t_strt:], 'r--', label="Residual") plt.grid('on') plt.axis([t_scl[0], 12., -6e-4, 6e-4]) plt.xlabel("$tf/2\pi$") plt.ylabel("Power Per Unit Density [$m^4/s^3$]") # plt.title("") plt.legend(loc='upper right') # plt.tight_layout() plt.show() mng = plt.get_current_fig_manager() mng.window.showMaximized() get_current_fig_manager().window.raise_()
def plot_count_dinucleotide_by_type(df, time): grouped = df.groupby(["Degree", "Di_nucleotide", "Replica", "Type"]).size().reset_index(name="Count") sns.set(style="ticks") nuc_order = list(set(grouped['Di_nucleotide'])) grid = sns.FacetGrid(grouped, col="Degree", row="Replica", row_order=['A', 'B'], hue="Type", palette="Set2") grid.map(sns.barplot, "Di_nucleotide", "Count", order=nuc_order) sns.plt.legend(loc='upper left', bbox_to_anchor=(-1.35, 1.5)) pylab.get_current_fig_manager().window.showMaximized() grid.fig.suptitle("Count by mutation type Passage {}".format(time), fontsize=18) plt.show()
def plot_all_pressures(self): conn = psycopg2.connect("dbname=will user=levlab host=levlabserver2.stanford.edu") cur = conn.cursor() sensor_query = '''SELECT {0}.name FROM {0} WHERE {0}.fault=FALSE and {0}.unit='Torr';'''.format(GAUGE_TABLE) cur.execute(sensor_query) sensors = cur.fetchall() databysensors = dict() notesbysensors = dict() for sensor in sensors: sensorname = sensor[0] data_query = '''SELECT {0}.time, {0}.value FROM {0}, {1} WHERE {0}.value > 0 and {0}.id = {1}.id and {1}.name = %s and {1}.unit='Torr' and {0}.time > %s;'''.format(PRESSURES_TABLE, GAUGE_TABLE) annotate_query = '''SELECT {0}.note, {0}.time, {0}.pressure FROM {0}, {1} WHERE {1}.name = %s and {0}.sensorid={1}.id'''.format(ANNOTATIONS_TABLE, GAUGE_TABLE) cur.execute(data_query, (sensorname, STARTDATETIME,)) databysensors[sensorname]=cur.fetchall() cur.execute(annotate_query, (sensorname,)) notesbysensors[sensorname]=cur.fetchall() cur.close() conn.close() fig = pylab.figure(figsize=(12,6)) ax1 = fig.add_subplot(111) ax1.set_yscale('log') for sensor in sensors: x = [data[0] for data in databysensors[sensor[0]]] y = [data[1] for data in databysensors[sensor[0]]] ax1.plot_date(x, y,'-', label = sensor[0]) for annotation in notesbysensors[sensor[0]]: print(annotation) ax1.annotate(annotation[0], (annotation[1], annotation[2]), xytext=(-50, 30), textcoords='offset points',arrowprops=dict(arrowstyle="->"), bbox=dict(boxstyle="round", fc="0.8")) ax1.fmt_xdate = matplotlib.dates.DateFormatter('%H%M') ax1.legend(loc = 'lower left') ax1.set_xlabel('Time') ax1.set_ylabel('Pressure / Torr') # ax1.set_title('Bake Data') # ax2 = fig.add_subplot(122) # chamber=sensors[chamberindex] # chambername=chamber[chamberindex] # x = [data[0] for data in databysensors[chambername]] # y = [data[1] for data in databysensors[chambername]] # ax2.plot_date(x, y,'-', label = chambername) # ax2.ticklabel_format(style='sci',scilimits=(0,0),axis='y') # ax2.fmt_xdate = matplotlib.dates.DateFormatter('%H%M') # ax2.legend(loc = 'upper left') # ax2.set_xlabel('Time') # ax2.set_ylabel('Pressure / Torr') # ax2.set_title('Bake Data') fig.autofmt_xdate() # print(x) # if show: wm = pylab.get_current_fig_manager() # wm.window.wm_geometry("1920x1080+50+50") wm.window.state('zoomed') if self.showplot: pylab.show() else: pylab.savefig('Z:\\Experiments\\Atomic Chip Microscopy\\Bakeout\\gaugeview.png')
def __init__ (self,mc): self.count = 50 self.scale = 3 self.mc = mc self.u = mc.u self.H = [] self.pause = False self.help = 1 self.arrow = True self.usage=['h - show/hide help', 'a - narrow bars', 'z - extend bars', 'x - narrow x ticks', 'c - extend x ticks', 'e - show arrow', 'q - pause', 'esc - exit'] self.figure = pyplot.figure() self.ax = self.figure.add_subplot(111) # (211) self.histogram() self.manager = get_current_fig_manager() def update(*args): self.ax.clear() self.histogram() self.manager.canvas.draw() if self.pause: return False return True def key_press(event): print 'press', event.key if event.key=='a': self.count /=0.9 if event.key=='z': self.count /=1.1 if event.key=='c': self.scale +=1 if event.key=='x' and self.scale !=1: self.scale -=1 if event.key=='e': self.arrow = not self.arrow if event.key=='h': if self.help == 2: self.help = 0 else: self.help += 1 if event.key=='q': if self.pause: self.pause = False gobject.idle_add(update) else: self.pause = True if event.key=='escape': gtk.main_quit() self.figure.canvas.mpl_connect('key_press_event', key_press) gobject.idle_add(update) pyplot.show()
def onmotion(self,event): if pyl.get_current_fig_manager().toolbar._active==None: if self.press==None: return (x0,y0,xpress,ypress,k,h,button)=self.press if button==1 and pyl.get_current_fig_manager().toolbar._active==None: dx=event.xdata-xpress dy=event.ydata-ypress self.patchList[k].center=(x0+dx,y0+dy) self.patchList[k].width=h*self.getWidthAdjust(event.ydata) #self.patchList[k].width=self.patchRads[k]*self.getWidthAdjust(event.ydata) self.patchList[k].figure.canvas.draw() elif button==3 and pyl.get_current_fig_manager().toolbar._active==None: dx=event.xdata-xpress multi=max((1.+dx/self.image.shape[1]*5.),1.e-3) self.patchList[k].height=h*multi self.patchList[k].width=h*multi*self.getWidthAdjust(y0) self.patchList[k].figure.canvas.draw()