python类figure()的实例源码

figrc.py 文件源码 项目:tap 作者: mfouesneau 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def ezrc(fontSize=22., lineWidth=2., labelSize=None, tickmajorsize=10,
         tickminorsize=5, figsize=(8, 6)):
    """
    slides - Define params to make pretty fig for slides
    """
    from pylab import rc, rcParams
    if labelSize is None:
        labelSize = fontSize + 5
    rc('figure', figsize=figsize)
    rc('lines', linewidth=lineWidth)
    rcParams['grid.linewidth'] = lineWidth
    rcParams['font.sans-serif'] = ['Helvetica']
    rcParams['font.serif'] = ['Helvetica']
    rcParams['font.family'] = ['Times New Roman']
    rc('font', size=fontSize, family='serif', weight='bold')
    rc('axes', linewidth=lineWidth, labelsize=labelSize)
    rc('legend', borderpad=0.1, markerscale=1., fancybox=False)
    rc('text', usetex=True)
    rc('image', aspect='auto')
    rc('ps', useafm=True, fonttype=3)
    rcParams['xtick.major.size'] = tickmajorsize
    rcParams['xtick.minor.size'] = tickminorsize
    rcParams['ytick.major.size'] = tickmajorsize
    rcParams['ytick.minor.size'] = tickminorsize
    rcParams['text.latex.preamble'] = ["\\usepackage{amsmath}"]
plotting.py 文件源码 项目:ugali 作者: DarkEnergySurvey 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def twoDimensionalScatter(title, title_x, title_y,
                          x, y,
                          lim_x = None, lim_y = None,
                          color = 'b', size = 20, alpha=None):
    """
    Create a two-dimensional scatter plot.

    INPUTS
    """
    pylab.figure()

    pylab.scatter(x, y, c=color, s=size, alpha=alpha, edgecolors='none')

    pylab.xlabel(title_x)
    pylab.ylabel(title_y)
    pylab.title(title)
    if type(color) is not str:
        pylab.colorbar()

    if lim_x:
        pylab.xlim(lim_x[0], lim_x[1])
    if lim_y:
        pylab.ylim(lim_y[0], lim_y[1])

############################################################
plot.py 文件源码 项目:spyking-circus 作者: spyking-circus 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def view_trigger_snippets_bis(trigger_snippets, elec_index, save=None):
    fig = pylab.figure()
    ax = fig.add_subplot(1, 1, 1)
    for n in xrange(0, trigger_snippets.shape[2]):
        y = trigger_snippets[:, elec_index, n]
        x = numpy.arange(- (y.size - 1) / 2, (y.size - 1) / 2 + 1)
        b = 0.5 + 0.5 * numpy.random.rand()
        ax.plot(x, y, color=(0.0, 0.0, b), linestyle='solid')
    ax.grid(True)
    ax.set_xlim([numpy.amin(x), numpy.amax(x)])
    ax.set_xlabel("time")
    ax.set_ylabel("amplitude")
    if save is None:
        pylab.show()
    else:
        pylab.savefig(save)
        pylab.close(fig)
    return
plot.py 文件源码 项目:spyking-circus 作者: spyking-circus 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def view_dataset(X, color='blue', title=None, save=None):
    n_components = 2
    pca = PCA(n_components)
    pca.fit(X)
    x = pca.transform(X)
    fig = pylab.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.scatter(x[:, 0], x[:, 1], c=color, s=5, lw=0.1)
    ax.grid(True)
    if title is None:
        ax.set_title("Dataset ({} samples)".format(X.shape[0]))
    else:
        ax.set_title(title + " ({} samples)".format(X.shape[0]))
    ax.set_xlabel("1st component")
    ax.set_ylabel("2nd component")
    if save is None:
        pylab.show()
    else:
        pylab.savefig(save)
        pylab.close(fig)
    return
plot.py 文件源码 项目:spyking-circus 作者: spyking-circus 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def view_loss_curve(losss, title=None, save=None):
    '''Plot loss curve'''
    x_min = 1
    x_max = len(losss) - 1
    fig = pylab.figure()
    ax = fig.gca()
    ax.semilogy(range(x_min, x_max + 1), losss[1:], color='blue', linestyle='solid')
    ax.grid(True, which='both')
    if title is None:
        ax.set_title("Loss curve")
    else:
        ax.set_title(title)
    ax.set_xlabel("iteration")
    ax.set_ylabel("loss")
    ax.set_xlim([x_min - 1, x_max + 1])
    if save is None:
        pylab.show()
    else:
        pylab.savefig(save)
        pylab.close(fig)
    return
two_sigma_financial_modelling.py 文件源码 项目:PortfolioTimeSeriesAnalysis 作者: MizioAnd 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def predicted_vs_actual_y_xgb(self, xgb, best_nrounds, xgb_params, x_train_split, x_test_split, y_train_split,
                                  y_test_split, title_name):
        # Split the training data into an extra set of test
        # x_train_split, x_test_split, y_train_split, y_test_split = train_test_split(x_train, y_train)
        dtrain_split = xgb.DMatrix(x_train_split, label=y_train_split)
        dtest_split = xgb.DMatrix(x_test_split)
        print(np.shape(x_train_split), np.shape(x_test_split), np.shape(y_train_split), np.shape(y_test_split))
        gbdt = xgb.train(xgb_params, dtrain_split, best_nrounds)
        y_predicted = gbdt.predict(dtest_split)
        plt.figure(figsize=(10, 5))
        plt.scatter(y_test_split, y_predicted, s=20)
        rmse_pred_vs_actual = self.rmse(y_predicted, y_test_split)
        plt.title(''.join([title_name, ', Predicted vs. Actual.', ' rmse = ', str(rmse_pred_vs_actual)]))
        plt.xlabel('Actual y')
        plt.ylabel('Predicted y')
        plt.plot([min(y_test_split), max(y_test_split)], [min(y_test_split), max(y_test_split)])
        plt.tight_layout()
wordemb-vis-tsne.py 文件源码 项目:nn4nlp-code 作者: neubig 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def display_data(word_vectors, words, target_words=None):
  target_matrix = word_vectors.copy()
  if target_words:
    target_words = [line.strip().lower() for line in open(target_words)][:2000]
    rows = [words.index(word) for word in target_words if word in words]
    target_matrix = target_matrix[rows,:]
  else:
    rows = np.random.choice(len(word_vectors), size=1000, replace=False)
    target_matrix = target_matrix[rows,:]
  reduced_matrix = tsne(target_matrix, 2);

  Plot.figure(figsize=(200, 200), dpi=100)
  max_x = np.amax(reduced_matrix, axis=0)[0]
  max_y = np.amax(reduced_matrix, axis=0)[1]
  Plot.xlim((-max_x,max_x))
  Plot.ylim((-max_y,max_y))

  Plot.scatter(reduced_matrix[:, 0], reduced_matrix[:, 1], 20);

  for row_id in range(0, len(rows)):
      target_word = words[rows[row_id]]
      x = reduced_matrix[row_id, 0]
      y = reduced_matrix[row_id, 1]
      Plot.annotate(target_word, (x,y))
  Plot.savefig("word_vectors.png");
disp_mp3.py 文件源码 项目:audio_scripts 作者: audiofilter 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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()
vg.py 文件源码 项目:PorousMediaLab 作者: biogeochemistry 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def PlotProps(pars):
    import numpy as np
    import pylab as pl
    import vanGenuchten as vg
    psi = np.linspace(-10, 2, 200)
    pl.figure
    pl.subplot(3, 1, 1)
    pl.plot(psi, vg.thetaFun(psi, pars))
    pl.ylabel(r'$\theta(\psi) [-]$')
    pl.subplot(3, 1, 2)
    pl.plot(psi, vg.CFun(psi, pars))
    pl.ylabel(r'$C(\psi) [1/m]$')
    pl.subplot(3, 1, 3)
    pl.plot(psi, vg.KFun(psi, pars))
    pl.xlabel(r'$\psi [m]$')
    pl.ylabel(r'$K(\psi) [m/d]$')
    # pl.show()
dtopotools_horiz_okada_and_1d.py 文件源码 项目:finite_volume_seismic_model 作者: cjvogl 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def plot_dZ_contours(x, y, dZ, axes=None, dZ_interval=0.5, verbose=False,
                               fig_kwargs={}):
    r"""For plotting seafloor deformation dZ"""
    import matplotlib.pyplot as plt

    dZ_max = max(dZ.max(), -dZ.min()) + dZ_interval
    clines1 = numpy.arange(dZ_interval, dZ_max, dZ_interval)
    clines = list(-numpy.flipud(clines1)) + list(clines1)

    # Create axes if needed
    if axes is None:
        fig = plt.figure(**fig_kwargs)
        axes = fig.add_subplot(111)

    if len(clines) > 0:
        if verbose:
            print "Plotting contour lines at: ",clines
        axes.contour(x, y, dZ, clines, colors='k')
    else:
        print "No contours to plot"

    return axes
dtopotools_horiz_okada_and_1d.py 文件源码 项目:finite_volume_seismic_model 作者: cjvogl 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def plot_okada(self, axes=None, dim=1, displacement='vertical', kwargs={}):
        if (self.dtopo is None):
        raise ValueError("Need to call create_dtopography before plot_okada")

        if (displacement is 'vertical'):
            if axes is None:
                from pylab import figure, subplot
                figure()
                axes = subplot(111)
            if (dim is 1):
                axes.plot(self.dtopo.x*LAT2METER,self.dtopo.dZ[0,0,:],**kwargs)
            elif (dim is 2):
                X,Y = numpy.meshgrid(self.dtopo.x,self.dtopo.y)
                axes.pcolormesh(X*LAT2METER,Y*LAT2METER,self.dtopo.dZ[0,:,:],**kwargs)
        elif (displacement is 'horizontal'):
            if axes is None:
                from pylab import figure, subplot
                figure()
                axes = subplot(111)
            if (dim is 1):
                axes.plot(self.dtopo.x*LAT2METER,self.dtopo.dY[0,0,:],**kwargs)
dtopotools_horiz_okada_and_1d.py 文件源码 项目:finite_volume_seismic_model 作者: cjvogl 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def plot_dZ_contours(x, y, dZ, axes=None, dZ_interval=0.5, verbose=False,
                               fig_kwargs={}):
    r"""For plotting seafloor deformation dZ"""
    import matplotlib.pyplot as plt

    dZ_max = max(dZ.max(), -dZ.min()) + dZ_interval
    clines1 = numpy.arange(dZ_interval, dZ_max, dZ_interval)
    clines = list(-numpy.flipud(clines1)) + list(clines1)

    # Create axes if needed
    if axes is None:
        fig = plt.figure(**fig_kwargs)
        axes = fig.add_subplot(111)

    if len(clines) > 0:
        if verbose:
            print "Plotting contour lines at: ",clines
        axes.contour(x, y, dZ, clines, colors='k')
    else:
        print "No contours to plot"

    return axes
test_visualization.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_axes():
    try:
        import matplotlib
        version = matplotlib.__version__.split("-")[0]
        version = version.split(".")[:2]
        if [int(_) for _ in version] < [0,99]:
            raise ImportError
        import pylab
    except ImportError:
        print("\nSkipping test (pylab not available or too old version)\n")
        return
    fig = pylab.figure()
    axes = fig.add_subplot(111)
    for ctx in [mp, fp]:
        ctx.plot(lambda x: x**2, [0, 3], axes=axes)
        assert axes.get_xlabel() == 'x'
        assert axes.get_ylabel() == 'f(x)'

    fig = pylab.figure()
    axes = fig.add_subplot(111)
    for ctx in [mp, fp]:
        ctx.cplot(lambda z: z, [-2, 2], [-10, 10], axes=axes)
    assert axes.get_xlabel() == 'Re(z)'
    assert axes.get_ylabel() == 'Im(z)'
test_visualization.py 文件源码 项目:twic_close_reading 作者: jarmoza 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_axes():
    try:
        import matplotlib
        version = matplotlib.__version__.split("-")[0]
        version = version.split(".")[:2]
        if [int(_) for _ in version] < [0,99]:
            raise ImportError
        import pylab
    except ImportError:
        print("\nSkipping test (pylab not available or too old version)\n")
        return
    fig = pylab.figure()
    axes = fig.add_subplot(111)
    for ctx in [mp, fp]:
        ctx.plot(lambda x: x**2, [0, 3], axes=axes)
        assert axes.get_xlabel() == 'x'
        assert axes.get_ylabel() == 'f(x)'

    fig = pylab.figure()
    axes = fig.add_subplot(111)
    for ctx in [mp, fp]:
        ctx.cplot(lambda z: z, [-2, 2], [-10, 10], axes=axes)
    assert axes.get_xlabel() == 'Re(z)'
    assert axes.get_ylabel() == 'Im(z)'
test_visualization.py 文件源码 项目:krpcScripts 作者: jwvanderbeck 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_axes():
    try:
        import matplotlib
        version = matplotlib.__version__.split("-")[0]
        version = version.split(".")[:2]
        if [int(_) for _ in version] < [0,99]:
            raise ImportError
        import pylab
    except ImportError:
        print("\nSkipping test (pylab not available or too old version)\n")
        return
    fig = pylab.figure()
    axes = fig.add_subplot(111)
    for ctx in [mp, fp]:
        ctx.plot(lambda x: x**2, [0, 3], axes=axes)
        assert axes.get_xlabel() == 'x'
        assert axes.get_ylabel() == 'f(x)'

    fig = pylab.figure()
    axes = fig.add_subplot(111)
    for ctx in [mp, fp]:
        ctx.cplot(lambda z: z, [-2, 2], [-10, 10], axes=axes)
    assert axes.get_xlabel() == 'Re(z)'
    assert axes.get_ylabel() == 'Im(z)'
old_camera.py 文件源码 项目:yt 作者: yt-project 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def show_mpl(self, im, enhance=True, clear_fig=True):
        if self._pylab is None:
            import pylab
            self._pylab = pylab
        if self._render_figure is None:
            self._render_figure = self._pylab.figure(1)
        if clear_fig: self._render_figure.clf()

        if enhance:
            nz = im[im > 0.0]
            nim = im / (nz.mean() + 6.0 * np.std(nz))
            nim[nim > 1.0] = 1.0
            nim[nim < 0.0] = 0.0
            del nz
        else:
            nim = im
        ax = self._pylab.imshow(nim[:,:,:3]/nim[:,:,:3].max(), origin='upper')
        return ax
old_camera.py 文件源码 项目:yt 作者: yt-project 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def plot_allsky_healpix(image, nside, fn, label = "", rotation = None,
                        take_log = True, resolution=512, cmin=None, cmax=None):
    import matplotlib.figure
    import matplotlib.backends.backend_agg
    if rotation is None: rotation = np.eye(3).astype("float64")

    img, count = pixelize_healpix(nside, image, resolution, resolution, rotation)

    fig = matplotlib.figure.Figure((10, 5))
    ax = fig.add_subplot(1,1,1,projection='aitoff')
    if take_log: func = np.log10
    else: func = lambda a: a
    implot = ax.imshow(func(img), extent=(-np.pi,np.pi,-np.pi/2,np.pi/2),
                       clip_on=False, aspect=0.5, vmin=cmin, vmax=cmax)
    cb = fig.colorbar(implot, orientation='horizontal')
    cb.set_label(label)
    ax.xaxis.set_ticks(())
    ax.yaxis.set_ticks(())
    canvas = matplotlib.backends.backend_agg.FigureCanvasAgg(fig)
    canvas.print_figure(fn)
    return img, count
house_prices.py 文件源码 项目:HousePrices 作者: MizioAnd 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def predicted_vs_actual_sale_price(self, x_train, y_train, title_name):
        # Split the training data into an extra set of test
        x_train_split, x_test_split, y_train_split, y_test_split = train_test_split(x_train, y_train)
        print(np.shape(x_train_split), np.shape(x_test_split), np.shape(y_train_split), np.shape(y_test_split))
        lasso = LassoCV(alphas=[0.0001, 0.0003, 0.0006, 0.001, 0.003, 0.006, 0.01, 0.03, 0.06, 0.1,
                                0.3, 0.6, 1],
                        max_iter=50000, cv=10)
        # lasso = RidgeCV(alphas=[0.0001, 0.0003, 0.0006, 0.001, 0.003, 0.006, 0.01, 0.03, 0.06, 0.1,
        #                         0.3, 0.6, 1], cv=10)

        lasso.fit(x_train_split, y_train_split)
        y_predicted = lasso.predict(X=x_test_split)
        plt.figure(figsize=(10, 5))
        plt.scatter(y_test_split, y_predicted, s=20)
        rmse_pred_vs_actual = self.rmse(y_predicted, y_test_split)
        plt.title(''.join([title_name, ', Predicted vs. Actual.', ' rmse = ', str(rmse_pred_vs_actual)]))
        plt.xlabel('Actual Sale Price')
        plt.ylabel('Predicted Sale Price')
        plt.plot([min(y_test_split), max(y_test_split)], [min(y_test_split), max(y_test_split)])
        plt.tight_layout()
house_prices.py 文件源码 项目:HousePrices 作者: MizioAnd 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def predicted_vs_actual_sale_price_xgb(self, xgb_params, x_train, y_train, seed, title_name):
        # Split the training data into an extra set of test
        x_train_split, x_test_split, y_train_split, y_test_split = train_test_split(x_train, y_train)
        dtrain_split = xgb.DMatrix(x_train_split, label=y_train_split)
        dtest_split = xgb.DMatrix(x_test_split)

        res = xgb.cv(xgb_params, dtrain_split, num_boost_round=1000, nfold=4, seed=seed, stratified=False,
                     early_stopping_rounds=25, verbose_eval=10, show_stdv=True)

        best_nrounds = res.shape[0] - 1
        print(np.shape(x_train_split), np.shape(x_test_split), np.shape(y_train_split), np.shape(y_test_split))
        gbdt = xgb.train(xgb_params, dtrain_split, best_nrounds)
        y_predicted = gbdt.predict(dtest_split)
        plt.figure(figsize=(10, 5))
        plt.scatter(y_test_split, y_predicted, s=20)
        rmse_pred_vs_actual = self.rmse(y_predicted, y_test_split)
        plt.title(''.join([title_name, ', Predicted vs. Actual.', ' rmse = ', str(rmse_pred_vs_actual)]))
        plt.xlabel('Actual Sale Price')
        plt.ylabel('Predicted Sale Price')
        plt.plot([min(y_test_split), max(y_test_split)], [min(y_test_split), max(y_test_split)])
        plt.tight_layout()
test_graphics_others.py 文件源码 项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda 作者: SignalMedia 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_hist_legacy(self):
        _check_plot_works(self.ts.hist)
        _check_plot_works(self.ts.hist, grid=False)
        _check_plot_works(self.ts.hist, figsize=(8, 10))
        _check_plot_works(self.ts.hist, by=self.ts.index.month)
        _check_plot_works(self.ts.hist, by=self.ts.index.month, bins=5)

        fig, ax = self.plt.subplots(1, 1)
        _check_plot_works(self.ts.hist, ax=ax)
        _check_plot_works(self.ts.hist, ax=ax, figure=fig)
        _check_plot_works(self.ts.hist, figure=fig)
        tm.close()

        fig, (ax1, ax2) = self.plt.subplots(1, 2)
        _check_plot_works(self.ts.hist, figure=fig, ax=ax1)
        _check_plot_works(self.ts.hist, figure=fig, ax=ax2)

        with tm.assertRaises(ValueError):
            self.ts.hist(by=self.ts.index, figure=fig)
test_graphics_others.py 文件源码 项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda 作者: SignalMedia 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_grouped_hist_multiple_axes(self):
        # GH 6970, GH 7069
        df = self.hist_df

        fig, axes = self.plt.subplots(2, 3)
        returned = df.hist(column=['height', 'weight', 'category'], ax=axes[0])
        self._check_axes_shape(returned, axes_num=3, layout=(1, 3))
        self.assert_numpy_array_equal(returned, axes[0])
        self.assertIs(returned[0].figure, fig)
        returned = df.hist(by='classroom', ax=axes[1])
        self._check_axes_shape(returned, axes_num=3, layout=(1, 3))
        self.assert_numpy_array_equal(returned, axes[1])
        self.assertIs(returned[0].figure, fig)

        with tm.assertRaises(ValueError):
            fig, axes = self.plt.subplots(2, 3)
            # pass different number of axes from required
            axes = df.hist(column='height', ax=axes)
views.py 文件源码 项目:little-python 作者: JeffyLu 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def stat_personal(self):
        if not os.path.exists(self.file_path + self.ip.ip):
            os.mkdir(self.file_path + self.ip.ip)
            print('make dir %s' % self.ip.ip)
        try:
            items = self.ip.info_set.count()
        except:
            return 0
        my_info = Info.objects.filter(ip = self.ip).order_by('date')
        dates = list(range(len(my_info)))
        bmis = [info.get_bmi() for info in my_info]
        pl.figure('my', figsize = (5.2, 2.8), dpi = 100)
        pl.plot(dates, bmis, '*-', color = '#20b2aa', linewidth = 1.5)
        pl.ylabel(u'BMI?', fontproperties = zhfont)
        pl.ylim(0.0, 50.0)
        pl.savefig(self.file_path + self.ip.ip + '/my.jpg')
        pl.cla()
        return items
final code3.py 文件源码 项目:computational_physics_N2014301020117 作者: yukangnineteen 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def plot(self):
        fig = pl.figure(figsize=(8,8))
        pl.plot(self.n,self.x2ave,'.c')
        pl.plot(self.n,self.x2ave_fit,'k')
        pl.ylim(0,100)
#        for i in range(self.M):
#            self.x = 0
#            for j in range(self.N):
#                for k in range(j):
#                    rnd = random.random()        

#                rnd = random.random()
#                if rnd > 0.5:
#                    self.x +=1
#                else:
#                    self.x -=1
##            print(self.x)
#            self.x2 += math.pow(self.x,2)
##            print(self.x2)
#        self.x2ave = self.x2/self.M
#        print(self.x2ave)
##        return self.x2ave
final code23.py 文件源码 项目:computational_physics_N2014301020117 作者: yukangnineteen 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def plot1(self):
#        fig = pl.figure(figsize=(8,8))
        ax1 = fig.add_subplot(111, projection='3d')
        ax1.scatter(self.x,self.y,self.z,c='k',s=10,marker='.')
#        pl.plot(self.x, self.y,'ok')
#        pl.plot(self.x, self.y,'c')
#        ???
        ax1.set_zlabel('$z$') 
        ax1.set_ylabel('$y$')
        ax1.set_xlabel('$x$')
        ax1.set_title('Random walk in three dimensions')

#    def plot2(self):
##        fig = pl.figure(figsize=(8,8))
#        ax = fig.add_subplot(111, projection='3d')
#        ax1.scatter(self.x,self.y,self.z,c='r',s=100,marker='o')
final code1.py 文件源码 项目:computational_physics_N2014301020117 作者: yukangnineteen 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def plot(self):
        fig = pl.figure(figsize=(8,8))
        pl.plot(self.n,self.xave,'.c')
        pl.plot(self.n,self.xave_fit,'k')
        pl.ylim(-1,1)
#        for i in range(self.M):
#            self.x = 0
#            for j in range(self.N):
#                for k in range(j):
#                    rnd = random.random()        

#                rnd = random.random()
#                if rnd > 0.5:
#                    self.x +=1
#                else:
#                    self.x -=1
##            print(self.x)
#            self.x2 += math.pow(self.x,2)
##            print(self.x2)
#        self.x2ave = self.x2/self.M
#        print(self.x2ave)
##        return self.x2ave
ui.py 文件源码 项目:autoxd 作者: nessessary 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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()
ui.py 文件源码 项目:autoxd 作者: nessessary 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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()
ui.py 文件源码 项目:autoxd 作者: nessessary 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def DrawHist(pl, shs):  
    """??????, shs: ??? array"""
    shs = np.array(shs, dtype=float)
    #print "mean: %.2f"%shs.mean()
    shs = shs[np.isnan(shs) == False]
    if len(shs)>0:
        pl.figure
        pl.hist(shs)
        def ShowHitCount(shs):
            #????
            go_count = len(shs) - len(shs[np.isnan(shs)])
            #???
            if len(shs) != 0:
                v = float(go_count)/ float(len(shs))
                #print("trade rato:%.2f%%"%(v*100))
            #?????
            if go_count>0:
                v = float(len(shs[shs>0]))/float(go_count)
                #print("win rato: %.2f%%"%(v*100))
        pl.show()
        #ShowHitCount(shs)
stock.py 文件源码 项目:autoxd 作者: nessessary 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def plot(self):
        #??????????????????
        pl.figure
        #?????
        a = []
        for h in self.weituo_historys:
            a.append(h.price)
        a = GuiYiHua(a)
        pl.plot(a, 'b')
        #???
        a = np.array(self.total_moneys)
        a = GuiYiHua(a)
        pl.plot(a, 'r')
        pl.legend(['price list', 'money list'])
        pl.show()
        pl.close()

    #???????????????, ??????????
stock.py 文件源码 项目:autoxd 作者: nessessary 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def Unittest_Kline():
    """"""
    kline = Guider("600100", "")
    print(kline.getData(0).date, kline.getLastData().date)

    #kline.myprint()
    obv = kline.OBV()

    pl.figure
    pl.subplot(2,1,1)
    pl.plot(kline.getCloses())
    pl.subplot(2,1,2)
    ma,m2,m3 = kline.MACD()
    pl.plot(ma)
    pl.plot(m2,'r')
    left = np.arange(0, len(m3))
    pl.bar(left,m3)
    #pl.plot(obv, 'y')
    pl.show()


#Unittest_Kstp()    
#
#???????????
#----------------------------------------------------------------------


问题


面经


文章

微信
公众号

扫码关注公众号