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

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

项目:tap    作者:mfouesneau    | 项目源码 | 文件源码
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}"]
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
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])

############################################################
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
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
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
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
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
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
项目:PortfolioTimeSeriesAnalysis    作者:MizioAnd    | 项目源码 | 文件源码
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()
项目:nn4nlp-code    作者:neubig    | 项目源码 | 文件源码
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");
项目:audio_scripts    作者:audiofilter    | 项目源码 | 文件源码
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()
项目:PorousMediaLab    作者:biogeochemistry    | 项目源码 | 文件源码
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()
项目:finite_volume_seismic_model    作者:cjvogl    | 项目源码 | 文件源码
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
项目:finite_volume_seismic_model    作者:cjvogl    | 项目源码 | 文件源码
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)
项目:finite_volume_seismic_model    作者:cjvogl    | 项目源码 | 文件源码
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
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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)'
项目:twic_close_reading    作者:jarmoza    | 项目源码 | 文件源码
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)'
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
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)'
项目:yt    作者:yt-project    | 项目源码 | 文件源码
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
项目:yt    作者:yt-project    | 项目源码 | 文件源码
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
项目:HousePrices    作者:MizioAnd    | 项目源码 | 文件源码
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()
项目:HousePrices    作者:MizioAnd    | 项目源码 | 文件源码
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()
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
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)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
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)
项目:little-python    作者:JeffyLu    | 项目源码 | 文件源码
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
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
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
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
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')
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
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
项目:autoxd    作者:nessessary    | 项目源码 | 文件源码
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()
项目:autoxd    作者:nessessary    | 项目源码 | 文件源码
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()
项目:autoxd    作者:nessessary    | 项目源码 | 文件源码
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)
项目:autoxd    作者:nessessary    | 项目源码 | 文件源码
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()

    #???????????????, ??????????
项目:autoxd    作者:nessessary    | 项目源码 | 文件源码
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()    
#
#???????????
#----------------------------------------------------------------------
项目:tap    作者:mfouesneau    | 项目源码 | 文件源码
def despine(fig=None, ax=None, top=True, right=True,
            left=False, bottom=False):
    """Remove the top and right spines from plot(s).

    fig : matplotlib figure
        figure to despine all axes of, default uses current figure
    ax : matplotlib axes
        specific axes object to despine
    top, right, left, bottom : boolean
        if True, remove that spine

    """
    if fig is None and ax is None:
        axes = plt.gcf().axes
    elif fig is not None:
        axes = fig.axes
    elif ax is not None:
        axes = [ax]

    for ax_i in axes:
        for side in ["top", "right", "left", "bottom"]:
            ax_i.spines[side].set_visible(not locals()[side])
项目:tap    作者:mfouesneau    | 项目源码 | 文件源码
def setMargins(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None):
        """
        Tune the subplot layout via the meanings (and suggested defaults) are::

            left  = 0.125  # the left side of the subplots of the figure
            right = 0.9    # the right side of the subplots of the figure
            bottom = 0.1   # the bottom of the subplots of the figure
            top = 0.9      # the top of the subplots of the figure
            wspace = 0.2   # the amount of width reserved for blank space between subplots
            hspace = 0.2   # the amount of height reserved for white space between subplots

        The actual defaults are controlled by the rc file

        """
        plt.subplots_adjust(left, bottom, right, top, wspace, hspace)
        plt.draw_if_interactive()
项目:tap    作者:mfouesneau    | 项目源码 | 文件源码
def setNmajors(xval=None, yval=None, ax=None, mode='auto', **kwargs):
        """
        setNmajors - set major tick number
        see figure.MaxNLocator for kwargs
        """
        if ax is None:
                ax = plt.gca()
        if (mode == 'fixed'):
                if xval is not None:
                        ax.xaxis.set_major_locator(MaxNLocator(xval, **kwargs))
                if yval is not None:
                        ax.yaxis.set_major_locator(MaxNLocator(yval, **kwargs))
        elif (mode == 'auto'):
                if xval is not None:
                        ax.xaxis.set_major_locator(AutoLocator(xval, **kwargs))
                if yval is not None:
                        ax.yaxis.set_major_locator(AutoLocator(yval, **kwargs))

        plt.draw_if_interactive()
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
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)'
项目:PyME    作者:vikramsunkara    | 项目源码 | 文件源码
def plot_reg_2D_stoc(X,stoc_vector):

    deter_vec = np.invert(stoc_vector)

    dom_max = np.amax(X[stoc_vector,:]) + 1

    A = np.zeros((dom_max,dom_max))

    stoc_indexs = np.arange(0,X.shape[0],1)[stoc_vector].astype(int)

    for i,deter_element in enumerate(deter_vec):
        if deter_element == True:
            A[X[int(stoc_indexs[0]),:].astype(int), X[int(stoc_indexs[1]),:].astype(int)] = X[i,:]
            pl.figure(i)
            #ax = fig.gca(projection='3d')
            #surf = ax.plot_surface(X[int(stoc_indexs[0]),:].astype(int), X[int(stoc_indexs[1]),:].astype(int),X[i,:], rstride=1, cstride=1,
#cmap=cm.coolwarm,linewidth=0, antialiased=False)
            pl.contour(A,X[i,:])
            #ax.zaxis.set_major_locator(LinearLocator(10))
            #ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
            #fig.colorbar(surf, shrink=0.5, aspect=5)
            pl.show()
项目:RNNVis    作者:myaooo    | 项目源码 | 文件源码
def test():

    points = square_points(10)

    distance = np.zeros((100,100))
    for (i, pointi) in enumerate(points):
        for (j, pointj) in enumerate(points):
            distance[i, j] = norm(pointi - pointj)

    Y, eigs = mds(distance)

    pylab.figure(1)
    pylab.plot(Y[:, 0], Y[:, 1], '.')

    pylab.figure(2)
    pylab.plot(points[:, 0], points[:, 1], '.')

    pylab.show()
项目:fang    作者:rgrosse    | 项目源码 | 文件源码
def show_particles(rbm, state, dataset, display=True, figname='PCD particles', figtitle='PCD particles',
                   size=None):
    try:
        fantasy_vis = rbm.vis_expectations(state.h)
    except:
        fantasy_vis = state

    if size is None:
        size = (dataset.num_rows, dataset.num_cols)
    imgs = [fantasy_vis[j, :np.prod(size)].reshape(size).as_numpy_array()
            for j in range(fantasy_vis.shape[0])]
    visual = misc.norm01(misc.pack(imgs))
    if display:
        pylab.figure(figname)
        pylab.matshow(visual, cmap='gray', fignum=False)
        pylab.title(figtitle)
    return visual
项目:fang    作者:rgrosse    | 项目源码 | 文件源码
def show_chains(rbm, state, dataset, num_particles=20, num_samples=20, show_every=10, display=True,
                figname='Gibbs chains', figtitle='Gibbs chains'):
    samples = gnp.zeros((num_particles, num_samples, state.v.shape[1]))
    state = state[:num_particles, :, :]

    for i in range(num_samples):
        samples[:, i, :] = rbm.vis_expectations(state.h)

        for j in range(show_every):
            state = rbm.step(state)

    npix = dataset.num_rows * dataset.num_cols
    rows = [vm.hjoin([samples[i, j, :npix].reshape((dataset.num_rows, dataset.num_cols)).as_numpy_array()
                      for j in range(num_samples)],
                     normalize=False)
            for i in range(num_particles)]
    grid = vm.vjoin(rows, normalize=False)

    if display:
        pylab.figure(figname)
        pylab.matshow(grid, cmap='gray', fignum=False)
        pylab.title(figtitle)
        pylab.gcf().canvas.draw()

    return grid
项目:fang    作者:rgrosse    | 项目源码 | 文件源码
def plot_eigenspectrum(G, s, nvis, nhid):
    with misc.gnumpy_conversion_check('allow'):
        dim = G.shape[0]
        d, Q = scipy.linalg.eigh(G)
        d = d[::-1]
        Q = Q[:, ::-1]

        pts = np.unique(np.floor(np.logspace(0., np.log10(dim-1), 500)).astype(int)) - 1

        cf = [fisher.correlation_fraction(Q[:, i], s, nvis, nhid) for i in pts]

        pylab.figure()
        pylab.subplot(2, 1, 1)
        pylab.loglog(range(1, dim+1), d, 'b-', lw=2.)
        pylab.xticks([])
        pylab.yticks(fontsize='large')

        pylab.subplot(2, 1, 2)
        pylab.semilogx(pts+1, cf, 'r-', lw=2.)
        pylab.xticks(fontsize='x-large')
        pylab.yticks(fontsize='large')
项目:spyking-circus-ort    作者:spyking-circus    | 项目源码 | 文件源码
def view_positions(self, indices=None, time=None):
        if time is None:
            time = 0
        res = self.synthetic_store.get(indices=indices, variables=['x', 'y', 'z'])
        pylab.figure()

        all_x = []
        all_y = []
        all_z = []
        all_c = []

        for key in res.keys():
            all_x += [res[key]['x'][time]]
            all_y += [res[key]['y'][time]]
            all_z += [res[key]['z'][time]]
            all_c += [self._scalarMap_synthetic.to_rgba(int(key))]

        pylab.scatter(self.probe.positions[0, :], self.probe.positions[1, :], c='k')
        pylab.scatter(all_x, all_y, c=all_c)
        pylab.show()
项目:MIT-CS-lectures    作者:William-Python-King    | 项目源码 | 文件源码
def ansQuest(maxTime,numTrials):
    means=[]
    distLists=performSim(maxTime,numTrials)
    for t in range(maxTime+1):
        tot=0.0
        for distL  in  distLists:
            tot+=distL[t]
        means.append(tot/len(distL))
    pylab.figure()
    pylab.plot(means)
    pylab.xlabel('distance')
    pylab.ylabel('time')
    pylab.title('Average Distance  vs. Time ('+str(len(distLists))+'trials)')
项目:IntroToDeepLearning    作者:robb-brown    | 项目源码 | 文件源码
def plotFields(layer,fieldShape=None,channel=None,figOffset=1,cmap=None,padding=0.01):
    # Receptive Fields Summary
    try:
        W = layer.W
    except:
        W = layer
    wp = W.eval().transpose();
    if len(np.shape(wp)) < 4:       # Fully connected layer, has no shape
        fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape) 
    else:           # Convolutional layer already has shape
        features, channels, iy, ix = np.shape(wp)
        if channel is not None:
            fields = wp[:,channel,:,:]
        else:
            fields = np.reshape(wp,[features*channels,iy,ix])

    perRow = int(math.floor(math.sqrt(fields.shape[0])))
    perColumn = int(math.ceil(fields.shape[0]/float(perRow)))

    fig = mpl.figure(figOffset); mpl.clf()

    # Using image grid
    from mpl_toolkits.axes_grid1 import ImageGrid
    grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
    for i in range(0,np.shape(fields)[0]):
        im = grid[i].imshow(fields[i],cmap=cmap); 

    grid.cbar_axes[0].colorbar(im)
    mpl.title('%s Receptive Fields' % layer.name)

    # old way
    # fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
    # tiled = []
    # for i in range(0,perColumn*perRow,perColumn):
    #   tiled.append(np.hstack(fields2[i:i+perColumn]))
    # 
    # tiled = np.vstack(tiled)
    # mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
    mpl.figure(figOffset+1); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar()
项目:IntroToDeepLearning    作者:robb-brown    | 项目源码 | 文件源码
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
    # Output summary
    try:
        W = layer.output
    except:
        W = layer
    wp = W.eval(feed_dict=feed_dict);
    if len(np.shape(wp)) < 4:       # Fully connected layer, has no shape
        temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
        fields = np.reshape(temp,[1]+fieldShape)
    else:           # Convolutional layer already has shape
        wp = np.rollaxis(wp,3,0)
        features, channels, iy,ix = np.shape(wp)
        if channel is not None:
            fields = wp[:,channel,:,:]
        else:
            fields = np.reshape(wp,[features*channels,iy,ix])

    perRow = int(math.floor(math.sqrt(fields.shape[0])))
    perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
    fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
    tiled = []
    for i in range(0,perColumn*perRow,perColumn):
        tiled.append(np.hstack(fields2[i:i+perColumn]))

    tiled = np.vstack(tiled)
    if figOffset is not None:
        mpl.figure(figOffset); mpl.clf(); 

    mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar();
项目:IntroToDeepLearning    作者:robb-brown    | 项目源码 | 文件源码
def plotFields(layer,fieldShape=None,channel=None,maxFields=25,figName='ReceptiveFields',cmap=None,padding=0.01):
    # Receptive Fields Summary
    W = layer.W
    wp = W.eval().transpose();
    if len(np.shape(wp)) < 4:       # Fully connected layer, has no shape
        fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape)
    else:           # Convolutional layer already has shape
        features, channels, iy, ix = np.shape(wp)
        if channel is not None:
            fields = wp[:,channel,:,:]
        else:
            fields = np.reshape(wp,[features*channels,iy,ix])

    fieldsN = min(fields.shape[0],maxFields)
    perRow = int(math.floor(math.sqrt(fieldsN)))
    perColumn = int(math.ceil(fieldsN/float(perRow)))

    fig = mpl.figure(figName); mpl.clf()

    # Using image grid
    from mpl_toolkits.axes_grid1 import ImageGrid
    grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
    for i in range(0,fieldsN):
        im = grid[i].imshow(fields[i],cmap=cmap);

    grid.cbar_axes[0].colorbar(im)
    mpl.title('%s Receptive Fields' % layer.name)

    # old way
    # fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
    # tiled = []
    # for i in range(0,perColumn*perRow,perColumn):
    #   tiled.append(np.hstack(fields2[i:i+perColumn]))
    #
    # tiled = np.vstack(tiled)
    # mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
    mpl.figure(figName+' Total'); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar()
项目:IntroToDeepLearning    作者:robb-brown    | 项目源码 | 文件源码
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
    # Output summary
    W = layer.output
    wp = W.eval(feed_dict=feed_dict);
    if len(np.shape(wp)) < 4:       # Fully connected layer, has no shape
        temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
        fields = np.reshape(temp,[1]+fieldShape)
    else:           # Convolutional layer already has shape
        wp = np.rollaxis(wp,3,0)
        features, channels, iy,ix = np.shape(wp)
        if channel is not None:
            fields = wp[:,channel,:,:]
        else:
            fields = np.reshape(wp,[features*channels,iy,ix])

    perRow = int(math.floor(math.sqrt(fields.shape[0])))
    perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
    fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
    tiled = []
    for i in range(0,perColumn*perRow,perColumn):
        tiled.append(np.hstack(fields2[i:i+perColumn]))

    tiled = np.vstack(tiled)
    if figOffset is not None:
        mpl.figure(figOffset); mpl.clf();

    mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar();
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def view_waveforms_clusters(data, halo, threshold, templates, amps_lim, n_curves=200, save=False):

    nb_templates = templates.shape[1]
    n_panels     = numpy.ceil(numpy.sqrt(nb_templates))
    mask         = numpy.where(halo > -1)[0]
    clust_idx    = numpy.unique(halo[mask])
    fig          = pylab.figure()    
    square       = True
    center       = len(data[0] - 1)//2
    for count, i in enumerate(xrange(nb_templates)):
        if square:
            pylab.subplot(n_panels, n_panels, count + 1)
            if (numpy.mod(count, n_panels) != 0):
                pylab.setp(pylab.gca(), yticks=[])
            if (count < n_panels*(n_panels - 1)):
                pylab.setp(pylab.gca(), xticks=[])

        subcurves = numpy.where(halo == clust_idx[count])[0]
        for k in numpy.random.permutation(subcurves)[:n_curves]:
            pylab.plot(data[k], '0.5')

        pylab.plot(templates[:, count], 'r')        
        pylab.plot(amps_lim[count][0]*templates[:, count], 'b', alpha=0.5)
        pylab.plot(amps_lim[count][1]*templates[:, count], 'b', alpha=0.5)

        xmin, xmax = pylab.xlim()
        pylab.plot([xmin, xmax], [-threshold, -threshold], 'k--')
        pylab.plot([xmin, xmax], [threshold, threshold], 'k--')
        #pylab.ylim(-1.5*threshold, 1.5*threshold)
        ymin, ymax = pylab.ylim()
        pylab.plot([center, center], [ymin, ymax], 'k--')
        pylab.title('Cluster %d' %i)

    if nb_templates > 0:
        pylab.tight_layout()
    if save:
        pylab.savefig(os.path.join(save[0], 'waveforms_%s' %save[1]))
        pylab.close()
    else:
        pylab.show()
    del fig
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def view_artefact(data, save=False):

    fig          = pylab.figure()    
    pylab.plot(data.T)
    if save:
        pylab.savefig(os.path.join(save[0], 'artefact_%s' %save[1]))
        pylab.close()
    else:
        pylab.show()
    del fig
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def view_raw_templates(file_name, n_temp=2, square=True):

    N_e, N_t, N_tm = templates.shape
    if not numpy.iterable(n_temp):
        if square:
            idx = numpy.random.permutation(numpy.arange(N_tm//2))[:n_temp**2]
        else:
            idx = numpy.random.permutation(numpy.arange(N_tm//2))[:n_temp]
    else:
        idx = n_temp

    import matplotlib.colors as colors
    my_cmap   = pylab.get_cmap('winter')
    cNorm     = colors.Normalize(vmin=0, vmax=N_e)
    scalarMap = pylab.cm.ScalarMappable(norm=cNorm, cmap=my_cmap)

    pylab.figure()
    for count, i in enumerate(idx):
        if square:
            pylab.subplot(n_temp, n_temp, count + 1)
            if (numpy.mod(count, n_temp) != 0):
                pylab.setp(pylab.gca(), yticks=[])
            if (count < n_temp*(n_temp - 1)):
                pylab.setp(pylab.gca(), xticks=[])
        else:
            pylab.subplot(len(idx), 1, count + 1)
            if count != (len(idx) - 1):
                pylab.setp(pylab.gca(), xticks=[])
        for j in xrange(N_e):
            colorVal = scalarMap.to_rgba(j)
            pylab.plot(templates[j, :, i], color=colorVal)

        pylab.title('Template %d' %i)
    pylab.tight_layout()
    pylab.show()
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def view_trigger_snippets(trigger_snippets, chans, save=None):
    # Create output directory if necessary.
    if os.path.exists(save):
        for f in os.listdir(save):
            p = os.path.join(save, f)
            os.remove(p)
        os.removedirs(save)
    os.makedirs(save)
    # Plot figures.
    fig = pylab.figure()
    for (c, chan) in enumerate(chans):
        ax = fig.add_subplot(1, 1, 1)
        for n in xrange(0, trigger_snippets.shape[2]):
            y = trigger_snippets[:, c, 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')
        y = numpy.mean(trigger_snippets[:, c, :], axis=1)
        x = numpy.arange(- (y.size - 1) / 2, (y.size - 1) / 2 + 1)
        ax.plot(x, y, color=(1.0, 0.0, 0.0), linestyle='solid')
        ax.grid(True)
        ax.set_xlim([numpy.amin(x), numpy.amax(x)])
        ax.set_title("Channel %d" %chan)
        ax.set_xlabel("time")
        ax.set_ylabel("amplitude")
        if save is not None:
            # Save plot.
            filename = "channel-%d.png" %chan
            path = os.path.join(save, filename)
            pylab.savefig(path)
        fig.clf()
    if save is None:
        pylab.show()
    else:
        pylab.close(fig)
    return
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def view_mahalanobis_distribution(data_1, data_2, save=None):
    '''Plot Mahalanobis distribution Before and After'''
    fig = pylab.figure()
    ax = fig.add_subplot(1,2,1)
    if len(data_1) == 3:
        d_gt, d_ngt, d_noi = data_1
    elif len(data_1) == 2:
        d_gt, d_ngt = data_1
    if len(data_1) == 3:
        ax.hist(d_noi, bins=50, color='k', alpha=0.5, label="Noise")
    ax.hist(d_ngt, bins=50, color='b', alpha=0.5, label="Non GT")
    ax.hist(d_gt, bins=75, color='r', alpha=0.5, label="GT")
    ax.grid(True)
    ax.set_title("Before")
    ax.set_ylabel("")
    ax.set_xlabel('# Samples')
    ax.set_xlabel('Distances')

    if len(data_2) == 3:
        d_gt, d_ngt, d_noi = data_2
    elif len(data_2) == 2:
        d_gt, d_ngt = data_2
    ax = fig.add_subplot(1,2,2)
    if len(data_2) == 3:
        ax.hist(d_noi, bins=50, color='k', alpha=0.5, label="Noise")
    ax.hist(d_ngt, bins=50, color='b', alpha=0.5, label="Non GT")
    ax.hist(d_gt, bins=75, color='r', alpha=0.5, label="GT")
    ax.grid(True)
    ax.set_title("After")
    ax.set_ylabel("")
    ax.set_xlabel('Distances')


    ax.legend()
    if save is None:
        pylab.show()
    else:
        pylab.savefig(save)
        pylab.close(fig)
    return