我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用pylab.grid()。
def display_wav(filename): input_data = read(filename) audio_in = input_data[1] samples = len(audio_in) fig = pylab.figure(); print samples/44100.0," seconds" k = 0 plot_data_out = [] for i in xrange(samples): plot_data_out.append(audio_in[k]/32768.0) k = k+1 pdata = numpy.array(plot_data_out, dtype=numpy.float) pylab.plot(pdata) pylab.grid(True) pylab.ion() pylab.show()
def plot(self, fontsize=16): """Create the barplot from the stats file""" from sequana.lazy import pylab from sequana.lazy import pandas as pd pylab.clf() df = pd.DataFrame(self._parse_data()['rules']) ts = df.ix['mean-runtime'] total_time = df.ix['mean-runtime'].sum() #ts['total'] = self._parse_data()['total_runtime'] / float(self.N) ts['total'] = total_time ts.sort_values(inplace=True) ts.plot.barh(fontsize=fontsize) pylab.grid(True) pylab.xlabel("Seconds (s)", fontsize=fontsize) try: pylab.tight_layout() except: pass
def plot_rectified(self): import pylab pylab.title('rectified') pylab.imshow(self.rectified) for line in self.vlines: p0, p1 = line p0 = self.inv_transform(p0) p1 = self.inv_transform(p1) pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='green') for line in self.hlines: p0, p1 = line p0 = self.inv_transform(p0) p1 = self.inv_transform(p1) pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='red') pylab.axis('image'); pylab.grid(c='yellow', lw=1) pylab.plt.yticks(np.arange(0, self.l, 100.0)); pylab.xlim(0, self.w) pylab.ylim(self.l, 0)
def plot_original(self): import pylab pylab.title('original') pylab.imshow(self.data) for line in self.lines: p0, p1 = line pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='blue', alpha=0.3) for line in self.vlines: p0, p1 = line pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='green') for line in self.hlines: p0, p1 = line pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='red') pylab.axis('image'); pylab.grid(c='yellow', lw=1) pylab.plt.yticks(np.arange(0, self.l, 100.0)); pylab.xlim(0, self.w) pylab.ylim(self.l, 0)
def plotPopScore(population, fitness=False): """ Plot the population score distribution Example: >>> Interaction.plotPopScore(population) :param population: population object (:class:`GPopulation.GPopulation`) :param fitness: if True, the fitness score will be used, otherwise, the raw. :rtype: None """ score_list = getPopScores(population, fitness) pylab.plot(score_list, 'o') pylab.title("Plot of population score distribution") pylab.xlabel('Individual') pylab.ylabel('Score') pylab.grid(True) pylab.show() # -----------------------------------------------------------------
def plotHistPopScore(population, fitness=False): """ Population score distribution histogram Example: >>> Interaction.plotHistPopScore(population) :param population: population object (:class:`GPopulation.GPopulation`) :param fitness: if True, the fitness score will be used, otherwise, the raw. :rtype: None """ score_list = getPopScores(population, fitness) n, bins, patches = pylab.hist(score_list, 50, facecolor='green', alpha=0.75, normed=1) pylab.plot(bins, pylab.normpdf(bins, numpy.mean(score_list), numpy.std(score_list)), 'r--') pylab.xlabel('Score') pylab.ylabel('Frequency') pylab.grid(True) pylab.title("Plot of population score distribution") pylab.show() # -----------------------------------------------------------------
def plot_word_frequencies(freq, user): samples = [item for item, _ in freq.most_common(50)] freqs = np.array([float(freq[sample]) for sample in samples]) freqs /= np.max(freqs) ylabel = "Normalized word count" pylab.grid(True, color="silver") kwargs = dict() kwargs["linewidth"] = 2 kwargs["label"] = user pylab.plot(freqs, **kwargs) pylab.xticks(range(len(samples)), [nltk.compat.text_type(s) for s in samples], rotation=90) pylab.xlabel("Samples") pylab.ylabel(ylabel) pylab.gca().set_yscale('log', basey=2)
def show_results(self): pl.plot(self.t1, self.n_A1, 'b--', label='A1: Time Step = 0.05') pl.plot(self.t1, self.n_B1, 'b', label='B1: Time Step = 0.05') pl.plot(self.t2, self.n_A2, 'g--', label='A2: Time Step = 0.1') pl.plot(self.t2, self.n_B2, 'g', label='B2: Time Step = 0.1') pl.plot(self.t1, self.n_A1_true, 'r--', label='True A1: Time Step = 0.05') pl.plot(self.t1, self.n_B1_true, 'r', label='True B1: Time Step = 0.05') pl.plot(self.t2, self.n_A2_true, 'c--', label='True A2: Time Step = 0.1') pl.plot(self.t2, self.n_B2_true, 'c', label='True B2: Time Step = 0.1') pl.title('Double Decay Probelm-Approximation Compared with True in Defferent Time Steps') pl.xlim(0.0, 0.1) pl.ylim(0.0, 100.0) pl.xlabel('time ($s$)') pl.ylabel('Number of Nuclei') pl.legend(loc='best', shadow=True, fontsize='small') pl.grid(True) pl.savefig("computational_physics homework 4(improved-7).png")
def show_simple(self): font = {'family': 'serif', 'color': 'k', 'weight': 'normal', 'size': 16, } pl.title('The Trajectory of Tageted Baseball\n with air flow in adiabatic model', fontdict = font) pl.plot(self.x, self.y, label ='$\\alpha = %.0f \degree$'%self.alpha) pl.xlabel('x $m$') pl.ylabel('y $m$') pl.xlim(0, 400) pl.ylim(-100, 200) pl.grid() pl.legend(loc = 'upper right', shadow = True, fontsize = 'medium') pl.text(5, -80, 'trojectories varing with angles of wind', fontdict = font) pl.show()
def show_results(self): font = {'family': 'serif', 'color': 'k', 'weight': 'normal', 'size': 14, } pl.plot(self.x, self.y, 'c', label='firing angle = 45°') pl.title('The Trajectory of a Cannon Shell', fontdict = font) pl.xlabel('x (k$m$)') pl.ylabel('y ($km$)') pl.xlim(0, 60) pl.ylim(0, 20) pl.grid(True) pl.legend(loc='upper right', shadow=True, fontsize='large') pl.text(41, 16, 'Only with air drag', fontdict = font) pl.show()
def show_results(self): font = {'family': 'serif', 'color': 'k', 'weight': 'normal', 'size': 12, } pl.plot(self.x, self.y, 'c', label='firing angle = 45°') pl.title('The Trajectory of a Cannon Shell', fontdict = font) pl.xlabel('x (k$m$)') pl.ylabel('y ($km$)') pl.xlim(0, 60) pl.ylim(0, 20) pl.grid(True) pl.legend(loc='upper right', shadow=True, fontsize='large') pl.text(34, 16, ' With both air drag and \n reduced air density-isothermal', fontdict = font) pl.show()
def show_results(self): font = {'family': 'serif', 'color': 'k', 'weight': 'normal', 'size': 12, } pl.plot(self.x, self.y, 'c', label='firing angle = 45°') pl.title('The Trajectory of a Cannon Shell', fontdict = font) pl.xlabel('x (k$m$)') pl.ylabel('y ($km$)') pl.xlim(0, 60) pl.ylim(0, 20) pl.grid(True) pl.legend(loc='upper right', shadow=True, fontsize='large') pl.text(34.5, 16, ' With air drag and the \n dependence of g on altitude', fontdict = font) pl.show()
def show_results(self): font = {'family': 'serif', 'color': 'k', 'weight': 'normal', 'size': 12, } pl.plot(self.x, self.y, 'c', label='firing angle = 45°') pl.title('The Trajectory of a Cannon Shell', fontdict = font) pl.xlabel('x (k$m$)') pl.ylabel('y ($km$)') pl.xlim(0, 60) pl.ylim(0, 20) pl.grid(True) pl.legend(loc='upper right', shadow=True, fontsize='large') pl.text(34.5, 16, ' With both air drag and \n reduced air density-adiabatic', fontdict = font) pl.show()
def DrawDvs(pl, closes, curve, sign, dvs, pandl, sh, title, leag=None, lad=None ): pl.figure pl.subplot(311) pl.title("id:%s Sharpe ratio: %.2f"%(str(title),sh)) pl.plot(closes) DrawLine(pl, sign, closes) pl.subplot(312) pl.grid() if dvs != None: pl.plot(dvs) if isinstance(curve, np.ndarray): DrawZZ(pl, curve, 'r') if leag != None: pl.plot(leag, 'r') if lad != None: pl.plot(lad, 'b') #pl.plot(stock.GuiYiHua(closes[:i])[60:]) pl.subplot(313) pl.plot(sign) pl.plot(pandl) pl.show() pl.close()
def DrawDvsAndZZ(pl, dvs, zz, closes=None): """dvs?zz??????; dvs : ????closes, """ dvs = np.array(dvs) pl.figure if closes == None: pl.plot(dvs) pl.plot(zz[:,0], zz[:,1], 'r') else: pl.subplot(211) pl.plot(closes) pl.grid() pl.subplot(212) pl.grid() pl.plot(dvs) pl.plot(zz[:,0], zz[:,1], 'r') pl.show() pl.close()
def elltest(scale=0.8,off=0.2): #generate an example, random, non-self-intersecting polygon. #This is done by first generating #it in polar coordinates and than translating it #to cartesian. Theta1,R1=linspace(0,2*pi,30),rand(30)*scale+off X1,Y1=R1*cos(Theta1),R1*sin(Theta1) X1=append(X1,X1[0]) Y1=append(Y1,Y1[0]) p.plot(X1,Y1,".-",ms=10) a2,b2,ecc2,alpha2=ellfit(X1,Y1,showFig=False) Xe,Ye=ellipse(b2,a2,-alpha2,X1.mean(),Y1.mean(),Nb=40) p.plot(Xe,Ye,"r.-") p.grid(True) p.show() pass
def plot(self,title='',include_baseline=False,equal_aspect=True): """ Method that generates a plot of the ROC curve Parameters: title: Title of the chart include_baseline: Add the baseline plot line if it's True equal_aspect: Aspects to be equal for all plot """ pylab.clf() pylab.plot([x[0] for x in self.derived_points], [y[1] for y in self.derived_points], self.linestyle) if include_baseline: pylab.plot([0.0,1.0], [0.0,1.0],'k-.') pylab.ylim((0,1)) pylab.xlim((0,1)) pylab.xticks(pylab.arange(0,1.1,.1)) pylab.yticks(pylab.arange(0,1.1,.1)) pylab.grid(True) if equal_aspect: cax = pylab.gca() cax.set_aspect('equal') pylab.xlabel('1 - Specificity') pylab.ylabel('Sensitivity') pylab.title(title) pylab.show()
def plotAccuracyGraph(X, Y, Xlabel='Variable', Ylabel='Accuracy', graphTitle="Test Accuracy Graph", filename="graph.pdf"): """ Plots and saves accuracy graphs """ try: timestamp = int(time.time()) fig = P.figure(figsize=(8,5)) # Set the graph's title P.title(graphTitle, fontname='monospace') # Set the axes labels P.xlabel(Xlabel, fontsize=12, fontname='monospace') P.ylabel(Ylabel, fontsize=12, fontname='monospace') # Add horizontal and vertical lines to the graph P.grid(color='DarkGray', linestyle='--', linewidth=0.1, axis='both') # Add the data to the graph P.plot(X, Y, 'r-*', linewidth=1.0) # Save figure prettyPrint("Saving figure to ./%s" % filename)#(graphTitle.replace(" ","_"), timestamp)) P.tight_layout() fig.savefig("./%s" % filename)#(graphTitle.replace(" ", "_"), timestamp)) except Exception as e: prettyPrint("Error encountered in \"plotAccuracyGraph\": %s" % e, "error") return False return True
def plot_sum_data(sum_data): pdata = numpy.array(sum_data, dtype=numpy.int16) pylab.figure() pylab.plot(pdata) pylab.grid(True) pylab.show()
def PowerCurve(self): """plot power curve.""" plt.plot(self.speeds, self.powers, linewidth=2.0) plt.title('Power Curve for ' + self.name) plt.grid(True) plt.xlabel('wind speed (m/s)') plt.ylabel('generation (kW)') plt.show(block=True)
def initUI(self): self.grid = QtGui.QGridLayout() self.checkbox = [] i = 0 bold = QtGui.QFont() bold.setBold(True) for plot in range(len(self.plot_order)): if self.plot_order[plot] in self.spacers: label = QtGui.QLabel(self.spacers[self.plot_order[plot]]) label.setFont(bold) self.grid.addWidget(label, i, 0) i += 1 self.checkbox.append(QtGui.QCheckBox(self.hdrs[self.plot_order[plot]], self)) if self.plots[self.plot_order[plot]]: self.checkbox[plot].setCheckState(QtCore.Qt.Checked) self.grid.addWidget(self.checkbox[-1], i, 0) i += 1 self.grid.connect(self.checkbox[0], QtCore.SIGNAL('stateChanged(int)'), self.check_all) show = QtGui.QPushButton('Proceed', self) show.clicked.connect(self.showClicked) self.grid.addWidget(show, i, 0) frame = QtGui.QFrame() frame.setLayout(self.grid) self.scroll = QtGui.QScrollArea() self.scroll.setWidgetResizable(True) self.scroll.setWidget(frame) self.layout = QtGui.QVBoxLayout(self) self.layout.addWidget(self.scroll) commnt = QtGui.QLabel('Nearest weather files:\n' + self.comment) self.layout.addWidget(commnt) self.setWindowTitle('SIREN - Weather dialog for ' + str(self.base_year)) QtGui.QShortcut(QtGui.QKeySequence('q'), self, self.quitClicked) self.show_them = False self.show()
def initUI(self): self.chosen = [] self.grid = QtGui.QGridLayout() self.checkbox = [] self.checkbox.append(QtGui.QCheckBox('Check / Uncheck all', self)) self.grid.addWidget(self.checkbox[-1], 0, 0) i = 0 c = 0 icons = Icons() for stn in sorted(self.stations, key=lambda station: station.name): if stn.technology[:6] == 'Fossil' and not self.actual: continue if stn.technology == 'Rooftop PV' and stn.scenario == 'Existing' and not self.gross_load: continue self.checkbox.append(QtGui.QCheckBox(stn.name, self)) icon = icons.getIcon(stn.technology) if icon != '': self.checkbox[-1].setIcon(QtGui.QIcon(icon)) i += 1 self.grid.addWidget(self.checkbox[-1], i, c) if i > 25: i = 0 c += 1 self.grid.connect(self.checkbox[0], QtCore.SIGNAL('stateChanged(int)'), self.check_all) show = QtGui.QPushButton('Choose', self) self.grid.addWidget(show, i + 1, c) show.clicked.connect(self.showClicked) self.setLayout(self.grid) self.setWindowTitle('SIREN - Power Stations dialog') QtGui.QShortcut(QtGui.QKeySequence('q'), self, self.quitClicked) self.show_them = False self.show()
def plot_com(self): pylab.plot( [-p[1] for p in self.com_real], [p[0] for p in self.com_real], 'g-', lw=2) pylab.plot( [-p[1] for p in self.com_ref], [p[0] for p in self.com_ref], 'k--', lw=1) pylab.legend(('$p_G$', '$p_G^{ref}$'), loc='upper right') pylab.grid(False) pylab.xlim(self.xlim) pylab.ylim(self.ylim) pylab.xlabel(self.xlabel) pylab.ylabel(self.ylabel) pylab.title("COM trajectory")
def plot_zmp(self): pylab.plot( [-p[1] for p in self.zmp_real], [p[0] for p in self.zmp_real], 'r-', lw=2) pylab.plot( [-p[1] for p in self.zmp_ref], [p[0] for p in self.zmp_ref], 'k--', lw=1) pylab.legend(('$p_Z$', '$p_Z^{ref}$'), loc='upper right') pylab.grid(False) pylab.xlim(self.xlim) pylab.ylim(self.ylim) pylab.xlabel(self.xlabel) pylab.ylabel(self.ylabel) pylab.title("ZMP trajectory")
def test_dT_impact(xvals, f, nmpc, sim, start=0.1, end=0.8, step=0.02, ymax=200, sample_size=100, label=None): """Used to generate Figure XX of the paper.""" c = raw_input("Did you remove iter/time caps in IPOPT settings? [y/N] ") if c.lower() not in ['y', 'yes']: print "Then go ahead and do it." return stats = [Statistics() for _ in xrange(len(xvals))] fails = [0. for _ in xrange(len(xvals))] pylab.ion() pylab.clf() for (i, dT) in enumerate(xvals): f(dT) for _ in xrange(sample_size): nmpc.on_tick(sim) if 'Solve' in nmpc.nlp.return_status: stats[i].add(nmpc.nlp.solve_time) else: # max CPU time exceeded, infeasible problem detected, ... fails[i] += 1. yvals = [1000 * ts.avg if ts.avg is not None else 0. for ts in stats] yerr = [1000 * ts.std if ts.std is not None else 0. for ts in stats] pylab.bar( xvals, yvals, width=step, yerr=yerr, color='y', capsize=5, align='center', error_kw={'capsize': 5, 'elinewidth': 5}) pylab.xlim(start - step / 2, end + step / 2) pylab.ylim(0, ymax) pylab.grid(True) if label is not None: pylab.xlabel(label, fontsize=24) pylab.ylabel('Comp. time (ms)', fontsize=20) pylab.tick_params(labelsize=16) pylab.twinx() yfails = [100. * fails[i] / sample_size for i in xrange(len(xvals))] pylab.plot(xvals, yfails, 'ro', markersize=12) pylab.plot(xvals, yfails, 'r--', linewidth=3) pylab.xlim(start - step / 2, end + step / 2) pylab.ylabel("Failure rate [%]", fontsize=20) pylab.tight_layout()
def show_results(self): pl.plot(self.t1, self.n_A1, 'b--', label='A1, Time Step = 0.05') pl.plot(self.t1, self.n_B1, 'b', label='B1, Time Step = 0.05') pl.plot(self.t2, self.n_A2, 'g--', label='A2, Time Step = 0.01') pl.plot(self.t2, self.n_B2, 'g', label='B2, Time Step = 0.01') pl.plot(self.t3, self.n_A3, 'r--', label='A3, Time Step = 0.1') pl.plot(self.t3, self.n_B3, 'r', label='B3, Time Step = 0.1') pl.title('Double Decay Probelm-Three Time Steps') pl.xlim(0.0, 2.5) pl.ylim(0.0, 100.0) pl.xlabel('time ($s$)') pl.ylabel('Number of Nuclei') pl.legend(loc='best', shadow=True, fontsize='small') pl.grid(True)
def show_results(self): pl.plot(self.t, self.n_A, 'b--', label='Number of Nuclei A') pl.plot(self.t, self.n_B, 'b', label='Number of Nuclei B') pl.plot(self.t, self.n_A_true, 'g--', label='True Number of Nuclei A') pl.plot(self.t, self.n_B_true, 'g', label='True Number of Nuclei B') pl.title('Double Decay Probelm-Approximation Compared with True') pl.xlim(0.0, 2.5) pl.ylim(0.0, 100.0) pl.xlabel('time ($s$)') pl.ylabel('Number of Nuclei') pl.legend(loc='best', shadow=True) pl.grid(True)
def ShowZZ(pl, zz, title=''): pl.figure pl.grid() if title != '': pl.title(title) DrawZZ(pl, zz, c='b') pl.show() pl.close()
def grid(self, *args, **kwargs): pl.grid(*args, **kwargs)
def plot_losses(conf,losses_list,builder,name=''): unique_id = builder.get_unique_id() savedir = 'losses' if not os.path.exists(savedir): os.makedirs(savedir) save_path = os.path.join(savedir,'{}_loss_{}.png'.format(name,unique_id)) pl.figure() for losses in losses_list: pl.semilogy(losses) pl.xlabel('Epoch') pl.ylabel('Loss') pl.grid() pl.savefig(save_path)
def plot_multiple_roc(rocList,title='',labels=None, include_baseline=False, equal_aspect=True): """ Plots multiple ROC curves on the same chart. Parameters: rocList: the list of ROCData objects title: The tile of the chart labels: The labels of each ROC curve include_baseline: if it's True include the random baseline equal_aspect: keep equal aspect for all roc curves """ pylab.clf() pylab.ylim((0,1)) pylab.xlim((0,1)) pylab.xticks(pylab.arange(0,1.1,.1)) pylab.yticks(pylab.arange(0,1.1,.1)) pylab.grid(True) if equal_aspect: cax = pylab.gca() cax.set_aspect('equal') pylab.xlabel("1 - Specificity") pylab.ylabel("Sensitivity") pylab.title(title) if not labels: labels = [ '' for x in rocList] _remove_duplicate_styles(rocList) for ix, r in enumerate(rocList): pylab.plot([x[0] for x in r.derived_points], [y[1] for y in r.derived_points], r.linestyle, linewidth=1, label=labels[ix]) if include_baseline: pylab.plot([0.0,1.0], [0.0, 1.0], 'k-', label= 'random') if labels: pylab.legend(loc='lower right') pylab.show()
def plot(self): import pylab as pl pl.plot(self.dim, self.signal) pl.xlabel(self.dim_units) pl.ylabel(self.signal_units) pl.grid(True) pl.show()
def get_required_coverage(self, M=0.01): """Return the required coverage to ensure the genome is covered A general question is what should be the coverage to make sure that e.g. E=99% of the genome is covered by at least a read. The answer is: .. math:: \log^{-1/(E-1)} This equation is correct but have a limitation due to floating precision. If one provides E=0.99, the answer is 4.6 but we are limited to a maximum coverage of about 36 when one provides E=0.9999999999999999 after which E is rounded to 1 on most computers. Besides, it is no convenient to enter all those numbers. A scientific notation would be better but requires to work with :math:`M=1-E` instead of :math:`E`. .. math:: \log^{-1/ - M} So instead of asking the question what is the requested fold coverage to have 99% of the genome covered, we ask the question what is the requested fold coverage to have 1% of the genome not covered. This allows us to use :math:`M` values as low as 1e-300 that is a fold coverage as high as 690. :param float M: this is the fraction of the genome not covered by any reads (e.g. 0.01 for 1%). See note above. :return: the required fold coverage .. plot:: import pylab from sequana import Coverage cover = Coverage() misses = np.array([1e-1, 1e-2, 1e-3, 1e-4,1e-5,1e-6]) required_coverage = cover.get_required_coverage(misses) pylab.semilogx(misses, required_coverage, 'o-') pylab.ylabel("Required coverage", fontsize=16) pylab.xlabel("Uncovered genome", fontsize=16) pylab.grid() # The inverse equation is required fold coverage = [log(-1/(E - 1))] """ # What should be the fold coverage to have 99% of the genome sequenced ? # It is the same question as equating 1-e^{-(NL/G}) == 0.99, we need NL/G = 4.6 if isinstance(M, float) or isinstance(M, int): assert M < 1 assert M >=0 else: M = np.array(M) # Here we do not use log(-1/(E-1)) but log(-1/(1-E-1)) to allow # for using float down to 1e-300 since 0.999999999999999 == 1 return np.log(-1/(-M))
def plotPrecisionRecall(precision, recall, outFileName, Fig=None, drawCol=1, textLabel = None, title = None, fontsize1 = 24, fontsize2 = 20, linewidth = 3): ''' :param precision: :param recall: :param outFileName: :param Fig: :param drawCol: :param textLabel: :param fontsize1: :param fontsize2: :param linewidth: ''' clearFig = False if Fig == None: Fig = pylab.figure() clearFig = True #tableString = 'Algo avgprec Fmax prec recall accuracy fpr Q(TonITS)\n' linecol = ['g','m','b','c'] #if we are evaluating SP, then BL is available #sectionName = 'Evaluation_'+tag+'PxProb' #fullEvalFile = os.path.join(eval_dir,evalName) #Precision,Recall,evalString = readEvaluation(fullEvalFile,sectionName,AlgoLabel) pylab.plot(100*recall, 100*precision, linewidth=linewidth, color=linecol[drawCol], label=textLabel) #writing out PrecRecall curves as graphic setFigLinesBW(Fig) if textLabel!= None: pylab.legend(loc='lower left',prop={'size':fontsize2}) if title!= None: pylab.title(title, fontsize=fontsize1) #pylab.title(title,fontsize=24) pylab.ylabel('PRECISION [%]',fontsize=fontsize1) pylab.xlabel('RECALL [%]',fontsize=fontsize1) pylab.xlim(0,100) pylab.xticks( [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100], ('0','','20','','40','','60','','80','','100'), fontsize=fontsize2 ) pylab.ylim(0,100) pylab.yticks( [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100], ('0','','20','','40','','60','','80','','100'), fontsize=fontsize2 ) pylab.grid(True) # if type(outFileName) != list: pylab.savefig( outFileName ) else: for outFn in outFileName: pylab.savefig( outFn ) if clearFig: pylab.close() Fig.clear()
def doit(csvfile): sensordata=[] timestamplist=[] if 1:#with open(fname, 'rb') as csvfile: for t in range(args.skip_lines): csvfile.readline() reader = csv.reader(csvfile, delimiter=args.delimiter) for a in reader: if a==[]: continue # empty line try: values = [float(t.replace(',','.')) for t in a if t !=''] except Exception,e: print a, e continue if args.columns: values = [values[t] for t in args.columns] if args.timestamps: sensordata.append(values[1:]) timestamplist.append(values[0]) else: sensordata.append(values) if args.histogram: import matplotlib.mlab as mlab mu = mlab.np.average(sensordata) sigma = max(abs(mlab.np.max(sensordata)- mu), abs(mlab.np.min(sensordata)- mu)) # the histogram of the data n, bins, patches = pylab.hist(mlab.np.array(sensordata), 100, normed=True, facecolor='green', alpha=0.75) pylab.grid() pylab.show() if args.output_file_name: outfile = open(args.output_file_name,'w') for line in sensordata: outfile.write(args.output_delimiter.join([args.output_formatter % round(t*args.output_multiplier) for t in line])+'\n') else: if timestamplist!=[]: # data with timestamp pylab.plot(timestamplist, sensordata, args.tick_mark) pylab.xlabel('time') else: pylab.plot(sensordata, args.tick_mark) pylab.xlabel('sample #') pylab.title(csvfile.name) if args.legend: pylab.legend(args.legend) pylab.grid() pylab.show()
def iz_test_bench(a, b, c, d, dt, Fshift): max_val = 1 << (Fshift + 7) I = Signal(intbv(0, min=-max_val, max=max_val)) output = Signal(bool(0)) clk = Signal(bool(0)) reset = ResetSignal(1, active=0, async=True) neuron_instance = neuron_module(clk, reset, I, output, a, b, c, d, dt, Fshift) @always(delay(50)) def clkgen(): clk.next = not clk @instance def stimulus(): I.next = 0 yield delay(10000) I.next = to_fixed(10.0, Fshift) yield delay(100000) I.next = 0 yield delay(10000) pylab.figure(1) pylab.subplot(311) pylab.title("MyHDL Izhikevitch neuron (chattering)") pylab.plot(t_values, v_values, label="v") pylab.ylabel('membrane potential (mv)') pylab.grid() pylab.subplot(312) pylab.plot(t_values, u_values, label="u") pylab.ylabel("recovery variable") pylab.grid() pylab.subplot(313) pylab.plot(t_values, I_values, label="I") pylab.grid() pylab.ylabel("input current") pylab.xlabel("time (usec)") pylab.show() raise StopSimulation return clkgen, stimulus, neuron_instance # Uncomment definitions of a, b, c, d to choose different neuron types. # Regular spiking #a, b, c, d = 0.02, 0.2, -65.0, 8.0 # Fast spiking #a, b, c, d = 0.1, 0.2, -65.0, 2.0 #intrinsically bursting #a, b, c, d =0.02, 0.2, -55.0, 4.0 # chattering
def plotReductionGraph(dataSamples, dataLabels, classNames, dimension=2, graphTitle="Test Graph", filename="reduction.pdf"): """ Plots data sample visualization graphs """ try: timestamp = int(time.time()) colors = ['DarkRed', 'DarkGreen', 'DarkBlue', 'DarkOrange', 'DarkMagenta', 'DarkCyan', 'Gray', 'Black'] randomColor = lambda: random.randint(0,255) markers = ['*', 'o', 'v', '^', 's', 'd', 'D', 'p', 'h', 'H', '<', '>', '.', ',', '|', '_'] fig = P.figure(figsize=(8,5)) if dimension == 3: ax = fig.add_subplot(111, projection='3d') P.title(graphTitle, fontname='monospace') if dimension == 2: P.xlabel('x1', fontsize=12, fontname='monospace') P.ylabel('x2', fontsize=12, fontname='monospace') else: ax.set_xlabel('x1', fontsize=12, fontname='monospace') ax.set_ylabel('x2', fontsize=12, fontname='monospace') ax.set_zlabel('x3', fontsize=12, fontname='monospace') P.grid(color='DarkGray', linestyle='--', linewidth=0.1, axis='both') for c in range(len(classNames)): X,Y,Z = [], [], [] for labelIndex in range(len(dataLabels)): if c == dataLabels[labelIndex]: X.append(dataSamples[labelIndex,:].tolist()[0]) Y.append(dataSamples[labelIndex,:].tolist()[1]) if dimension == 3: Z.append(dataSamples[labelIndex,:].tolist()[2]) # Plot points of that class #P.plot(Y, X, color='#%02X%02X%02X' % (randomColor(), randomColor(), randomColor()), marker=markers[c], markeredgecolor='None', markersize=4.0, linestyle='None', label=classNames[c]) if dimension == 2: P.plot(Y, X, color=colors[c % len(colors)], marker=markers[c % len(markers)], markersize=5.0, linestyle='None', label=classNames[c]) else: ax.scatter(X,Y,Z,c=colors[c % len(colors)], marker=markers[c % len(markers)]) if dimension == 2: #P.legend([x.split(",")[-1] for x in classNames], fontsize='xx-small', numpoints=1, fancybox=True) P.legend([x for x in classNames], fontsize='xx-small', numpoints=1, fancybox=True) else: ax.legend([x for x in classNames], fontsize='xx-small', numpoints=1, fancybox=True) prettyPrint("Saving results to ./%s" % filename)#(graphTitle, timestamp)) P.tight_layout() fig.savefig("./%s" % filename)#(graphTitle, timestamp)) except Exception as e: prettyPrint("Error encountered in \"plotReductionGraph\": %s" % e, "error") return False return True