Python pylab 模块,legend() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pylab.legend()

项目:seqhawkes    作者:mlukasik    | 项目源码 | 文件源码
def display_results_figure(results, METRIC):
    import pylab as pb
    color = iter(pb.cm.rainbow(np.linspace(0, 1, len(results))))
    plots = []
    for method in results.keys():
        x = []
        y = []
        for train_perc in sorted(results[method].keys()):
            x.append(train_perc)
            y.append(results[method][train_perc][0])
        c = next(color)
        (pi, ) = pb.plot(x, y, color=c)
        plots.append(pi)
    from matplotlib.font_manager import FontProperties
    fontP = FontProperties()
    fontP.set_size('small')
    pb.legend(plots, map(method_name_mapper, results.keys()),
              prop=fontP, bbox_to_anchor=(0.6, .65))
    pb.xlabel('#Tweets from target rumour for training')
    pb.ylabel('Accuracy')
    pb.title(METRIC.__name__)
    pb.savefig('incrementing_training_size.png')
项目:ndparse    作者:neurodata    | 项目源码 | 文件源码
def display_pr_curve(precision, recall):
    # following examples from sklearn

    # TODO:  f1 operating point

    import pylab as plt
    # Plot Precision-Recall curve
    plt.clf()
    plt.plot(recall, precision, label='Precision-Recall curve')
    plt.xlabel('Recall')
    plt.ylabel('Precision')
    plt.ylim([0.0, 1.05])
    plt.xlim([0.0, 1.0])
    plt.title('Precision-Recall example: Max f1={0:0.2f}'.format(max_f1))
    plt.legend(loc="lower left")
    plt.show()
项目:TPs    作者:DataMiningP7    | 项目源码 | 文件源码
def ex2():
    x = np.linspace(-10, 10)

    # "--" = dashed line
    plt.plot(x, np.sin(x), "--", label="sinus")
    plt.plot(x, np.cos(x), label="cosinus")

    # Show the legend using the labels above
    plt.legend()

    # The trick here is we have to make another plot on top of the two others.
    pi2 = np.pi/2

    # Find B such that (-B * pi/2) >= -10 > ((-B-1) * pi/2), i.e. the
    # first multiple of pi/2 higher than -10.
    b = pi2*int(-10.0/pi2)

    # x2 is all multiples of pi/2 between -10 and 10.
    x2 = np.arange(b, 10, pi2)

    # "b." = blue dots
    plt.plot(x2, np.sin(x2), "b.")
    plt.show()
项目:breaking_cycles_in_noisy_hierarchies    作者:zhenv5    | 项目源码 | 文件源码
def _plotFMeasures(fstepsize=.1,  stepsize=0.0005, start = 0.0, end = 1.0):
    """Plots 10 fmeasure Curves into the current canvas."""
    p = sc.arange(start, end, stepsize)[1:]
    for f in sc.arange(0., 1., fstepsize)[1:]:
        points = [(x, _fmeasureCurve(f, x)) for x in p
                  if 0 < _fmeasureCurve(f, x) <= 1.5]
        try:
            xs, ys = zip(*points)
            curve, = pl.plot(xs, ys, "--", color="gray", linewidth=0.8)  # , label=r"$f=%.1f$"%f) # exclude labels, for legend
            # bad hack:
            # gets the 10th last datapoint, from that goes a bit to the left, and a bit down
            datapoint_x_loc = int(len(xs)/2)
            datapoint_y_loc = int(len(ys)/2)
            # x_left = 0.05
            # y_left = 0.035
            x_left = 0.035
            y_left = -0.02
            pl.annotate(r"$f=%.1f$" % f, xy=(xs[datapoint_x_loc], ys[datapoint_y_loc]), xytext=(xs[datapoint_x_loc] - x_left, ys[datapoint_y_loc] - y_left), size="small", color="gray")
        except Exception as e:
            print e 

#colors = "gcmbbbrrryk"
#colors = "yyybbbrrrckgm"  # 7 is a prime, so we'll loop over all combinations of colors and markers, when zipping their cycles
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
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")
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show(self):
#        pl.semilogy(self.theta, self.omega)
#                , label = '$L =%.1f m, $'%self.l + '$dt = %.2f s, $'%self.dt + '$\\theta_0 = %.2f radians, $'%self.theta[0] + '$q = %i, $'%self.q + '$F_D = %.2f, $'%self.F_D + '$\\Omega_D = %.1f$'%self.Omega_D)
        pl.plot(self.theta_phase ,self.omega_phase, '.', label = '$t \\approx 2\\pi n / \\Omega_D$')
        pl.xlabel('$\\theta$ (radians)')
        pl.ylabel('$\\omega$ (radians/s)')
        pl.legend()
#        pl.text(-1.4, 0.3, '$\\omega$ versus $\\theta$ $F_D = 1.2$', fontsize = 'x-large')
        pl.title('Chaotic Regime')
#        pl.show()
#        pl.semilogy(self.time_array, self.delta)
#        pl.legend(loc = 'upper center', fontsize = 'small')
#        pl.xlabel('$time (s)$')
#        pl.ylabel('$\\Delta\\theta (radians)$')
#        pl.xlim(0, self.T)
#        pl.ylim(float(input('ylim-: ')),float(input('ylim+: ')))
#        pl.ylim(1E-11, 0.01)
#        pl.text(4, -0.15, 'nonlinear pendulum - Euler-Cromer method')
#        pl.text(10, 1E-3, '$\\Delta\\theta versus time F_D = 0.5$')
#        pl.title('Simple Harmonic Motion')
        pl.title('Chaotic Regime')
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show(self):
#        pl.semilogy(self.theta, self.omega)
#                , label = '$L =%.1f m, $'%self.l + '$dt = %.2f s, $'%self.dt + '$\\theta_0 = %.2f radians, $'%self.theta[0] + '$q = %i, $'%self.q + '$F_D = %.2f, $'%self.F_D + '$\\Omega_D = %.1f$'%self.Omega_D)
        pl.plot(self.time_array,self.delta)

#        pl.show()
#        pl.semilogy(self.time_array, self.delta)
#        pl.legend(loc = 'upper center', fontsize = 'small')
#        pl.xlabel('$time (s)$')
#        pl.ylabel('$\\Delta\\theta (radians)$')
#        pl.xlim(0, self.T)
#        pl.ylim(float(input('ylim-: ')),float(input('ylim+: ')))
#        pl.ylim(1E-11, 0.01)
#        pl.text(4, -0.15, 'nonlinear pendulum - Euler-Cromer method')
#        pl.text(10, 1E-3, '$\\Delta\\theta versus time F_D = 0.5$')
#        pl.title('Simple Harmonic Motion')
#        pl.title('Chaotic Regime')
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
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()
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
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()
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
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()
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
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()
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
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()
项目:ArduPi-ECG    作者:ferdavid1    | 项目源码 | 文件源码
def main():
    data = pd.read_table('../Real_Values.txt').get_values()
    x = [float(d) for d in data]
    test = np.array([669, 592, 664, 1005, 699, 401, 646, 472, 598, 681, 1126, 1260, 562, 491, 714, 530, 521, 687, 776, 802, 499, 536, 871, 801, 965, 768, 381, 497, 458, 699, 549, 427, 358, 219, 635, 756, 775, 969, 598, 630, 649, 722, 835, 812, 724, 966, 778, 584, 697, 737, 777, 1059, 1218, 848, 713, 884, 879, 1056, 1273, 1848, 780, 1206, 1404, 1444, 1412, 1493, 1576, 1178, 836, 1087, 1101, 1082, 775, 698, 620, 651, 731, 906, 958, 1039, 1105, 620, 576, 707, 888, 1052, 1072, 1357, 768, 986, 816, 889, 973, 983, 1351, 1266, 1053, 1879, 2085, 2419, 1880, 2045, 2212, 1491, 1378, 1524, 1231, 1577, 2459, 1848, 1506, 1589, 1386, 1111, 1180, 1075, 1595, 1309, 2092, 1846, 2321, 2036, 3587, 1637, 1416, 1432, 1110, 1135, 1233, 1439, 894, 628, 967, 1176, 1069, 1193, 1771, 1199, 888, 1155, 1254, 1403, 1502, 1692, 1187, 1110, 1382, 1808, 2039, 1810, 1819, 1408, 803, 1568, 1227, 1270, 1268, 1535, 873, 1006, 1328, 1733, 1352, 1906, 2029, 1734, 1314, 1810, 1540, 1958, 1420, 1530, 1126, 721, 771, 874, 997, 1186, 1415, 973, 1146, 1147, 1079, 3854, 3407, 2257, 1200, 734, 1051, 1030, 1370, 2422, 1531, 1062, 530, 1030, 1061, 1249, 2080, 2251, 1190, 756, 1161, 1053, 1063, 932, 1604, 1130, 744, 930, 948, 1107, 1161, 1194, 1366, 1155, 785, 602, 903, 1142, 1410, 1256, 742, 985, 1037, 1067, 1196, 1412, 1127, 779, 911, 989, 946, 888, 1349, 1124, 761, 994, 1068, 971, 1157, 1558, 1223, 782, 2790, 1835, 1444, 1098, 1399, 1255, 950, 1110, 1345, 1224, 1092, 1446, 1210, 1122, 1259, 1181, 1035, 1325, 1481, 1278, 769, 911, 876, 877, 950, 1383, 980, 705, 888, 877, 638, 1065, 1142, 1090, 1316, 1270, 1048, 1256, 1009, 1175, 1176, 870, 856, 860])
    n_predict = 100
    extrapolation = fourierExtrapolation(x, n_predict)

    pl.figure()
    pl.plot(np.arange(len(x), len(extrapolation) + len(x)), extrapolation, 'r', label = 'extrapolation')
    pl.plot(x, 'b', label = 'Given Data', linewidth = 3)
    pl.legend()
    pl.ylabel('BPM')
    pl.xlabel('Sample')
    pl.title('Fourier Extrapolation')
    pl.savefig('FourierExtrapolation.png')
    #pl.show()
    with open('Fourier_PredValues.txt', 'w') as out:
        out.write(str([e for e in extrapolation]).strip('[]'))
项目:mglex    作者:fungs    | 项目源码 | 文件源码
def plot_clusters_pca(responsibilities, color_groups):
    from sklearn.decomposition import RandomizedPCA
    import pylab as pl
    from random import shuffle

    colors = list(colors_dict.values())
    shuffle(colors)

    pca = RandomizedPCA(n_components=2)
    X = pca.fit_transform(responsibilities)
    # print >>stderr, pca.explained_variance_ratio_

    pl.figure()
    pl.scatter(X[:, 0], X[:, 1], c="grey", label="unknown")
    for c, sub, i in zip(colors, color_groups, count(0)):
        pl.scatter(X[sub, 0], X[sub, 1], c=c, label=str(i))
    pl.legend()
    pl.title("PCA responsibility matrix")
    pl.show()
项目:Parallel-SGD    作者:angadgill    | 项目源码 | 文件源码
def plot(func):
    random_state = check_random_state(0)
    one_core = []
    multi_core = []
    sample_sizes = range(1000, 6000, 1000)

    for n_samples in sample_sizes:
        X = random_state.rand(n_samples, 300)

        start = time.time()
        func(X, n_jobs=1)
        one_core.append(time.time() - start)

        start = time.time()
        func(X, n_jobs=-1)
        multi_core.append(time.time() - start)

    pl.figure('scikit-learn parallel %s benchmark results' % func.__name__)
    pl.plot(sample_sizes, one_core, label="one core")
    pl.plot(sample_sizes, multi_core, label="multi core")
    pl.xlabel('n_samples')
    pl.ylabel('Time (s)')
    pl.title('Parallel %s' % func.__name__)
    pl.legend()
项目:AdK_analysis    作者:orbeckst    | 项目源码 | 文件源码
def _auto_plots(self,mode,filebasename,figdir,plotargs):
        """Generate standard plots and write png and and pdf. Chooses filename and plot title."""
        import pylab

        try:
            os.makedirs(figdir)
        except OSError,err:
            if err.errno != errno.EEXIST:
                raise

        def figs(*args):
            return os.path.join(figdir,*args)

        modefilebasename = filebasename + self._suffix[mode]
        _plotargs = plotargs.copy()  # need a copy because of changing 'title'
        if plotargs.get('title') is None:  # None --> set automatic title
            _plotargs['title'] = self._title[mode]+' '+self.legend

        pylab.clf()
        self.plot(**_plotargs)
        pylab.savefig(figs(modefilebasename + '.png'))   # png
        pylab.savefig(figs(modefilebasename + '.pdf'))   # pdf

        print "--- Plotted %(modefilebasename)r (png,pdf)." % vars()
项目:AdK_analysis    作者:orbeckst    | 项目源码 | 文件源码
def plot(self,direction,legend=True,**kwargs):
        """Plot all distributions; colors are set automatically to kwargs[cmap]."""
        import pylab
        pnormalize = pylab.normalize(vmin=1,vmax=len(self.distribution[direction]))

        kwargs.setdefault('alpha',1.0)
        kwargs.setdefault('linewidth',4)
        fmt = kwargs.pop('fmt','-')
        cmap = kwargs.pop('cmap',pylab.cm.jet)

        count = 0
        for target,(hist,edges) in self.distribution[direction].items():
            count += 1
            midpoints = 0.5*(edges[1:] + edges[:-1])
            kwargs['color'] = cmap(pnormalize(count))
            pylab.plot(midpoints,hist,fmt,label="%s" % target,**kwargs)
        if legend:
            pylab.legend(loc='best',
                         prop=pylab.matplotlib.font_manager.FontProperties(size=6))
项目:livespin    作者:biocompibens    | 项目源码 | 文件源码
def plot(self, outpath=''):
        pylab.figure(figsize = (17,10))
        diff = self.f2-self.f3
        pylab.subplot(2,1,1)
        pylab.plot(range(self.lengthSeq), self.f2, 'r-', label = "f2")
        pylab.plot(range(self.lengthSeq), self.f3, 'g-', label = "f3")
        pylab.xlim([0., self.lengthSeq])
        pylab.tick_params(axis='both', which='major', labelsize=25)
        pylab.subplot(2,1,2)

        diff2 = diff/self.f3
        diff2 /= np.max(diff2)
        pylab.plot(range(self.lengthSeq), diff2, 'b-', label = "Rescaled (by max) difference / f3")
        pylab.xlabel("Temps (en images)", fontsize = 25)
        pylab.tick_params(axis='both', which='major', labelsize=25)
        pylab.xlim([0., self.lengthSeq])
        #pylab.legend(loc= 2, prop = {'size':15})
        pylab.savefig(outpath)
        pylab.close()
项目:livespin    作者:biocompibens    | 项目源码 | 文件源码
def bootstrap_extradata(self, nBoot, extradataA, nbins = 20):
        pops =[]
        meanpop = [[] for i in data.cat]
        pylab.figure(figsize = (14,14))
        for i in xrange(min(4, len(extradataA))):
            #pylab.subplot(2,2,i+1)
            if  i ==0:
                pylab.title("Bootstrap on means", fontsize = 20.)
            pop = extradataA[i]# & (self.GFP > 2000)]#
            for index in xrange(nBoot):
                newpop = np.random.choice(pop, size=len(pop), replace=True)

                #meanpop[i].append(np.mean(newpop))
            pops.append(newpop)
            pylab.legend()
        #pylab.title(cat[i])
            pylab.xlabel("Angle(degree)", fontsize = 15)
            pylab.xlim([0., 90.])
        for i in xrange(len(extradataA)):
            for j in xrange(i+1, len(extradataA)):
                statT, pvalue = scipy.stats.ttest_ind(pops[i], pops[j], equal_var=False)
                print "cat{0} & cat{1} get {2} ({3})".format(i,j, pvalue,statT)
        pylab.savefig("/users/biocomp/frose/frose/Graphics/FINALRESULTS-diff-f3/mean_nBootstrap{0}_bins{1}_GFPsup{2}_FLO_{3}.png".format(nBoot, nbins, 'all', randint(0,999)))
项目:DVH    作者:glucee    | 项目源码 | 文件源码
def main():


    # Read the example RT structure and RT dose files
    # The testdata was downloaded from the dicompyler website as testdata.zip

    # Obtain the structures and DVHs from the DICOM data

    rtssfile = 'testdata/rtss.dcm'
    rtdosefile = 'testdata/rtdose.dcm'
    RTss = dicomparser.DicomParser(rtssfile)
    #RTdose = dicomparser.DicomParser("testdata/rtdose.dcm") 
    RTstructures = RTss.GetStructures()

    # Generate the calculated DVHs
    calcdvhs = {}
    for key, structure in RTstructures.iteritems():
        calcdvhs[key] = dvhcalc.get_dvh(rtssfile, rtdosefile, key)
        if (key in calcdvhs) and (len(calcdvhs[key].counts) and calcdvhs[key].counts[0]!=0):
            print ('DVH found for ' + structure['name'])
            pl.plot(calcdvhs[key].counts * 100/calcdvhs[key].counts[0], 
                    color=dvhcalc.np.array(structure['color'], dtype=float) / 255, 
                    label=structure['name'], 
                    linestyle='dashed')
        #else: 
        #    print("%d: no DVH"%key)
    pl.xlabel('Distance (cm)')
    pl.ylabel('Percentage Volume')
    pl.legend(loc=7, borderaxespad=-5)
    pl.setp(pl.gca().get_legend().get_texts(), fontsize='x-small')
    pl.savefig('testdata/dvh.png', dpi = 75)
项目:astromalign    作者:dstndstn    | 项目源码 | 文件源码
def filters_legend(lp, filters): #, **kwa):
    I = argsort_filters(filters)
    #plt.legend([lp[i] for i in I], [filters[i] for i in I], **kwa)
    return [lp[i] for i in I], [filters[i] for i in I]
项目:astromalign    作者:dstndstn    | 项目源码 | 文件源码
def plotfitquality(H, xe, ye, A):
    '''
    H,xe,ye from plotalignment()
    '''
    import pylab as plt
    xe /= 1000.
    ye /= 1000.
    xx = (xe[:-1] + xe[1:])/2.
    yy = (ye[:-1] + ye[1:])/2.
    XX,YY = np.meshgrid(xx, yy)
    XX = XX.ravel()
    YY = YY.ravel()
    XY = np.vstack((XX,YY)).T
    Mdist = np.sqrt(mahalanobis_distsq(XY, A.mu, A.C))
    assert(len(H.ravel()) == len(Mdist))
    mod = A.getModel(XX, YY)
    R2 = XX**2 + YY**2
    mod[R2 > (A.match.rad)**2] = 0.
    mod *= (H.sum() / mod.sum())
    plt.clf()
    rng = (0, 7)
    plt.hist(Mdist, 100, weights=H.ravel(), histtype='step', color='b', label='data', range=rng)
    plt.hist(Mdist, 100, weights=mod, histtype='step', color='r', label='model', range=rng)
    plt.xlabel('| Chi |')
    plt.ylabel('Number of matches')
    plt.title('Gaussian peak fit quality')
    plt.legend(loc='upper right')
项目:multi-contact-zmp    作者:stephane-caron    | 项目源码 | 文件源码
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")
项目:multi-contact-zmp    作者:stephane-caron    | 项目源码 | 文件源码
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")
项目:MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python    作者:tiagomestreteixeira    | 项目源码 | 文件源码
def displayRetirementWithMonthlies(monthlies, rate, terms):
    plt.figure('retireMonth')
    plt.clf()
    for monthly in monthlies:
        xvals, yvals = retire(monthly, rate, terms)
        plt.plot(xvals, yvals, label='retire:' + str(monthly))
        plt.legend(loc='upper left')
项目:MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python    作者:tiagomestreteixeira    | 项目源码 | 文件源码
def displayRetirementWithRates(monthly, rates, terms):
    plt.figure('retireRate')
    plt.clf()
    for rate in rates:
        xvals, yvals = retire(monthly, rate, terms)
        plt.plot(xvals, yvals,
                 label='retire:' + str(monthly) + ':' + str(int(rate * 100)))
        plt.legend(loc='upper left')
项目:MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python    作者:tiagomestreteixeira    | 项目源码 | 文件源码
def displayRetirementWithMonthsAndRates(monthlies, rates, terms):
    plt.figure('retireBoth')
    plt.clf()
    plt.xlim(30 * 12, 40 * 12)
    for monthly in monthlies:
        for rate in rates:
            xvals, yvals = retire(monthly, rate, terms)
            plt.plot(xvals, yvals,
                     label='retire:' + str(monthly) + ':' + str(int(rate * 100)))
            plt.legend(loc='upper left')
项目:GLaDOS2    作者:TheComet    | 项目源码 | 文件源码
def zipf(self, message, users):
        source_user = message.author.name
        source_user = source_user.strip('@').split('#')[0]

        target_users = [user.strip('@').split('#')[0] for user in users.split()]
        if len(users) == 0:
            target_users = [source_user]

        if users == '*':
            if message.server is not None:
                target_users = [member.name for member in message.server.members]
        target_users = [user for user in target_users if self.check_nickname_valid(user.lower()) is None]

        image_file_name = self.quotes_file_name(source_user.lower())[:-4] + '.png'
        pylab.title('Word frequencies')
        for user in target_users:
            quotes_file = codecs.open(self.quotes_file_name(user.lower()), 'r', encoding='utf-8')
            lines = quotes_file.readlines()
            quotes_file.close()

            if len(lines) < 20:
                continue

            tokenizer = nltk.tokenize.RegexpTokenizer(r'\w+')
            tokens = self.filter_to_english_words(tokenizer.tokenize(str(lines)))
            if len(tokens) < 200:
                continue
            freq = nltk.FreqDist(tokens)
            self.plot_word_frequencies(freq, user)

        pylab.legend()
        pylab.savefig(image_file_name)
        pylab.gcf().clear()

        await self.client.send_file(message.channel, image_file_name)
项目:smarty    作者:openforcefield    | 项目源码 | 文件源码
def create_plot_file(trajFile, plot_filename, plot_others=False, verbose = False):
    """
    Creates plot to demonstrate performance of smarty or smirky

    trajFile - csv file generated by smarty, smarty_elemental, or smirky
    plot_filename - pdf to save plot file to
    plot_others - if True plots data for all reftypes separately, optional
    """

    data = pd.read_csv(trajFile, quotechar="'")
    numerator = data.columns[-2].lower()

    timeseries = load_trajectory(trajFile)
    time_fractions = scores_vs_time(timeseries, numerator)

    max_score = max(time_fractions['all']) *100.0
    if verbose: print("Maximum score was %.1f %%" % max_score)
    # plot overall score
    pl.plot( time_fractions['all'], 'k-', linewidth = 2.0)

    if plot_others:
        reftypes = [k for k in time_fractions]
        reftypes.remove('all')

        # Plot scors for individual types
        for reftype in reftypes:
            pl.plot(time_fractions[reftype])

        pl.legend(['all']+reftypes, loc='lower right')

    pl.xlabel('Iterations')
    pl.ylabel('Fraction of reference type found')
    pl.ylim(-0.1, 1.1)

    pl.savefig(plot_filename)
项目:ThermoCodeLib    作者:longlevan    | 项目源码 | 文件源码
def smooth_curve(curve_data,N_smooth,exp_max=-1,shift_0=0,fix_first_nonzero=False,plotit=False,t='x for plot'):
    """
    smoothens the curve data for plotting as good as possible while maintaining last and first value
    curve data => np.array, 1D that should be smoothened out
    N_smooth => number of points to smooth over (float)
    exp_max => adjust exponential behavior for average (0='normal' moving average)
    shift_0 => manually fix from where on smoothing is active, e.g. up till where no smootthing is applied
    fix_first_nonzero => if set to true, then automatically determines shift_0 to be where the first nonzero entry is
    plotit => plot results
    t => x-cooordinate for plot
    """
    a=curve_data
    N=N_smooth
    v=np.exp(np.linspace(exp_max, 0., N))
    v=v/v.sum()
    a_v=np.convolve(a,v,'same')
    if fix_first_nonzero==True:
        shift_0=np.nonzero(a != 0)[0][0]
    for n in range(0,len(v)):
        if n!=0:
            v=np.exp(np.linspace(exp_max, 0., n))
            v=v/v.sum()
            a_v[n+shift_0]=np.convolve(a,v,'same')[n+shift_0]
            a_v[len(a)-n-1]=np.convolve(a,v,'same')[len(a)-n-1]
        else:
            a_v[n+shift_0]=a[n+shift_0]
            for i in range(0,n+shift_0):
                a_v[i]=a[i]
            a_v[len(a)-n-1]=a[len(a)-n-1]
    if plotit:
        try:
            np.sin(t)
        except:
            t=np.linspace(0,len(curve_data),len(curve_data))
        import pylab as plt
        plt.plot(t,a,label='original data')
        plt.plot(t,a_v,label='smoothened')
        plt.legend(loc='best',fancybox=True)
        plt.title('curve smoothing')
        plt.show()
    return a_v
项目:ThermoCodeLib    作者:longlevan    | 项目源码 | 文件源码
def smooth_curve(curve_data,N_smooth,exp_max=-1,shift_0=0,fix_first_nonzero=False,plotit=False,t='x for plot'):
    """
    smoothens the curve data for plotting as good as possible while maintaining last and first value
    curve data => np.array, 1D that should be smoothened out
    N_smooth => number of points to smooth over (float)
    exp_max => adjust exponential behavior for average (0='normal' moving average)
    shift_0 => manually fix from where on smoothing is active, e.g. up till where no smootthing is applied
    fix_first_nonzero => if set to true, then automatically determines shift_0 to be where the first nonzero entry is
    plotit => plot results
    t => x-cooordinate for plot
    """
    a=curve_data
    N=N_smooth
    v=np.exp(np.linspace(exp_max, 0., N))
    v=v/v.sum()
    a_v=np.convolve(a,v,'same')
    if fix_first_nonzero==True:
        shift_0=np.nonzero(a != 0)[0][0]
    for n in range(0,len(v)):
        if n!=0:
            v=np.exp(np.linspace(exp_max, 0., n))
            v=v/v.sum()
            a_v[n+shift_0]=np.convolve(a,v,'same')[n+shift_0]
            a_v[len(a)-n-1]=np.convolve(a,v,'same')[len(a)-n-1]
        else:
            a_v[n+shift_0]=a[n+shift_0]
            for i in range(0,n+shift_0):
                a_v[i]=a[i]
            a_v[len(a)-n-1]=a[len(a)-n-1]
    if plotit:
        try:
            np.sin(t)
        except:
            t=np.linspace(0,len(curve_data),len(curve_data))
        import pylab as plt
        plt.plot(t,a,label='original data')
        plt.plot(t,a_v,label='smoothened')
        plt.legend(loc='best',fancybox=True)
        plt.title('curve smoothing')
        plt.show()
    return a_v
项目:casiopeia    作者:adbuerger    | 项目源码 | 文件源码
def plot_measurements_and_simulation_results(time_points, ydata, y_sim):

    pl.subplot2grid((4, 2), (0, 0))
    pl.plot(time_points, ydata[:,0], label = "measurements")
    pl.plot(time_points, y_sim[:,0], label = "simulation")
    pl.title("Measurement data compared to simulation results")
    pl.xlabel("t")
    pl.ylabel("X", rotation = 0, labelpad = 20)
    pl.legend(loc = "lower left")

    pl.subplot2grid((4, 2), (1, 0))
    pl.plot(time_points, ydata[:,1], label = "measurements")
    pl.plot(time_points, y_sim[:,1], label = "simulation")
    pl.xlabel("t")
    pl.ylabel("Y", rotation = 0, labelpad = 15)
    pl.legend("lower right")

    pl.subplot2grid((4, 2), (2, 0))
    pl.plot(time_points, ydata[:,2], label = "measurements")
    pl.plot(time_points, y_sim[:,2], label = "simulation")
    pl.xlabel("t")
    pl.ylabel(r"\phi", rotation = 0, labelpad = 15)
    pl.legend("lower left")

    pl.subplot2grid((4, 2), (3, 0))
    pl.plot(time_points, ydata[:,3], label = "measurements")
    pl.plot(time_points, y_sim[:,3], label = "simulation")
    pl.xlabel("t")
    pl.ylabel("v", rotation = 0, labelpad = 20)
    pl.legend("upperleft")

    pl.subplot2grid((4, 2), (0, 1), rowspan = 4)
    pl.plot(ydata[:,0], ydata[:, 1], label = "measurements")
    pl.plot(y_sim[:,0], y_sim[:,1], label = "estimations")
    pl.title("Measured race track compared to simulated results")
    pl.xlabel("X")
    pl.ylabel("Y", rotation = 0, labelpad = 20)
    pl.legend(loc = "upper left")
    pl.show()
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_results(self):
        pl.plot(self.t, self.n_A1, 'b--', label='A1: Time Constant = 1')
        pl.plot(self.t, self.n_B1, 'g', label='B1: Time Constant = 2')
        pl.plot(self.t, self.n_A2, 'k--', label='A2: Time Constant = 1')
        pl.plot(self.t, self.n_B2, 'c', label='B2: Time Constant = 2')
        pl.plot(self.t, self.n_A3, 'm--', label='A3: Time Constant = 1')
        pl.plot(self.t, self.n_B3, 'y', label='B3: Time Constant = 2')
        pl.title('Double Decay Probelm - Nuclei with Different Time Constans')
        pl.xlim(0.0, 5.0)
        pl.ylim(0.0, 100.0)
        pl.xlabel('time ($s$)')
        pl.ylabel('Number of Nuclei')
        pl.legend(loc='upper right', shadow=True, fontsize='small')
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_results(self):
        pl.plot(self.t, self.n_A, 'b--', label='Number of Nuclei A: Time Constant = 1')
        pl.plot(self.t, self.n_B, 'g', label='Number of Nuclei B: Time Constant = 2')
        pl.title('Double Decay Probelm - Nuclei with Different Time Constans')
        pl.xlim(0.0, 5.0)
        pl.ylim(0.0, 100.0)
        pl.xlabel('time ($s$)')
        pl.ylabel('Number of Nuclei')
        pl.legend(loc='best', shadow=True)
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_results(self):
        pl.plot(self.t, self.n_A, 'b--', label='Number of Nuclei A')
        pl.plot(self.t, self.n_B, 'g', label='Number of Nuclei B')
        pl.title('Double Decay Probelm-Situation 1')
        pl.xlim(0.0, 5.0)
        pl.ylim(0.0, 100.0)
        pl.xlabel('time ($s$)')
        pl.ylabel('Number of Nuclei')
        pl.legend(loc='best', shadow=True)
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_results(self):
        pl.plot(self.t, self.n_A, 'b--', label='Number of Nuclei A: Time Constant = 2')
        pl.plot(self.t, self.n_B, 'g', label='Number of Nuclei B: Time Constant = 1')
        pl.title('Double Decay Probelm - Nuclei with Different Time Constans')
        pl.xlim(0.0, 5.0)
        pl.ylim(0.0, 100.0)
        pl.xlabel('time ($s$)')
        pl.ylabel('Number of Nuclei')
        pl.legend(loc='best', shadow=True)
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_results(self):
        pl.plot(self.t, self.n_A, 'b--', label='Number of Nuclei A: Time Constant = 1')
        pl.plot(self.t, self.n_B, 'g', label='Number of Nuclei B: Time Constant = 2')
        pl.title('Double Decay Probelm - Nuclei with Different Time Constans')
        pl.xlim(0.0, 5.0)
        pl.ylim(0.0, 100.0)
        pl.xlabel('time ($s$)')
        pl.ylabel('Number of Nuclei')
        pl.legend(loc='best', shadow=True)
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_results(self):
        pl.plot(self.t, self.n_A, 'b', label='Number of Nuclei A')
        pl.plot(self.t, self.n_B, 'g+', label='Number of Nuclei B')
        pl.title('Double Decay Probelm-Situation 3')
        pl.xlim(0.0, 5.0)
        pl.ylim(25.0, 75.0)
        pl.xlabel('time ($s$)')
        pl.ylabel('Number of Nuclei')
        pl.legend(loc='best', shadow=True)
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
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)
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_results(self):
        pl.plot(self.t, self.n_A1, 'b--', label='A1')
        pl.plot(self.t, self.n_B1, 'g', label='B1')
        pl.plot(self.t, self.n_A2, 'r--', label='A2')
        pl.plot(self.t, self.n_B2, 'c', label='B2')
        pl.plot(self.t, self.n_A3, 'm', label='A3')
        pl.plot(self.t, self.n_B3, 'k+', label='B3')
        pl.title('Double Decay Probelm-Three Situations')
        pl.xlim(0.0, 5.0)
        pl.ylim(0.0, 100.0)
        pl.xlabel('time ($s$)')
        pl.ylabel('Number of Nuclei')
        pl.legend(loc="best", shadow=True, fontsize='small')
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_results(self):
        pl.plot(self.t, self.n_A, 'b--', label='Number of Nuclei A: Time Constant = 2')
        pl.plot(self.t, self.n_B, 'g', label='Number of Nuclei B: Time Constant = 1')
        pl.title('Double Decay Probelm - Nuclei with Different Time Constans')
        pl.xlim(0.0, 5.0)
        pl.ylim(0.0, 100.0)
        pl.xlabel('time ($s$)')
        pl.ylabel('Number of Nuclei')
        pl.legend(loc='best', shadow=True)
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
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)
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
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)
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_results(self):
        pl.plot(self.t, self.n_A, 'b--', label='Number of Nuclei A')
        pl.plot(self.t, self.n_B, 'g', label='Number of Nuclei B')
        pl.title('Double Decay Probelm-Situation 2')
        pl.xlim(0.0, 5.0)
        pl.ylim(10.0, 90.0)
        pl.xlabel('time ($s$)')
        pl.ylabel('Number of Nuclei')
        pl.legend(loc='best', shadow=True)
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show(self):
        pl.plot(self.t, self.theta, label = '$F_D =$' + str(self.F_D))
        pl.xlim(0, 100)
        pl.ylim(-4, 4)
        pl.xlabel('time ($s$)')
        pl.ylabel('$\\theta$ (radians)')
        pl.legend()
#        pl.text(32, 2, '$\\theta$ versus time $F_D =$' + str(self.F_D))

#pl.subplot(311)
#r1 = routes_to_chaos(amplitude = 1.35)
#r1.calculate()
#r1.show()
#pl.subplot(312)
#r2 = routes_to_chaos(amplitude = 1.44)
#r2.calculate()
#r2.show()
#pl.subplot(313)
#r3 = routes_to_chaos(amplitude = 1.465)
#r3.calculate()
#r3.show()
#pl.show()

#r= routes_to_chaos(amplitude = 1.465)
#r.calculate()
#r.show()
项目:autoxd    作者:nessessary    | 项目源码 | 文件源码
def DrawTs(pl, ts=[], lines = None, title="", high=[], low=[],mid=[], save_file=False,legends=None):
    """?????, ts: closes, save_file: ?????????"""
    pl.figure
    legend = []
    if len(ts)>0:
        pl.plot(ts)
        legend.append('ts')
    if len(high)>0:
        pl.plot(high)
        legend.append('high')
    if len(low)>0:
        pl.plot(low)
        legend.append('low')
    if len(mid)>0:
        pl.plot(mid)
        legend.append('mid')

    prop = fm.FontProperties(fname="c:/windows/fonts/simsun.ttc")
    if title != "":
        pl.title(title, fontproperties=prop)
    if lines != None:
        i = lines
        if i>=len(ts):
            i = len(ts)-1
        pl.plot([i,i], [ts[i]-ts[i]*0.1, ts[i]+ts[i]*0.1], 'g')
        legend.append('lines')
    if legends is not None:
        legend = legends
    pl.legend(legend, loc='upper left')
    if save_file:
        fname = 't3.png'
        pl.savefig(fname)
        return fname
    pl.show()
    pl.close()
项目:autoxd    作者:nessessary    | 项目源码 | 文件源码
def DrawClosesAndVolumes(pl, closes, volumes, zz=None, avg=None, trade_index=None,\
                         title=None, closes_dp=None, closes_bankuai=None):
    """?closes??df???
    closes_dp: ??
    closes_bankuai: ??
    """
    legend = []
    pl.figure
    pl.subplot(211)
    if title != None:
        pl.title(title, fontproperties=getFont())
    pl.plot(closes)
    legend.append('close')
    if zz != None:
        DrawZZ(pl, zz, c='r')
    if avg != None:
        pl.plot(avg)
    if not agl.IsNone(closes_dp):
        pl.plot(closes_dp)
        legend.append('dapan')
    if not agl.IsNone(closes_bankuai):
        pl.plot(closes_bankuai)
        legend.append('bankuai')
    if trade_index != None:
        pl, index, ts = pl, trade_index, closes
        _DrawVLine(pl, index, ts)   
    pl.legend(legend, loc='upper left')
    pl.subplot(212)
    pl.plot(volumes)
    pl.show()
    pl.close()
项目:autoxd    作者:nessessary    | 项目源码 | 文件源码
def legend(self, *args, **kwargs):
        pl.legend(*args, **kwargs)
项目:PyME    作者:vikramsunkara    | 项目源码 | 文件源码
def plot_checked(self):
        import pylab as pl
        pl.ioff()
        from statistics import expectation
        exp = []

        # The expectation plotter
        if len(self._stored_t) != 0:
            pl.figure(2)
            pl.title(" Method %s"%("OFSP"))
            pl.xlabel("Time, t")
            pl.ylabel("Expectation")

            for i in range(len(self._stored_t)):
                exp.append(expectation((self._stored_domain_states[i],self._stored_p[i])))

            EXP = np.array(exp).T

            for i in range(EXP.shape[0]):
                pl.plot(self._stored_t,EXP[i,:],'x-',label=self.model.species[i])
            pl.legend()

        # The probability plotter
        if len(self._probed_t) != 0:
            pl.figure(3)
            pl.title(" Method %s | Probing States over Time "%("OFSP"))
            pl.xlabel("Time, t")
            pl.ylabel("Probability")

            probs = np.array(self._probed_probs).T

            for i in range(probs.shape[0]):
                pl.plot(self._probed_t,probs[i,:],'x-',label=str(self._probed_states[0][:,i]))
            pl.legend()

        pl.show()
项目:PyME    作者:vikramsunkara    | 项目源码 | 文件源码
def plot_checked(self):
        """
        plot_checked plots the expectations of the data check pointed.
        """
        import pylab as pl
        pl.ioff()

        if len(self._stored_t) != 0:
            pl.figure(2)
            pl.title(" Method %s"%(self.model_name))
            pl.xlabel("Time,t")
            pl.ylabel("Expectation")

            exp = []

            for i in range(len(self._stored_t)):
                exp.append(np.sum(np.multiply(self._stored_X[i],self._stored_w[i]),axis=1))

            EXP = np.array(exp).T


            for i in range(EXP.shape[0]):
                pl.plot(self._stored_t,EXP[i,:],'x-',label=self.model.species[i])

            pl.legend()

        # The probability plotter
        if len(self._probed_t) != 0:
            pl.figure(3)
            pl.title(" Method %s | Probing States over Time "%(self.model_name))
            pl.xlabel("Time, t")
            pl.ylabel("Marginal Probability")

            probs = np.array(self._probed_probs).T

            for i in range(probs.shape[0]):
                pl.plot(self._probed_t,probs[i,:],'x-',label=str(self._probed_states[0][self.stoc_vector,i]))
            pl.legend()
        pl.show()