def hinton(W, maxWeight=None): """ Draws a Hinton diagram for visualizing a weight matrix. Temporarily disables matplotlib interactive mode if it is on, otherwise this takes forever. """ reenable = False if P.isinteractive(): P.ioff() P.clf() height, width = W.shape if not maxWeight: maxWeight = 2**np.ceil(np.log(np.max(np.abs(W))) / np.log(2)) P.fill(np.array([0, width, width, 0]), np.array([0, 0, height, height]), 'gray') P.axis('off') P.axis('equal') for x in range(width): for y in range(height): w = W[y, x] weight = w / maxWeight if w > 0 else min(1, -w / maxWeight) color = 'white' if w > 0 else 'black' _blob((x + 1) - 0.5, height - (y + 1) + 0.5, weight, color) if reenable: P.ion() P.show()
def ploterrorbars(x, y, dy, ymax=None, color='k', xfac=1, ax=None, xlog=False, **other): if ax is None: ax = pylab.gca() if ymax is None: ymin = y - dy ymax = y + dy else: ymin = dy ymax = ymax if xlog: dxlog = 0.005 * xfac * (np.log10(xlim()[1]) - np.log10(xlim()[0])) print('dxlog', dxlog) dx = dxlog * x / np.log10(np.e) else: dx = 0.005 * xfac * (xlim()[1] - xlim()[0]) xtemp = xlim() ytemp = ylim() pylab.ioff() for i in range(len(x)): ax.plot([x[i], x[i]], [ymin[i], ymax[i]], color=color, **other) ax.plot([x[i] - dx, x[i] + dx], [ymax[i], ymax[i]], color=color, **other) ax.plot([x[i] - dx, x[i] + dx], [ymin[i], ymin[i]], color=color, **other) if pylab.isinteractive(): pylab.ion() pylab.show() ax.set_xlim(xtemp[0], xtemp[1]) ax.set_ylim(ytemp[0], ytemp[1])
def hinton(W, maxWeight=None): """ Source: http://wiki.scipy.org/Cookbook/Matplotlib/HintonDiagrams Draws a Hinton diagram for visualizing a weight matrix. Temporarily disables matplotlib interactive mode if it is on, otherwise this takes forever. """ reenable = False if pl.isinteractive(): pl.ioff() pl.clf() height, width = W.shape if not maxWeight: maxWeight = 2**np.ceil(np.log(np.max(np.abs(W)))/np.log(2)) pl.fill(np.array([0,width,width,0]),np.array([0,0,height,height]),'gray') pl.axis('off') pl.axis('equal') for x in xrange(width): for y in xrange(height): _x = x+1 _y = y+1 w = W[y,x] if w > 0: _blob(_x - 0.5, height - _y + 0.5, min(1,w/maxWeight),'white') elif w < 0: _blob(_x - 0.5, height - _y + 0.5, min(1,-w/maxWeight),'black') if reenable: pl.ion() pl.show()
def hinton(W, maxWeight=None): """ Draws a Hinton diagram for visualizing a weight matrix. Temporarily disables matplotlib interactive mode if it is on, otherwise this takes forever. """ import pylab reenable = False if pylab.isinteractive(): pylab.ioff() pylab.clf() height, width = W.shape if not maxWeight: maxWeight = 2**np.ceil(np.log(np.max(np.abs(W))) / np.log(2)) pylab.fill(np.array([0, width, width, 0]), np.array([0, 0, height, height]), 'gray') pylab.axis('off') pylab.axis('equal') for x in range(width): for y in range(height): _x = x + 1 _y = y + 1 w = W[y, x] if w > 0: _blob(_x - 0.5, height - _y + 0.5, min(1, w / maxWeight), 'white') elif w < 0: _blob(_x - 0.5, height - _y + 0.5, min(1, -w / maxWeight), 'black') if reenable: pylab.ion() pylab.show()
def hinton(W,filename="hinton.pdf", maxWeight=None): """ Draws a Hinton diagram for visualizing a weight matrix. Temporarily disables matplotlib interactive mode if it is on, otherwise this takes forever. """ reenable = False if P.isinteractive(): P.ioff() P.clf() ax=P.subplot(111) height, width = W.shape if not maxWeight: maxWeight = 2**np.ceil(np.log(np.max(np.abs(W)))/np.log(2)) P.fill(np.array([0,width,width,0]),np.array([0,0,height,height]),'gray') P.axis('off') #P.axis('equal') ax.set_yticklabels(['25','20','15','10','5','0']) for x in xrange(width): for y in xrange(height): _x = x+1 _y = y+1 w = W[y,x] if w > 0: _blob(_x - 0.5, height - _y + 0.5, min(1,w/maxWeight),'white') elif w < 0: _blob(_x - 0.5, height - _y + 0.5, min(1,-w/maxWeight),'black') if reenable: P.ion() P.title(filename) P.savefig(filename)
def __init__(self, parent=None, pid=None, figure_or_canvas=None): super().__init__(parent, pid, 'plot') self.fileMenu = self.menuBar().addMenu("&File") self.addMenuItem(self.fileMenu, 'Open...', self.openFigure) self.addMenuItem(self.fileMenu, 'Save As...', self.saveFigure) self.addMenuItem(self.fileMenu, 'Close', self.close_me_from_menu, icon='cross.png') self.addMenuItem(self.fileMenu, 'Close Others', self.close_others) self.editMenu = CheckMenu("&Edit", self.menuBar()) self.menuBar().addMenu(self.editMenu) self.addMenuItem(self.editMenu, 'Copy', self.copyToCb, statusTip="Copy to Clipboard", icon='page_copy.png') self.viewMenu = CheckMenu("&View", self.menuBar()) self.menuBar().addMenu(self.viewMenu) self.addMenuItem(self.viewMenu, 'Refresh', self.refresh, statusTip="Refresh the plot", icon='update.png') self.addMenuItem(self.viewMenu, 'Grid', self.grid, statusTip="Show/hide grid", icon='layer_grid.png') self.addMenuItem( self.viewMenu, 'Tight', self.tight, statusTip="Adjust the padding between and around subplots", icon='canvas_size.png') self.addMenuItem(self.viewMenu, 'Interactive', self.toggle_interactive, checkcall=lambda: pylab.isinteractive()) self.addBaseMenu() if hasattr(figure_or_canvas, 'canvas'): self.figure = figure_or_canvas self.canvas = figure_or_canvas.canvas else: self.figure = figure_or_canvas.figure self.canvas = figure_or_canvas self.setCentralWidget(self.canvas) self.nav = NavigationToolbar(self.canvas, self) self.nav.setIconSize(QtCore.QSize(20, 20)) self.addToolBar(self.nav) self.statusBar().hide()
def hinton(W, out_file=None, maxWeight=None): """ Draws a Hinton diagram for visualizing a weight matrix. Temporarily disables matplotlib interactive mode if it is on, otherwise this takes forever. """ reenable = False if P.isinteractive(): P.ioff() P.clf() height, width = W.shape if not maxWeight: maxWeight = 2**N.ceil(N.log(N.max(N.abs(W)))/N.log(2)) P.gca().set_position([0, 0, 1, 1]) P.fill(N.array([0,width,width,0]),N.array([0,0,height,height]),'gray') P.axis('off') P.axis('equal') for x in xrange(width): for y in xrange(height): _x = x+1 _y = y+1 w = W[y,x] if w > 0: _blob(_x - 0.5, height - _y + 0.5, min(1,w/maxWeight),'white') elif w < 0: _blob(_x - 0.5, height - _y + 0.5, min(1,-w/maxWeight),'black') if reenable: P.ion() #P.show() if out_file: #P.savefig(out_file, format='png', bbox_inches='tight', pad_inches=0) fig = P.gcf() fig.subplots_adjust() fig.savefig(out_file)
def hinton(W, filename="hinton.pdf", maxWeight=None): """ Draws a Hinton diagram for visualizing a weight matrix. Temporarily disables matplotlib interactive mode if it is on, otherwise this takes forever. """ reenable = False if P.isinteractive(): P.ioff() P.clf() ax = P.subplot(111) height, width = W.shape if not maxWeight: maxWeight = 2**np.ceil(np.log(np.max(np.abs(W))) / np.log(2)) P.fill(np.array([0, width, width, 0]), np.array([0, 0, height, height]), 'gray') P.axis('off') #P.axis('equal') ax.set_yticklabels(['25', '20', '15', '10', '5', '0']) for x in xrange(width): for y in xrange(height): _x = x + 1 _y = y + 1 w = W[y, x] if w > 0: _blob(_x - 0.5, height - _y + 0.5, min(1, w / maxWeight), 'white') elif w < 0: _blob(_x - 0.5, height - _y + 0.5, min(1, -w / maxWeight), 'black') if reenable: P.ion() P.title(filename) P.savefig(filename)
def __init__(self, features, **kwargs): self.features = features self.fc_function = None self.lw_function = None wasinteractive = pylab.isinteractive() if wasinteractive: pylab.ioff() self.shapes = [] for i, feature in enumerate(self.features): if isinstance(feature.shape, g.MultiPolygon): self.shapes.append([]) for shape in feature.shape.geoms: x, y = numpy.asarray(shape.exterior)[:, :2].swapaxes(0, 1) self.shapes[-1].append(pylab.fill(x, y, **kwargs)[0]) if isinstance(feature.shape, g.Polygon): x, y = numpy.asarray(feature.shape.exterior)[:, :2].swapaxes( 0, 1) self.shapes.append(pylab.fill(x, y, **kwargs)) elif isinstance(feature.shape, g.MultiLineString): self.shapes.append([]) for shape in feature.shape.geoms: x, y = numpy.asarray(shape)[:, :2].swapaxes(0, 1) self.shapes[-1].append(pylab.plot(x, y, **kwargs)[0]) elif isinstance(feature.shape, g.LineString): x, y = numpy.asarray(feature.shape).swapaxes(0, 1) self.shapes.append(pylab.plot(x, y, **kwargs)) elif isinstance(feature.shape, g.Point): x, y = feature.shape.x, feature.shape.y self.shapes.append(pylab.plot([x], [y], **kwargs)[0]) pylab.axis('equal') if wasinteractive: pylab.ion() pylab.draw()
def hinton(W, name, maxWeight=None): """ Draws a Hinton diagram for visualizing a weight matrix. Temporarily disables matplotlib interactive mode if it is on, otherwise this takes forever. """ reenable = False if P.isinteractive(): P.ioff() P.clf() height, width = W.shape if not maxWeight: maxWeight = 2**N.ceil(N.log(N.max(N.abs(W))) / N.log(2)) P.fill(N.array([0, width, width, 0]), N.array([0, 0, height, height]), 'gray') P.axis('off') P.axis('equal') for x in range(width): for y in range(height): _x = x + 1 _y = y + 1 w = W[y, x] if w > 0: _blob(_x - 0.5, height - _y + 0.5, min(1, w / maxWeight), 'white') elif w < 0: _blob(_x - 0.5, height - _y + 0.5, min(1, -w / maxWeight), 'black') if reenable: P.ion() P.savefig('hinton' + name + '.png') P.show()
def __call__(self,output_fn,init_time=0,final_time=None,**params): p=ParamOverrides(self,params) if final_time is None: final_time=topo.sim.time() attrs = p.attrib_names if len(p.attrib_names)>0 else output_fn.attrib_names for a in attrs: pylab.figure(figsize=(6,4)) isint=pylab.isinteractive() pylab.ioff() pylab.grid(True) ylabel=p.ylabel pylab.ylabel(a+" "+ylabel) pylab.xlabel('Iteration Number') coords = p.units if len(p.units)>0 else output_fn.units for coord in coords: y_data=[y for (x,y) in output_fn.values[a][coord]] x_data=[x for (x,y) in output_fn.values[a][coord]] if p.raw==True: plot_data=zip(x_data,y_data) pylab.save(normalize_path(p.filename+a+'(%.2f, %.2f)' %(coord[0], coord[1])),plot_data,fmt='%.6f', delimiter=',') pylab.plot(x_data,y_data, label='Unit (%.2f, %.2f)' %(coord[0], coord[1])) (ymin,ymax)=p.ybounds pylab.axis(xmin=init_time,xmax=final_time,ymin=ymin,ymax=ymax) if isint: pylab.ion() pylab.legend(loc=0) p.title=topo.sim.name+': '+a p.filename_suffix=a self._generate_figure(p)
def hinton(W, max_weight=None, names=(names, worst_names)): """ Draws a Hinton diagram for visualizing a weight matrix. Temporarily disables matplotlib interactive mode if it is on, otherwise this takes forever. """ reenable = False if P.isinteractive(): P.ioff() P.clf() height, width = W.shape if not max_weight: max_weight = 2**np.ceil(np.log(np.max(np.abs(W)))/np.log(2)) P.fill(np.array([0, width, width, 0]), np.array([0, 0, height, height]), 'gray') P.axis('off') P.axis('equal') cmap = plt.get_cmap('RdYlGn') for x in range(width): if names: plt.text(-0.5, x, names[0][x], fontsize=7, ha='right', va='bottom') plt.text(x, height+0.5, names[1][height-x-1], fontsize=7, va='bottom', rotation='vertical', ha='left') for y in range(height): _x = x+1 _y = y+1 w = W[y, x] if w > 0: _blob(_x - 0.5, height - _y + 0.5, min(1, w/max_weight), color=cmap(w/max_weight)) elif w < 0: _blob(_x - 0.5, height - _y + 0.5, min(1, -w/max_weight), 'black') if reenable: P.ion() P.show()
def graticule(dpar=None,dmer=None,coord=None,local=None,**kwds): """Create a graticule, either on an existing mollweide map or not. Parameters: - dpar, dmer: interval in degrees between meridians and between parallels - coord: the coordinate system of the graticule (make rotation if needed, using coordinate system of the map if it is defined) - local: True if local graticule (no rotation is performed) Return: None """ f = pylab.gcf() wasinteractive = pylab.isinteractive() pylab.ioff() try: if len(f.get_axes()) == 0: ax=PA.HpxMollweideAxes(f,(0.02,0.05,0.96,0.9),coord=coord) f.add_axes(ax) ax.text(0.86,0.05,ax.proj.coordsysstr,fontsize=14, fontweight='bold',transform=ax.transAxes) for ax in f.get_axes(): if isinstance(ax,PA.SphericalProjAxes): ax.graticule(dpar=dpar,dmer=dmer,coord=coord, local=local,**kwds) finally: pylab.draw() if wasinteractive: pylab.ion()
def graticule(dpar=None, dmer=None, coord=None, local=None, **kwds): """Create a graticule, either on an existing mollweide map or not. Parameters: - dpar, dmer: interval in degrees between meridians and between parallels - coord: the coordinate system of the graticule (make rotation if needed, using coordinate system of the map if it is defined) - local: True if local graticule (no rotation is performed) Return: None """ f = pylab.gcf() wasinteractive = pylab.isinteractive() pylab.ioff() try: if len(f.get_axes()) == 0: ax = PA.HpxMollweideAxes(f, (0.02, 0.05, 0.96, 0.9), coord=coord) f.add_axes(ax) ax.text(0.86, 0.05, ax.proj.coordsysstr, fontsize=14, fontweight='bold', transform=ax.transAxes) for ax in f.get_axes(): if isinstance(ax, PA.SphericalProjAxes): ax.graticule(dpar=dpar, dmer=dmer, coord=coord, local=local, **kwds) finally: pylab.draw() if wasinteractive: pylab.ion()
def hinton(self, maxWeight=None): """ Draws a Hinton diagram for visualizing a weight matrix. Temporarily disables matplotlib interactive mode if it is on, otherwise this takes forever. Source: http://wiki.scipy.org/Cookbook/Matplotlib/HintonDiagrams """ reenable = False if P.isinteractive(): P.ioff() P.clf() height, width = self.sigma_w.shape if not maxWeight: maxWeight = 2**np.ceil( np.log(np.max(np.abs(self.sigma_w))) / np.log(2)) P.fill(np.array([0, width, width, 0]), np.array([0, 0, height, height]), 'gray') P.axis('off') P.axis('equal') for x in xrange(width): for y in xrange(height): _x = x + 1 _y = y + 1 w = self.sigma_w[y, x] if w > 0: self._blob(_x - 0.5, height - _y + 0.5, min(1, w / maxWeight), 'white') elif w < 0: self._blob(_x - 0.5, height - _y + 0.5, min(1, -w / maxWeight), 'black') if reenable: P.ion() P.show()
def hinton(W, maxWeight=None): """ Draws a Hinton diagram for visualizing a weight matrix. Temporarily disables matplotlib interactive mode if it is on, otherwise this takes forever. """ reenable = False if P.isinteractive(): P.ioff() P.clf() height, width = W.shape if not maxWeight: maxWeight = 2**N.ceil(N.log(N.max(N.abs(W)))/N.log(2)) P.fill(N.array([0,width,width,0]),N.array([0,0,height,height]),'gray') P.axis('off') P.axis('equal') for x in xrange(width): for y in xrange(height): _x = x+1 _y = y+1 w = W[y,x] if w > 0: _blob(_x - 0.5, height - _y + 0.5, min(1,w/maxWeight),'white') elif w < 0: _blob(_x - 0.5, height - _y + 0.5, min(1,-w/maxWeight),'black') if reenable: P.ion() P.show()
def draw(self, axes=None, loc=2): if axes == None: axes = p.gca() if self.box != None and self.box in axes.artists: del axes.artists[ axes.artists.index(self.box) ] #key_areas = [ mpl.offsetbox.TextArea(k, textprops=self.textprops) for k in self.datadict.keys() ] #val_areas = [ mpl.offsetbox.TextArea(self.datadict[k], textprops=self.textprops) for k in self.datadict.keys() ] key_areas = [ mpl.offsetbox.TextArea(k, textprops=self.textprops) for k in list(self.datadict.keys()) ] val_areas = [ mpl.offsetbox.TextArea(self.datadict[k], textprops=self.textprops) for k in list(self.datadict.keys()) ] key_vpack = mpl.offsetbox.VPacker(children=key_areas, align="left", pad=0, sep=0) val_vpack = mpl.offsetbox.VPacker(children=val_areas, align="right", pad=0, sep=0) hpack = mpl.offsetbox.HPacker(children=[key_vpack, val_vpack], align="top", pad=0,sep=4) globchildren = [] if self.title != None: #titlearea = mpl.offsetbox.TextArea(self.title, textprops=self.titleprops) titlearea = mpl.offsetbox.TextArea(self.title) globchildren.append(titlearea) globchildren.append(hpack) globvpack = mpl.offsetbox.VPacker(children=globchildren, align="center", pad=0, sep=1) self.box = mpl.offsetbox.AnchoredOffsetbox(loc=loc, child=globvpack) self.box.patch.set_facecolor(self.facecolor) self.box.patch.set_edgecolor(self.edgecolor) self.box.patch.set_alpha(self.alpha) axes.add_artist( self.box ) if p.isinteractive(): p.gcf().canvas.draw()
def showslice2(thedata,thelabel,minval,maxval,colormap): theshape=thedata.shape numslices=theshape[0] ysize=theshape[1] xsize=theshape[2] slicesqrt=int(np.ceil(np.sqrt(numslices))) theslice=np.zeros((ysize*slicesqrt,xsize*slicesqrt)) for i in range(0,numslices): ypos=int(i/slicesqrt)*ysize xpos=int(i%slicesqrt)*xsize theslice[ypos:ypos+ysize,xpos:xpos+xsize]=thedata[i,:,:] if P.isinteractive(): P.ioff() P.axis('off') P.axis('equal') P.subplots_adjust(hspace=0.0) P.axes([0,0,1,1], frameon = False) if (colormap==0): thecmap=P.cm.gray else: mycmdata1 = { 'red' : ((0., 0., 0.), (0.5, 1.0, 0.0), (1., 1., 1.)), 'green': ((0., 0., 0.), (0.5, 1.0, 1.0), (1., 0., 0.)), 'blue' : ((0., 0., 0.), (0.5, 1.0, 0.0), (1., 0., 0.)) } thecmap = P.matplotlib.colors.LinearSegmentedColormap('mycm', mycmdata1) #thecmap=P.cm.spectral theimptr = P.imshow(theslice, vmin=minval, vmax=maxval, interpolation='nearest', label=thelabel, aspect='equal', cmap=thecmap) #P.colorbar() return()
def saveHintonDiagram(W, directory): maxWeight = None #print "Weight: ", W """ Draws a Hinton diagram for visualizing a weight matrix. Temporarily disables matplotlib interactive mode if it is on, otherwise this takes forever. """ reenable = False if pylab.isinteractive(): pylab.ioff() pylab.clf() height, width = W.shape if not maxWeight: maxWeight = 2**numpy.ceil(numpy.log(numpy.max(numpy.abs(W)))/numpy.log(2)) pylab.fill(numpy.array([0,width,width,0]),numpy.array([0,0,height,height]),'gray') pylab.axis('off') pylab.axis('equal') for x in xrange(width): for y in xrange(height): _x = x+1 _y = y+1 w = W[y,x] if w > 0: _blob(_x - 0.5, height - _y + 0.5, min(1,w/maxWeight),'white') elif w < 0: _blob(_x - 0.5, height - _y + 0.5, min(1,-w/maxWeight),'black') if reenable: pylab.ion() #pylab.show() pylab.savefig(directory)
def __call__(self,**params): p=ParamOverrides(self,params) sheet = p.sheet for coordinate in p.coords: i_value,j_value=sheet.sheet2matrixidx(coordinate[0],coordinate[1]) pylab.figure(figsize=(7,7)) isint=pylab.isinteractive() pylab.ioff() pylab.ylabel('Response',fontsize='large') pylab.xlabel('%s (%s)' % (p.x_axis.capitalize(),p.unit),fontsize='large') pylab.title('Sheet %s, coordinate(x,y)=(%0.3f,%0.3f) at time %s' % (sheet.name,coordinate[0],coordinate[1],topo.sim.timestr())) p.title='%s: %s Tuning Curve' % (topo.sim.name,p.x_axis.capitalize()) self.first_curve=True for curve_label in sorted(sheet.curve_dict[p.x_axis].keys()): x_values,y_values,ticks=self._curve_values(i_value,j_value,sheet.curve_dict[p.x_axis][curve_label]) x_tick_values,ticks = self._reduce_ticks(ticks) labels = [self._format_x_tick_label(x) for x in ticks] pylab.xticks(x_tick_values, labels,fontsize='large') pylab.yticks(fontsize='large') p.plot_type(x_values, y_values, label=curve_label,lw=3.0) self.first_curve=False if isint: pylab.ion() if p.legend: pylab.legend(loc=2) self._generate_figure(p)
def plot(self): fig = self._doPlot() if not pylab.isinteractive(): pylab.show() else: pylab.draw() pylab.close(fig)
def showlines(vs, size=(4.1,2), **kwargs): # {{{ ''' Plot line plots of a list of 1D variables on the same plot. Parameters ---------- v : list of :class:`Var` The variables to plot. Should all have 1 non-degenerate axis. ''' Z = [v.squeeze() for v in vs] for z in Z: assert z.naxes == 1, 'Variable %s has %d non-generate axes; must have 1.' % (z.name, z.naxes) fig = kwargs.pop('fig', None) ax = wr.AxesWrapper(size=size) ydat = [] for v in vs: vplot(v, axes=ax, label=v.name, ) ydat.append(ax.find_plot(wr.Plot).plot_args[1]) ylim = (np.min([np.min(y) for y in ydat]), np.max([np.max(y) for y in ydat])) kwargs.update(dict(ylim=ylim)) ax.legend(loc='best', frameon=False) ax.setp(**kwargs) import pylab as pyl if pyl.isinteractive(): ax.render(fig) return ax
def read_text_pyfusion(files, target='^Shot .*', ph_dtype=None, plot=pl.isinteractive(), ms=100, hold=0, debug=0, quiet=1, exception = Exception): """ Accepts a file or a list of files, returns a list of structured arrays See merge ds_list to merge and convert types (float -> pyfusion.prec_med """ st = seconds(); last_update=seconds() file_list = files if len(np.shape(files)) == 0: file_list = [file_list] f='f8' if ph_dtype == None: ph_dtype = [('p12',f),('p23',f),('p34',f),('p45',f),('p56',f)] #ph_dtype = [('p12',f)] ds_list =[] comment_list =[] count = 0 for (i,filename) in enumerate(file_list): if seconds() - last_update > 30: last_update = seconds() print('reading {n}/{t}: {f}' .format(f=filename, n=i, t=len(file_list))) try: if pl.is_string_like(target): skip = 1+find_data(filename, target,debug=debug) else: skip = target if quiet == 0: print('{t:.1f} sec, loading data from line {s} of {f}' .format(t = seconds()-st, s=skip, f=filename)) # this little bit to determine layout of data # very inefficient to read twice, but in a hurry! txt = np.loadtxt(fname=filename, skiprows=skip-1, dtype=str, delimiter='FOOBARWOOBAR') header_toks = txt[0].split() # is the first character of the 2nd last a digit? if header_toks[-2][0] in '0123456789': if pyfusion.VERBOSE > 0: print('found new header including number of phases') n_phases = int(header_toks[-2]) ph_dtype = [('p{n}{np1}'.format(n=n,np1=n+1), f) for n in range(n_phases)] if 'frlow' in header_toks: # add the two extra fields fs_dtype= [ ('shot','i8'), ('t_mid','f8'), ('_binary_svs','i8'), ('freq','f8'), ('amp', 'f8'), ('a12','f8'), ('p', 'f8'), ('H','f8'), ('frlow','f8'), ('frhigh', 'f8'),('phases',ph_dtype)] else: fs_dtype= [ ('shot','i8'), ('t_mid','f8'), ('_binary_svs','i8'), ('freq','f8'), ('amp', 'f8'), ('a12','f8'), ('p', 'f8'), ('H','f8'), ('phases',ph_dtype)] ds_list.append( np.loadtxt(fname=filename, skiprows = skip, dtype= fs_dtype) ) count += 1 comment_list.append(filename) except ValueError, info: print('Conversion error while reading {f} with loadtxt - {info}'.format(f=filename, info=info))
def showcol(vs, size=(4.1,2), **kwargs): # {{{ ''' Plot variable, showing a contour plot for 2d variables or a line plot for 1d variables. Parameters ---------- v : list of lists of :class:`Var` The variables to plot. Should have either 1 or 2 non-degenerate axes. Notes ----- This function is intended as the simplest way to display the contents of a variable, choosing appropriate parameter values as automatically as possible. ''' Z = [v.squeeze() for v in vs] assert Z[0].naxes in [1, 2], 'Variables %s has %d non-generate axes; must have 1 or 2.' % (Z.name, Z.naxes) for z in Z[1:]: assert Z[0].naxes == z.naxes, 'All variables must have the same number of non-generate dimensions' #assert all([a == b for a, b in zip(Z[0].axes, z.axes)]) fig = kwargs.pop('fig', None) if Z[0].naxes == 1: axs = [] ydat = [] for v in vs: lblx = (v is vs[-1]) ax = vplot(v, lblx = lblx, **kwargs) ax.size = size axs.append([ax]) ydat.append(ax.find_plot(wr.Plot).plot_args[1]) Ax = wr.grid(axs) ylim = (np.min([np.min(y) for y in ydat]), np.max([np.max(y) for y in ydat])) Ax.setp(ylim = ylim, children=True) elif Z[0].naxes == 2: axs = [] for v in vs: lblx = (v is vs[-1]) ax = vcontour(v, lblx = lblx, **kwargs) ax.size = size axs.append([ax]) Ax = wr.grid(axs) cbar = kwargs.pop('colorbar', dict(orientation='vertical')) cf = Ax.axes[0].find_plot(wr.Contourf) if cbar and cf is not None: Ax = wr.colorbar(Ax, cf, **cbar) import pylab as pyl if pyl.isinteractive(): Ax.render(fig) return Ax
def refresh(self): for i, f in enumerate(self.features): for s in self.shapes[i]: if self.fc_function and hasattr(s, 'set_fc'): s.set_fc(self.fc_function(f)) if self.lw_function and hasattr(s, 'set_lw'): s.set_lw(self.lw_function(f)) if pylab.isinteractive(): pylab.draw()
def plot_rectangular(x, y, x_label=None, y_label=None, title=None, show_legend=True, axis='tight', ax=None, *args, **kwargs): ''' plots rectangular data and optionally label axes. Parameters ------------ z : array-like, of complex data data to plot x_label : string x-axis label y_label : string y-axis label title : string plot title show_legend : Boolean controls the drawing of the legend ax : :class:`matplotlib.axes.AxesSubplot` object axes to draw on *args,**kwargs : passed to pylab.plot ''' if ax is None: ax = plb.gca() my_plot = ax.plot(x, y, *args, **kwargs) if x_label is not None: ax.set_xlabel(x_label) if y_label is not None: ax.set_ylabel(y_label) if title is not None: ax.set_title(title) if show_legend: # only show legend if they provide a label if 'label' in kwargs: ax.legend() if axis is not None: ax.autoscale(True, 'x', True) ax.autoscale(True, 'y', False) if plb.isinteractive(): plb.draw() return my_plot
def showslice(theslice): if P.isinteractive(): P.ioff() P.axis('off') P.axis('equal') P.axis('tight') P.imshow(theslice, interpolation='nearest', aspect='equal', cmap=P.cm.gray) P.colorbar() return()
def plot_uncertainty_bounds_s(self, multiplier=200, *args, **kwargs): ''' Plots complex uncertainty bounds plot on smith chart. This function plots the complex uncertainty of a NetworkSet as circles on the smith chart. At each frequency a circle with radii proportional to the complex standard deviation of the set at that frequency is drawn. Due to the fact that the `markersize` argument is in pixels, the radii can scaled by the input argument `multiplier`. default kwargs are { 'marker':'o', 'color':'b', 'mew':0, 'ls':'', 'alpha':.1, 'label':None, } Parameters ------------- multipliter : float controls the circle sizes, by multiples of the standard deviation. ''' default_kwargs = { 'marker': 'o', 'color': 'b', 'mew': 0, 'ls': '', 'alpha': .1, 'label': None, } default_kwargs.update(**kwargs) if plb.isinteractive(): was_interactive = True plb.interactive(0) else: was_interactive = False [ self.mean_s[k].plot_s_smith(*args, ms=self.std_s[k].s_mag * multiplier, **default_kwargs) for k in range(len(self[0])) ] if was_interactive: plb.interactive(1) plb.draw() plb.show()
def plot_polar( theta, r, x_label=None, y_label=None, title=None, show_legend=True, axis_equal=False, ax=None, *args, **kwargs ): """ plots polar data on a polar plot and optionally label axes. Parameters ------------ theta : array-like data to plot r : array-like x_label : string x-axis label y_label : string y-axis label title : string plot title show_legend : Boolean controls the drawing of the legend ax : :class:`matplotlib.axes.AxesSubplot` object axes to draw on *args,**kwargs : passed to pylab.plot See Also ---------- plot_rectangular : plots rectangular data plot_complex_rectangular : plot complex data on complex plane plot_polar : plot polar data plot_complex_polar : plot complex data on polar plane plot_smith : plot complex data on smith chart """ if ax is None: ax = plb.gca(polar=True) ax.plot(theta, r, *args, **kwargs) if x_label is not None: ax.set_xlabel(x_label) if y_label is not None: ax.set_ylabel(y_label) if title is not None: ax.set_title(title) if show_legend: # only show legend if they provide a label if "label" in kwargs: ax.legend() if axis_equal: ax.axis("equal") if plb.isinteractive(): plb.draw()
def plot_smith(z, smith_r=1, chart_type='z', x_label='Real', y_label='Imaginary', title='Complex Plane', show_legend=True, axis='equal', ax=None, force_chart = False, *args, **kwargs): ''' plot complex data on smith chart Parameters ------------ z : array-like, of complex data data to plot smith_r : number radius of smith chart chart_type : ['z','y'] Contour type for chart. * *'z'* : lines of constant impedance * *'y'* : lines of constant admittance x_label : string x-axis label y_label : string y-axis label title : string plot title show_legend : Boolean controls the drawing of the legend axis_equal: Boolean sets axis to be equal increments (calls axis('equal')) force_chart : Boolean forces the re-drawing of smith chart ax : :class:`matplotlib.axes.AxesSubplot` object axes to draw on *args,**kwargs : passed to pylab.plot See Also ---------- plot_rectangular : plots rectangular data plot_complex_rectangular : plot complex data on complex plane plot_polar : plot polar data plot_complex_polar : plot complex data on polar plane plot_smith : plot complex data on smith chart ''' if ax is None: ax = plb.gca() # test if smith chart is already drawn if not force_chart: if len(ax.patches) == 0: smith(ax=ax, smithR = smith_r, chart_type=chart_type) plot_complex_rectangular(z, x_label=x_label, y_label=y_label, title=title, show_legend=show_legend, axis=axis, ax=ax, *args, **kwargs) ax.axis(smith_r*npy.array([-1.1, 1.1, -1.1, 1.1])) if plb.isinteractive(): plb.draw()
def plot_polar(theta, r, x_label=None, y_label=None, title=None, show_legend=True, axis_equal=False, ax=None, *args, **kwargs): ''' plots polar data on a polar plot and optionally label axes. Parameters ------------ theta : array-like data to plot r : array-like x_label : string x-axis label y_label : string y-axis label title : string plot title show_legend : Boolean controls the drawing of the legend ax : :class:`matplotlib.axes.AxesSubplot` object axes to draw on *args,**kwargs : passed to pylab.plot See Also ---------- plot_rectangular : plots rectangular data plot_complex_rectangular : plot complex data on complex plane plot_polar : plot polar data plot_complex_polar : plot complex data on polar plane plot_smith : plot complex data on smith chart ''' if ax is None: ax = plb.gca(polar=True) ax.plot(theta, r, *args, **kwargs) if x_label is not None: ax.set_xlabel(x_label) if y_label is not None: ax.set_ylabel(y_label) if title is not None: ax.set_title(title) if show_legend: # only show legend if they provide a label if 'label' in kwargs: ax.legend() if axis_equal: ax.axis('equal') if plb.isinteractive(): plb.draw()
def plot(self): """ Draw this layout to a matplotlib canvas. """ fig = self._doPlot() if not pylab.isinteractive(): pylab.show() else: pylab.draw() pylab.close(fig)
def showlines(vs, fmts=None, labels=None, size=(4.1, 2), lblx=True, lbly=True, **kwargs): # {{{ ''' Produce line plots of a list of 1D variables on a single figure. Parameters ---------- vs : list of :class:`Var` The variables to plot. Should all have 1 non-degenerate axis. ''' Z = [v.squeeze() for v in vs] for z in Z: assert z.naxes == 1, 'Variable %s has %d non-generate axes; must have 1.' % ( z.name, z.naxes) fig = kwargs.pop('fig', None) ax = wr.AxesWrapper(size=size) ydat = [] for i, v in enumerate(vs): if fmts is None: fmt = '' elif hasattr(fmts, '__len__'): fmt = fmts[i] else: fmt = fmts if labels is None: lbl = v.name elif hasattr(labels, '__len__'): lbl = labels[i] else: lbl = labels vplot(v, axes=ax, fmt=fmt, label=lbl) ydat.append(ax.find_plot(wr.Plot).plot_args[1]) #ylim = (np.min([np.min(y) for y in ydat]), np.max([np.max(y) for y in ydat])) #kwargs.update(dict(ylim=ylim)) kwleg = kwargs.pop('legend', dict(loc='best', frameon=False)) ax.legend(**kwleg) ax.setp(**kwargs) import pylab as pyl if pyl.isinteractive(): ax.render(fig) return ax
def draw_selection(self, lbl, replace=True): """ draw a given subset """ if (lbl not in self._draws) | (replace is True): sample = self.selections[lbl] self._draws[lbl] = sample.draw(self.x, self.y, ax=self.axes) if plt.isinteractive(): self.draw() return sample, self._draws[lbl]
def plot_uncertainty_bounds_s(self, multiplier =200, *args, **kwargs): ''' Plots complex uncertainty bounds plot on smith chart. This function plots the complex uncertainty of a NetworkSet as circles on the smith chart. At each frequency a circle with radii proportional to the complex standard deviation of the set at that frequency is drawn. Due to the fact that the `markersize` argument is in pixels, the radii can scaled by the input argument `multiplier`. default kwargs are { 'marker':'o', 'color':'b', 'mew':0, 'ls':'', 'alpha':.1, 'label':None, } Parameters ------------- multipliter : float controls the circle sizes, by multiples of the standard deviation. ''' default_kwargs = { 'marker':'o', 'color':'b', 'mew':0, 'ls':'', 'alpha':.1, 'label':None, } default_kwargs.update(**kwargs) if plb.isinteractive(): was_interactive = True plb.interactive(0) else: was_interactive = False [self.mean_s[k].plot_s_smith(*args, ms = self.std_s[k].s_mag*multiplier, **default_kwargs) for k in range(len(self[0]))] if was_interactive: plb.interactive(1) plb.draw() plb.show()
def wrapper(*args, **kwds): interactive_mode = P.isinteractive() if interactive_mode: #logging.debug('Turning pylab interactive off.') P.ioff() try: return fn(*args, **kwds) finally: if interactive_mode: #logging.debug('Turning pylab interactive on.') P.ion()
def __call__(self, recalc_range=False): if recalc_range: self.maxvalue = max((self.f(c) for c in self.polygons.iterkeys())) self.minvalue = min((self.f(c) for c in self.polygons.iterkeys())) for cell, poly in self.polygons.iteritems(): v = self.f(cell) c = self.cmap( (v - self.minvalue) / (self.maxvalue - self.minvalue)) poly.set_fc(c) if pylab.isinteractive(): pylab.draw()
def delgraticules(): f = pylab.gcf() wasinteractive = pylab.isinteractive() pylab.ioff() try: for ax in f.get_axes(): if isinstance(ax,PA.SphericalProjAxes): ax.delgraticules() finally: pylab.draw() if wasinteractive: pylab.ion()
def Trace_diag(LH,Lna,LT,LHR,Lair,fignum) : figure(fignum) if isinteractive() : ioff() lna_H,lH_H=Return_Hs(LH,Lna) Plotlines(lna_H,lH_H,lineprops) lna_T,lH_T=Return_Ts(LT,Lna) Plotlines(lna_T,lH_T,lineprops) lna_HR,lH_HR=Return_HRs(Lna,LHR) PlotHR(lna_HR,lH_HR,LHR,lineprops_HR) Ttick=Transf_xy(Lna[0],array(lH_T[0:-1:2]))[1] Tlabel=map(str,LT) yticks(Ttick,Tlabel) xlabel(r'$\rm{Teneur\ en\ eau\ (na)}\ [\ g_{H_2O}\ /\ g_{AS}\ ]$') ylabel(r'$\rm{Temp\'erature\ (T)}\ [\ ^{\circ}C\ ]$') title("Diagramme de l'air humide") if not(isinteractive()) : ion() axis([x1,x3,y1,y3]) setp(gca(),autoscale_on=False) draw()
def delgraticules(): f = pylab.gcf() wasinteractive = pylab.isinteractive() pylab.ioff() try: for ax in f.get_axes(): if isinstance(ax, PA.SphericalProjAxes): ax.delgraticules() finally: pylab.draw() if wasinteractive: pylab.ion()
def __init__(self, cells, value_function, cmap=pylab.cm.jet, hold=True, vmin=None, vmax=None, **kwargs): self.cells = cells self.__f = value_function was_interactive = pylab.isinteractive() if was_interactive: pylab.ioff() geos = [] self.maxvalue = -1e300 if vmax is None else vmax self.minvalue = 1e300 if vmin is None else vmin self.polygons = {} # Generate image array, which is filled with generated values from self.f self._A = [] for cell in cells: shape = geoms[cell] if hasattr(shape, "geoms"): shapes = shape.geoms else: shapes = [shape] value = self.f(cell) self._A.append(value) if vmax is None: self.maxvalue = max(value, self.maxvalue) if vmin is None: self.minvalue = min(value, self.minvalue) for s in shapes: geos.append((cell, s, value)) if self.minvalue >= self.maxvalue: self.minvalue = self.maxvalue - 1 for cell, s, v in geos: if hasattr(s, "exterior"): s = s.exterior c = cmap( float(v - self.minvalue) / float(self.maxvalue - self.minvalue)) a = pylab.asarray(s) self.polygons[cell] = pylab.fill(a[:, 0], a[:, 1], fc=c, hold=hold, **kwargs)[0] hold = 1 pylab.axis('equal') norm = pylab.matplotlib.colors.Normalize(self.minvalue, self.maxvalue) pylab.matplotlib.cm.ScalarMappable.__init__(self, norm, cmap) if was_interactive: pylab.draw() pylab.ion()
def draw(self, axes=None, loc=2): if axes == None: axes = p.gca() if self.box != None and self.box in axes.artists: del axes.artists[axes.artists.index(self.box)] #key_areas = [ mpl.offsetbox.TextArea(k, textprops=self.textprops) for k in self.datadict.keys() ] #val_areas = [ mpl.offsetbox.TextArea(self.datadict[k], textprops=self.textprops) for k in self.datadict.keys() ] key_areas = [ mpl.offsetbox.TextArea(k, textprops=self.textprops) for k in list(self.datadict.keys()) ] val_areas = [ mpl.offsetbox.TextArea(self.datadict[k], textprops=self.textprops) for k in list(self.datadict.keys()) ] key_vpack = mpl.offsetbox.VPacker(children=key_areas, align="left", pad=0, sep=0) val_vpack = mpl.offsetbox.VPacker(children=val_areas, align="right", pad=0, sep=0) hpack = mpl.offsetbox.HPacker(children=[key_vpack, val_vpack], align="top", pad=0, sep=4) globchildren = [] if self.title != None: #titlearea = mpl.offsetbox.TextArea(self.title, textprops=self.titleprops) titlearea = mpl.offsetbox.TextArea(self.title) globchildren.append(titlearea) globchildren.append(hpack) globvpack = mpl.offsetbox.VPacker(children=globchildren, align="center", pad=0, sep=1) self.box = mpl.offsetbox.AnchoredOffsetbox(loc=loc, child=globvpack) self.box.patch.set_facecolor(self.facecolor) self.box.patch.set_edgecolor(self.edgecolor) self.box.patch.set_alpha(self.alpha) axes.add_artist(self.box) if p.isinteractive(): p.gcf().canvas.draw()
def histogram_p_values(p_values, tag): import pylab as P interactive_mode = P.isinteractive() P.ioff() try: P.figure() P.hist(p_values) P.title('%s p-values for transcriptional programs' % tag) P.xlabel('p-values') P.savefig(os.path.join(output_dir, 'p-values-for-%ss.png' % tag), format='PNG') P.close() finally: if interactive_mode: P.ion()
def graticule(dpar=None, dmer=None, coord=None, local=None, **kwds): """Draw a graticule on the current Axes. Parameters ---------- dpar, dmer : float, scalars Interval in degrees between meridians and between parallels coord : {'E', 'G', 'C'} The coordinate system of the graticule (make rotation if needed, using coordinate system of the map if it is defined). local : bool If True, draw a local graticule (no rotation is performed, useful for a gnomonic view, for example) Notes ----- Other keyword parameters will be transmitted to the projplot function. See Also -------- delgraticules """ import pylab f = pylab.gcf() wasinteractive = pylab.isinteractive() pylab.ioff() try: if len(f.get_axes()) == 0: ax = PA.HpxMollweideAxes(f, (0.02, 0.05, 0.96, 0.9), coord=coord) f.add_axes(ax) ax.text( 0.86, 0.05, ax.proj.coordsysstr, fontsize=14, fontweight="bold", transform=ax.transAxes, ) for ax in f.get_axes(): if isinstance(ax, PA.SphericalProjAxes): ax.graticule(dpar=dpar, dmer=dmer, coord=coord, local=local, **kwds) finally: pylab.draw() if wasinteractive: pylab.ion()
def projtext(*args,**kwds): f = pylab.gcf() wasinteractive = pylab.isinteractive() pylab.ioff() ret = None try: for ax in f.get_axes(): if isinstance(ax,PA.SphericalProjAxes): ret = ax.projtext(*args,**kwds) finally: pylab.draw() if wasinteractive: pylab.ion() #pylab.show() return ret
def projtext(*args, **kwds): f = pylab.gcf() wasinteractive = pylab.isinteractive() pylab.ioff() ret = None try: for ax in f.get_axes(): if isinstance(ax, PA.SphericalProjAxes): ret = ax.projtext(*args, **kwds) finally: pylab.draw() if wasinteractive: pylab.ion() #pylab.show() return ret
def showvar(var, *args, **kwargs): # {{{ ''' Plot variable, showing a contour plot for 2d variables or a line plot for 1d variables. Parameters ---------- var : :class:`Var` The variable to plot. Should have either 1 or 2 non-degenerate axes. *args, **kwargs : arguments to pass on to underlying plotting routines, see Notes. Notes ----- This function is intended as the simplest way to display the contents of a variable, choosing appropriate parameter values as automatically as possible. For 1d variables it calls :func:`Var.vplot()`, and for 2d variables :func:`Var.vcontour`. In the latter case, if filled contours were produced, it calls `AxesWrapper.colorbar()'. A dictionary ``colorbar`` can be provided to pass arguments through. Setting ``colorbar`` to ``False`` suppresses the colorbar. See Also -------- vplot, vcontour, colorbar ''' Z = var.squeeze() assert Z.naxes in [1, 2], 'Variable %s has %d non-generate axes; must have 1 or 2.' % (var.name, Z.naxes) fig = kwargs.pop('fig', None) if Z.naxes == 1: ax = vplot(var, *args, **kwargs) elif Z.naxes == 2: ax = vcontour(var, *args, **kwargs) cbar = kwargs.pop('colorbar', dict(orientation='vertical')) cf = ax.find_plot(wr.Contourf) if cbar and cf is not None: ax = wr.colorbar(ax, cf, **cbar) import pylab as pyl if pyl.isinteractive(): ax.render(fig) return ax
def test_analytic_phase(verbose=3): """ >>> test_analytic_phase() """ t=array(range(10000))/100. x=sin(t+t**2/30) y=cos(t+t**2/30) if len(analytic_phase(x)) < len(x): print('shortened from {0} to {1}' .format(len(x),len(analytic_phase(x)))) if verbose>2: xx0=pl.plot(smooth(analytic_phase(x) - analytic_phase(y), 10), hold=0) xx1=pl.plot(smooth(analytic_phase(x) - analytic_phase(y+100), 10), 'k--', hold=1) pl.title('black dash and blue should overlay well') if not(pl.isinteractive()): pl.show()
def bar_timeseries(data, **kwargs): try: step = kwargs.pop('step') ts = data.reduce_avg(data.begin - data.begin % step, step) except KeyError: ts = data x = __x_from_ts(ts) was_inter = pylab.isinteractive() pylab.ioff() bars = pylab.bar(x, ts, ts.step / cmf.day, **kwargs) ax = pylab.gca() ax.xaxis_date() if was_inter: pylab.draw() pylab.ion() return bars
def hinton(W, labels=['', ''], axes=[[], []], name="", maxWeight=None): """ Draws a Hinton diagram for visualizing a weight matrix. Temporarily disables matplotlib interactive mode if it is on, otherwise this takes forever. """ reenable = False if P.isinteractive(): P.ioff() P.clf() height, width = W.shape if not maxWeight: maxWeight = 2**N.ceil(N.log(N.max(N.abs(W))) / N.log(2)) P.fill(N.array([0, width, width, 0]), N.array([0, 0, height, height]), 'gray') #P.axis('off') P.axis('equal') P.axis('image') P.xlabel(labels[0]) P.ylabel(labels[1]) #fig = P.figure() #ax = fig.add_subplot(111) #ax.set_xticklabels(axes[0]) #ax.set_yticklabels(axes[1]) P.xticks(N.arange(len(axes[0])) + 0.5, axes[0], fontsize=10) P.yticks(N.arange(len(axes[1])) + 0.5, axes[1], fontsize=10) for x in xrange(width): for y in xrange(height): _x = x + 1 _y = y + 1 w = W[y, x] if w > 0: _blob(_x - 0.5, height - _y + 0.5, min(1, w / maxWeight), 'white') elif w < 0: _blob(_x - 0.5, height - _y + 0.5, min(1, -w / maxWeight), 'black') if reenable: P.ion() #P.show() if name == "": P.savefig("hinton.png") else: P.savefig(name + ".png")
def plot_tseries(dtimes, data, ax=None, labels=None, datefmt='%b %d, %H:%M', colors=None, ylabel="", title="", fontsize="medium", saveto="", **kwargs): """Plot time series data (e.g. gage recordings) Parameters ---------- dtimes : array of datetime objects (time steps) data : 2D array of shape ( num time steps, num data series ) labels : list of strings (names of data series) title : string kwargs : keyword arguments related to pylab.plot """ if ax is None: returnax = False fig = pl.figure() ax = fig.add_subplot(1, 1, 1, title=title) else: returnax = True # if labels==None: # labels = ["series%d"%i for i in range(1, data.shape[1]+1)] # for i, label in enumerate(labels): # ax.plot_date(mpl.dates.date2num(dtimes),data[:,i],label=label, color=colors[i], **kwargs) ax.plot_date(mpl.dates.date2num(dtimes), data, **kwargs) ax.xaxis.set_major_formatter(mdates.DateFormatter(datefmt)) pl.setp(ax.get_xticklabels(), visible=True) pl.setp(ax.get_xticklabels(), rotation=-30, horizontalalignment='left') ax.set_ylabel(ylabel, size=fontsize) ax = set_ticklabel_size(ax, fontsize) ax.legend(loc='best') if returnax: return ax if saveto == "": # show plot pl.show() if not pl.isinteractive(): # close figure explicitely if pylab is not in interactive mode pl.close() else: # save plot to file if (path.exists(path.dirname(saveto))) or (path.dirname(saveto) == ''): pl.savefig(saveto) pl.close()