Python matplotlib.pyplot 模块,semilogy() 实例源码

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

项目:pycma    作者:CMA-ES    | 项目源码 | 文件源码
def plot_axes_scaling(self, iabscissa=1):
        from matplotlib import pyplot
        if not hasattr(self, 'D'):
            self.load()
        dat = self
        if np.max(dat.D[:, 5:]) == np.min(dat.D[:, 5:]):
            pyplot.text(0, dat.D[-1, 5],
                        'all axes scaling values equal to %s'
                        % str(dat.D[-1, 5]),
                        verticalalignment='center')
            return self  # nothing interesting to plot
        self._enter_plotting()
        pyplot.semilogy(dat.D[:, iabscissa], dat.D[:, 5:], '-b')
        # pyplot.hold(True)
        pyplot.grid(True)
        ax = array(pyplot.axis())
        # ax[1] = max(minxend, ax[1])
        pyplot.axis(ax)
        pyplot.title('Principle Axes Lengths')
        # pyplot.xticks(xticklocs)
        self._xlabel(iabscissa)
        self._finalize_plotting()
        return self
项目:mx-lsoftmax    作者:luoyetx    | 项目源码 | 文件源码
def plot_beta():
    '''plot beta over training
    '''
    beta = args.beta
    scale = args.scale
    beta_min = args.beta_min
    num_epoch = args.num_epoch
    epoch_size = int(float(args.num_examples) / args.batch_size)

    x = np.arange(num_epoch*epoch_size)
    y = beta * np.power(scale, x)
    y = np.maximum(y, beta_min)
    epoch_x = np.arange(num_epoch) * epoch_size
    epoch_y = beta * np.power(scale, epoch_x)
    epoch_y = np.maximum(epoch_y, beta_min)

    # plot beta descent curve
    plt.semilogy(x, y)
    plt.semilogy(epoch_x, epoch_y, 'ro')
    plt.title('beta descent')
    plt.ylabel('beta')
    plt.xlabel('epoch')
    plt.show()
项目:third_person_im    作者:bstadie    | 项目源码 | 文件源码
def plot_axes_scaling(self, iabscissa=1):
        if not hasattr(self, 'D'):
            self.load()
        dat = self
        self._enter_plotting()
        pyplot.semilogy(dat.D[:, iabscissa], dat.D[:, 5:], '-b')
        pyplot.hold(True)
        pyplot.grid(True)
        ax = array(pyplot.axis())
        # ax[1] = max(minxend, ax[1])
        pyplot.axis(ax)
        pyplot.title('Principle Axes Lengths')
        # pyplot.xticks(xticklocs)
        self._xlabel(iabscissa)
        self._finalize_plotting()
        return self
项目:YellowFin    作者:JianGoForIt    | 项目源码 | 文件源码
def plot_loss(loss_list, log_dir, iter_id):
  def running_mean(x, N):
    cumsum = np.cumsum(np.insert(x, 0, 0))
    return (cumsum[N:] - cumsum[:-N]) / N
  plt.figure()
  plt.semilogy(loss_list, '.', alpha=0.2, label="Loss")
  plt.semilogy(running_mean(loss_list,100), label="Average Loss")
  plt.xlabel('Iterations')
  plt.ylabel('Loss')
  plt.legend()
  plt.grid()
  ax = plt.subplot(111)
  ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05),
        ncol=3, fancybox=True, shadow=True)
  plt.savefig(log_dir + "/fig_loss_iter_" + str(iter_id) + ".pdf")
  print("figure plotted")
  plt.close()
项目:rllabplusplus    作者:shaneshixiang    | 项目源码 | 文件源码
def plot_axes_scaling(self, iabscissa=1):
        if not hasattr(self, 'D'):
            self.load()
        dat = self
        self._enter_plotting()
        pyplot.semilogy(dat.D[:, iabscissa], dat.D[:, 5:], '-b')
        pyplot.hold(True)
        pyplot.grid(True)
        ax = array(pyplot.axis())
        # ax[1] = max(minxend, ax[1])
        pyplot.axis(ax)
        pyplot.title('Principle Axes Lengths')
        # pyplot.xticks(xticklocs)
        self._xlabel(iabscissa)
        self._finalize_plotting()
        return self
项目:radwatch-analysis    作者:bearing    | 项目源码 | 文件源码
def plot_xy(x, y, ax=None, xlabel='Energy [keV]', **kwargs):
    """
    Plot x and y as a spectrum.
    """

    if not ax:
        new_plot = True
        plt.figure()
        ax = plt.axes()
    else:
        new_plot = False

    plt.semilogy(x, y, axes=ax, drawstyle='steps-mid', **kwargs)

    if new_plot:
        plt.xlabel(xlabel)
        plt.ylabel('Counts')

    if 'label' in kwargs:
        plt.legend()
    plt.show()

    return ax
项目:Fluid2d    作者:pvthinker    | 项目源码 | 文件源码
def plot_numvisc(diagfile):
    plt.figure()
    nc = Dataset(diagfile)
    t=nc.variables['t'][:]
    ke=nc.variables['ke'][:]
    dkdt=np.diff(ke)/np.diff(t)
    ens=nc.variables['enstrophy'][:]
    ensm=0.5*(ens[1:]+ens[:-1])
#    deltake[visc,res]=-(ke[-1]-ke[0])

#    deltaens[visc,res]=max(medfilt(ens,21))-ens[5]

    visc_tseries = -dkdt/ensm*4.4*np.pi
    visc_num = max(visc_tseries[t[1:]>0.02])
    #print('N=%4i / visc = %4.1e / num = %4.2e'%(N[res],Kdiff[visc],visc_num[res]))
    plt.semilogy(t[1:],visc_tseries)
    plt.xlabel('time')
    plt.ylabel('viscosity (-(1/2V)dE/dt)')
    plt.grid('on')
    plt.show()
项目:cma    作者:hardmaru    | 项目源码 | 文件源码
def plot_axes_scaling(self, iabscissa=1):
        if not hasattr(self, 'D'):
            self.load()
        dat = self
        self._enter_plotting()
        pyplot.semilogy(dat.D[:, iabscissa], dat.D[:, 5:], '-b')
        pyplot.hold(True)
        pyplot.grid(True)
        ax = array(pyplot.axis())
        # ax[1] = max(minxend, ax[1])
        pyplot.axis(ax)
        pyplot.title('Principle Axes Lengths')
        # pyplot.xticks(xticklocs)
        self._xlabel(iabscissa)
        self._finalize_plotting()
        return self
项目:python-mrcz    作者:em-MRCZ    | 项目源码 | 文件源码
def plotSSNR( self ):
        """
        Pulls the SSNR from each class in a _model.star file and plots them, for assessing which class is the 
        'best' class 
        """

        N_particles = np.sum( self.star[b'data_model_groups'][b'GroupNrParticles'] )
        N_classes = self.star[b'data_model_general'][b'NrClasses']

        plt.figure()
        for K in np.arange( N_classes ):
            Resolution = self.star[b'data_model_class_%d'%(K+1)][b'Resolution']
            SSNR = self.star[b'data_model_class_%d'%(K+1)][b'SsnrMap']
            plt.semilogy( Resolution, SSNR+1.0, 
                     label="Class %d: %d" %(K+1,N_particles*self.star[b'data_model_classes'][b'ClassDistribution'][K]) )
        plt.legend( loc = 'best' )
        plt.xlabel( "Resolution ($\AA^{-1}$)" )
        plt.ylabel( "Spectral Signal-to-Noise Ratio" )
        # Let's also display the class distributions in the legend
项目:gail-driver    作者:sisl    | 项目源码 | 文件源码
def plot_axes_scaling(self, iabscissa=1):
        if not hasattr(self, 'D'):
            self.load()
        dat = self
        self._enter_plotting()
        pyplot.semilogy(dat.D[:, iabscissa], dat.D[:, 5:], '-b')
        pyplot.hold(True)
        pyplot.grid(True)
        ax = array(pyplot.axis())
        # ax[1] = max(minxend, ax[1])
        pyplot.axis(ax)
        pyplot.title('Principle Axes Lengths')
        # pyplot.xticks(xticklocs)
        self._xlabel(iabscissa)
        self._finalize_plotting()
        return self
项目:SOAR    作者:araujolma    | 项目源码 | 文件源码
def showHistP(self):
        IterRest = numpy.arange(0,self.NIterRest+1,1)

        if self.histP[IterRest].any() > 0:
            plt.semilogy(IterRest,self.histP[IterRest],'b',label='P')

        if self.histPint[IterRest].any() > 0:
            plt.semilogy(IterRest,self.histPint[IterRest],'k',label='P_int')

        if self.histPpsi[IterRest].any() > 0:
            plt.semilogy(IterRest,self.histPpsi[IterRest],'r',label='P_psi')

        plt.plot(IterRest,self.tol['P']+0.0*IterRest,'-.b',label='tolP')
        print("\nConvergence report on P:")
        plt.grid(True)
        plt.xlabel("Iterations")
        plt.ylabel("P values")
        plt.legend()
        plt.show()

#%% GRADIENT-WISE METHODS
项目:SOAR    作者:araujolma    | 项目源码 | 文件源码
def showHistQ(self):
        IterGrad = numpy.arange(1,self.NIterGrad+1,1)

        if self.histQ[IterGrad].any() > 0:
            plt.semilogy(IterGrad,self.histQ[IterGrad],'b',label='Q')

        if self.histQx[IterGrad].any() > 0:
            plt.semilogy(IterGrad,self.histQx[IterGrad],'k',label='Qx')

        if self.histQu[IterGrad].any() > 0:
            plt.semilogy(IterGrad,self.histQu[IterGrad],'r',label='Qu')

        if self.histQp[IterGrad].any() > 0:
            plt.semilogy(IterGrad,self.histQp[IterGrad],'g',label='Qp')

        if self.histQt[IterGrad].any() > 0:
            plt.semilogy(IterGrad,self.histQt[IterGrad],'y',label='Qt')

        plt.title("Convergence report on Q")
        plt.grid(True)
        plt.xlabel("Iterations")
        plt.ylabel("Q values")
        plt.legend()
        plt.show()
项目:SOAR    作者:araujolma    | 项目源码 | 文件源码
def displayLogErrors(self, legendList):

        if self.count != 0:
            err = numpy.array(self.errorsList)
            for e in err:
                e = numpy.array(e)
            err = numpy.array(err)
            plt.hold(True)
            if numpy.ndim(err) == 2:
                for ii in range(0, len(self.errorsList[-1])):
                    plt.semilogy(range(0, self.count),
                                 abs(err[:, ii]), label=legendList[ii])
                plt.hold(False)
            else:
                plt.semilogy(range(0, self.count),
                             abs(err), label=legendList[0])
            plt.grid(True)
            plt.ylabel("erros []")
            plt.xlabel("iteration number []")
            plt.title(self.name)
#            if self.name == 'All errors':
            plt.legend()
            plt.show()
项目:DCN    作者:alexnowakvila    | 项目源码 | 文件源码
def plot_losses(self, losses, losses_reg, scales=[], fig=0):
        # discriminative losses
        plt.figure(fig)
        plt.clf()
        plt.semilogy(range(0, len(losses)), losses, 'b')
        plt.xlabel('iterations')
        plt.ylabel('Loss')
        plt.title('discriminative loss')
        path = os.path.join(self.path, 'losses.png')
        plt.savefig(path)
        # reg loss
        plt.figure(fig + 1)
        plt.clf()
        plt.semilogy(range(0, len(losses_reg)), losses_reg, 'b')
        plt.xlabel('iterations')
        plt.ylabel('Loss')
        plt.title('split regularization loss')
        path = os.path.join(self.path, 'split_variances.png')
        plt.savefig(path)
项目:DCN    作者:alexnowakvila    | 项目源码 | 文件源码
def plot_losses(self, losses, reward, scales=[], fig=0):
        # discriminative losses
        plt.figure(fig)
        plt.clf()
        plt.semilogy(range(0, len(losses)), losses, 'b')
        plt.xlabel('iterations')
        plt.ylabel('Loss')
        plt.title('loss')
        path = os.path.join(self.path, 'losses.png')
        plt.savefig(path)
        # reward
        plt.figure(fig)
        plt.clf()
        plt.plot(range(0, len(reward)), reward, 'b')
        plt.xlabel('iterations')
        plt.title('kmeans cost')
        path = os.path.join(self.path, 'cost.png')
        plt.savefig(path)
项目:DCN    作者:alexnowakvila    | 项目源码 | 文件源码
def plot_losses(self, losses, losses_reg, scales=[], fig=0):
        # discriminative losses
        plt.figure(fig)
        plt.clf()
        plt.semilogy(range(0, len(losses)), losses, 'b')
        plt.xlabel('iterations')
        plt.ylabel('Loss')
        plt.title('discriminative loss')
        path = os.path.join(self.path, 'losses.png')
        plt.savefig(path)
        # reg loss
        plt.figure(fig + 1)
        plt.clf()
        plt.semilogy(range(0, len(losses_reg)), losses_reg, 'b')
        plt.xlabel('iterations')
        plt.ylabel('Loss')
        plt.title('split regularization loss')
        path = os.path.join(self.path, 'split_variances.png')
        plt.savefig(path)
项目:rllab    作者:rll    | 项目源码 | 文件源码
def plot_axes_scaling(self, iabscissa=1):
        if not hasattr(self, 'D'):
            self.load()
        dat = self
        self._enter_plotting()
        pyplot.semilogy(dat.D[:, iabscissa], dat.D[:, 5:], '-b')
        pyplot.hold(True)
        pyplot.grid(True)
        ax = array(pyplot.axis())
        # ax[1] = max(minxend, ax[1])
        pyplot.axis(ax)
        pyplot.title('Principle Axes Lengths')
        # pyplot.xticks(xticklocs)
        self._xlabel(iabscissa)
        self._finalize_plotting()
        return self
项目:maml_rl    作者:cbfinn    | 项目源码 | 文件源码
def plot_axes_scaling(self, iabscissa=1):
        if not hasattr(self, 'D'):
            self.load()
        dat = self
        self._enter_plotting()
        pyplot.semilogy(dat.D[:, iabscissa], dat.D[:, 5:], '-b')
        pyplot.hold(True)
        pyplot.grid(True)
        ax = array(pyplot.axis())
        # ax[1] = max(minxend, ax[1])
        pyplot.axis(ax)
        pyplot.title('Principle Axes Lengths')
        # pyplot.xticks(xticklocs)
        self._xlabel(iabscissa)
        self._finalize_plotting()
        return self
项目:pyballd    作者:Yurlungur    | 项目源码 | 文件源码
def test_derivatives():
    orders = [4+(2*i) for i in range(12)]
    errors = [test_derivatives_at_order(o) for o in orders]
    plt.semilogy(orders,errors,'bo-',lw=2,ms=12)
    plt.xlabel('order in y-direction',fontsize=16)
    plt.ylabel(r'$|E|_2$',fontsize=16)
    for postfix in ['.png','.pdf']:
        name = 'orthopoly_errors'+postfix
        if USE_FIGS_DIR:
            name = 'figs/' + name
        plt.savefig(name,
                    bbox_inches='tight')
    plt.clf()
项目:pyballd    作者:Yurlungur    | 项目源码 | 文件源码
def test_interpolation():
    xfine = np.linspace(XMIN,XMAX,100)
    yfine = np.linspace(YMIN,YMAX,100)
    orders = [4+(2*i) for i in range(12)]
    errors = [test_interp_at_order(o) for o in orders]
    plt.semilogy(orders,errors,'bo-',lw=2,ms=12)
    plt.xlabel('order in y-direction',fontsize=16)
    plt.ylabel('max(interpolation error)',fontsize=16)
    for postfix in ['.png','.pdf']:
        name = 'orthopoly_interp_errors'+postfix
        if USE_FIGS_DIR:
            name = 'figs/' + name
        plt.savefig(name,
                    bbox_inches='tight')
    plt.clf()
项目:pycma    作者:CMA-ES    | 项目源码 | 文件源码
def plot_correlations(self, iabscissa=1):
        """spectrum of correlation matrix and largest correlation"""
        if not hasattr(self, 'corrspec'):
            self.load()
        if len(self.corrspec) < 2:
            return self
        x = self.corrspec[:, iabscissa]
        y = self.corrspec[:, 6:]  # principle axes
        ys = self.corrspec[:, :6]  # "special" values

        from matplotlib.pyplot import semilogy, text, grid, axis, title
        self._enter_plotting()
        semilogy(x, y, '-c')
        # hold(True)
        semilogy(x[:], np.max(y, 1) / np.min(y, 1), '-r')
        text(x[-1], np.max(y[-1, :]) / np.min(y[-1, :]), 'axis ratio')
        if ys is not None:
            semilogy(x, 1 + ys[:, 2], '-b')
            text(x[-1], 1 + ys[-1, 2], '1 + min(corr)')
            semilogy(x, 1 - ys[:, 5], '-b')
            text(x[-1], 1 - ys[-1, 5], '1 - max(corr)')
            semilogy(x[:], 1 + ys[:, 3], '-k')
            text(x[-1], 1 + ys[-1, 3], '1 + max(neg corr)')
            semilogy(x[:], 1 - ys[:, 4], '-k')
            text(x[-1], 1 - ys[-1, 4], '1 - min(pos corr)')
        grid(True)
        ax = array(axis())
        # ax[1] = max(minxend, ax[1])
        axis(ax)
        title('Spectrum (roots) of correlation matrix')
        # pyplot.xticks(xticklocs)
        self._xlabel(iabscissa)
        self._finalize_plotting()
        return self
项目:third_person_im    作者:bstadie    | 项目源码 | 文件源码
def plot_correlations(self, iabscissa=1):
        """spectrum of correlation matrix and largest correlation"""
        if not hasattr(self, 'corrspec'):
            self.load()
        if len(self.corrspec) < 2:
            return self
        x = self.corrspec[:, iabscissa]
        y = self.corrspec[:, 6:]  # principle axes
        ys = self.corrspec[:, :6]  # "special" values

        from matplotlib.pyplot import semilogy, hold, text, grid, axis, title
        self._enter_plotting()
        semilogy(x, y, '-c')
        hold(True)
        semilogy(x[:], np.max(y, 1) / np.min(y, 1), '-r')
        text(x[-1], np.max(y[-1, :]) / np.min(y[-1, :]), 'axis ratio')
        if ys is not None:
            semilogy(x, 1 + ys[:, 2], '-b')
            text(x[-1], 1 + ys[-1, 2], '1 + min(corr)')
            semilogy(x, 1 - ys[:, 5], '-b')
            text(x[-1], 1 - ys[-1, 5], '1 - max(corr)')
            semilogy(x[:], 1 + ys[:, 3], '-k')
            text(x[-1], 1 + ys[-1, 3], '1 + max(neg corr)')
            semilogy(x[:], 1 - ys[:, 4], '-k')
            text(x[-1], 1 - ys[-1, 4], '1 - min(pos corr)')
        grid(True)
        ax = array(axis())
        # ax[1] = max(minxend, ax[1])
        axis(ax)
        title('Spectrum (roots) of correlation matrix')
        # pyplot.xticks(xticklocs)
        self._xlabel(iabscissa)
        self._finalize_plotting()
        return self
项目:third_person_im    作者:bstadie    | 项目源码 | 文件源码
def __init__(self, func, x, args=(), basis=None, name=None,
                 plot_cmd=pyplot.plot if pyplot else None, load=True):
        """
        Parameters
        ----------
            `func`
                objective function
            `x`
                point in search space, middle point of the sections
            `args`
                arguments passed to `func`
            `basis`
                evaluated points are ``func(x + locations[j] * basis[i])
                for i in len(basis) for j in len(locations)``,
                see `do()`
            `name`
                filename where to save the result
            `plot_cmd`
                command used to plot the data, typically matplotlib pyplots `plot` or `semilogy`
            `load`
                load previous data from file ``str(func) + '.pkl'``

        """
        self.func = func
        self.args = args
        self.x = x
        self.name = name if name else str(func).replace(' ', '_').replace('>', '').replace('<', '')
        self.plot_cmd = plot_cmd  # or semilogy
        self.basis = np.eye(len(x)) if basis is None else basis

        try:
            self.load()
            if any(self.res['x'] != x):
                self.res = {}
                self.res['x'] = x  # TODO: res['x'] does not look perfect
            else:
                print(self.name + ' loaded')
        except:
            self.res = {}
            self.res['x'] = x
项目:Auspex    作者:BBN-Q    | 项目源码 | 文件源码
def nTron_IQ_plot(iq_vals, desc, threshold=0.0):
    iq_vals = iq_vals.real < threshold
    iqr = iq_vals.reshape(desc['Integrated'].dims(), order='C')
    iqrm = np.mean(iqr, axis=0)
    extent = (0.18, 10, 0.14, 0.40)
    aspect = 9.84/0.34
    plt.imshow(iqrm, origin='lower', cmap='RdGy', extent=extent, aspect=aspect)


# def plot_BER(volts, multidata, **kwargs):
#     ber_dat = [switching_BER(data, **kwargs) for data in multidata]
#     mean = []; limit = []; ci68 = []; ci95 = []
#     for datum in ber_dat:
#         mean.append(datum[0])
#         limit.append(datum[1])
#         ci68.append(datum[2])
#         ci95.append(datum[3])
#     mean = np.array(mean)
#     limit = np.array(limit)
#     fig = plt.figure()
#     plt.semilogy(volts, 1-mean, '-o')
#     plt.semilogy(volts, 1-limit, linestyle="--")
#     plt.fill_between(volts, [1-ci[0] for ci in ci68], [1-ci[1] for ci in ci68],  alpha=0.2, edgecolor="none")
#     plt.fill_between(volts, [1-ci[0] for ci in ci95], [1-ci[1] for ci in ci95],  alpha=0.2, edgecolor="none")
#     plt.ylabel("Switching Error Rate", size=14)
#     plt.xlabel("Pulse Voltage (V)", size=14)
#     plt.title("Bit Error Rate", size=16)
#     return fig

# def load_BER_data_legacy(filename):
#     with h5py.File(filename, 'r') as f:
#         dsets = [f[k] for k in f.keys() if "data" in k]
#         data_mean = [np.mean(dset.value, axis=-1) for dset in dsets]
#         volts = [float(dset.attrs['pulse_voltage']) for dset in dsets]
#     return volts, data_mean
项目:crypto-forcast    作者:7yl4r    | 项目源码 | 文件源码
def run(self):
        for i, inp in enumerate(self.input()):
            print(" === " + inp.path + " === \n")
            dta = pandas.read_csv(inp.path,  header=0, quotechar='"')#, names=self.col_names)

            dcol = dta[self.col_names[1]]
            dfcol = dcol.apply(lambda x: float(str(x).split()[0].replace(',', ''))) #  rm commas in values

            # Number of samplepoints
            N = len(dfcol)
            # sample spacing
            T = 1.0 / 800.0
            x = np.linspace(0.0, N*T, N)
            y = dfcol
            yf = scipy.fftpack.fft(y)
            xf = np.linspace(0.0, 1.0/(2.0*T), N/2)

            plt.clf()

            # plot 0-inf
            # plt.plot(xf, 2.0/N * np.abs(yf[0:N/2]))

            # plot 1-inf
            plt.plot(xf[1:], 2.0/N * np.abs(yf[0:int(N/2)])[1:])

            # log-scale
            # plt.semilogy(xf, 2.0/N * np.abs(yf[0:int(N/2)]))

            plt.savefig(self.output()[i].path)

            # with open(self.output()[i].path, 'w') as outfile:
            #     outfile.write("TODO: add results here")
项目:tango    作者:LLNL    | 项目源码 | 文件源码
def plot_err_history(self, savename=None):
        """Plot the self-consistency error vs. iteration number for this timestep.
        Optionally, save the figure to a file.
        """
        fig = plt.figure()
        plt.semilogy(self.iterationNumber, self.errHistory)
        plt.xlabel('Iteration Number')
        plt.ylabel('self-consistency error (rms)')
        if savename is not None:
            fig.savefig(savename, bbox_inches='tight')
        return fig
项目:rllabplusplus    作者:shaneshixiang    | 项目源码 | 文件源码
def plot_correlations(self, iabscissa=1):
        """spectrum of correlation matrix and largest correlation"""
        if not hasattr(self, 'corrspec'):
            self.load()
        if len(self.corrspec) < 2:
            return self
        x = self.corrspec[:, iabscissa]
        y = self.corrspec[:, 6:]  # principle axes
        ys = self.corrspec[:, :6]  # "special" values

        from matplotlib.pyplot import semilogy, hold, text, grid, axis, title
        self._enter_plotting()
        semilogy(x, y, '-c')
        hold(True)
        semilogy(x[:], np.max(y, 1) / np.min(y, 1), '-r')
        text(x[-1], np.max(y[-1, :]) / np.min(y[-1, :]), 'axis ratio')
        if ys is not None:
            semilogy(x, 1 + ys[:, 2], '-b')
            text(x[-1], 1 + ys[-1, 2], '1 + min(corr)')
            semilogy(x, 1 - ys[:, 5], '-b')
            text(x[-1], 1 - ys[-1, 5], '1 - max(corr)')
            semilogy(x[:], 1 + ys[:, 3], '-k')
            text(x[-1], 1 + ys[-1, 3], '1 + max(neg corr)')
            semilogy(x[:], 1 - ys[:, 4], '-k')
            text(x[-1], 1 - ys[-1, 4], '1 - min(pos corr)')
        grid(True)
        ax = array(axis())
        # ax[1] = max(minxend, ax[1])
        axis(ax)
        title('Spectrum (roots) of correlation matrix')
        # pyplot.xticks(xticklocs)
        self._xlabel(iabscissa)
        self._finalize_plotting()
        return self
项目:rllabplusplus    作者:shaneshixiang    | 项目源码 | 文件源码
def __init__(self, func, x, args=(), basis=None, name=None,
                 plot_cmd=pyplot.plot if pyplot else None, load=True):
        """
        Parameters
        ----------
            `func`
                objective function
            `x`
                point in search space, middle point of the sections
            `args`
                arguments passed to `func`
            `basis`
                evaluated points are ``func(x + locations[j] * basis[i])
                for i in len(basis) for j in len(locations)``,
                see `do()`
            `name`
                filename where to save the result
            `plot_cmd`
                command used to plot the data, typically matplotlib pyplots `plot` or `semilogy`
            `load`
                load previous data from file ``str(func) + '.pkl'``

        """
        self.func = func
        self.args = args
        self.x = x
        self.name = name if name else str(func).replace(' ', '_').replace('>', '').replace('<', '')
        self.plot_cmd = plot_cmd  # or semilogy
        self.basis = np.eye(len(x)) if basis is None else basis

        try:
            self.load()
            if any(self.res['x'] != x):
                self.res = {}
                self.res['x'] = x  # TODO: res['x'] does not look perfect
            else:
                print(self.name + ' loaded')
        except:
            self.res = {}
            self.res['x'] = x
项目:Dstl-Satellite-Imagery-Feature-Detection    作者:DeepVoltaire    | 项目源码 | 文件源码
def visualize_training(loss_train, loss_eval, name, acc_train, acc_eval):
    """
    Visualizes training with log_loss, loss and accuracy plot over training and evaluation sets.
    """
    loss_train = np.abs(loss_train)
    loss_eval = np.abs(loss_eval)
    plt.semilogy(loss_train, basey=2)
    plt.semilogy(loss_eval, basey=2, c="red")
    plt.title('{} model loss'.format(name))
    plt.ylabel('loss')
    plt.xlabel('batch')
    plt.legend(['train', 'eval'], loc='upper left')
    os.makedirs("../plots", exist_ok=True)
    plt.savefig("../plots/log_loss_{}.png".format(name), bbox_inches="tight", pad_inches=1)
    plt.clf()
    plt.cla()
    plt.close()

    plt.plot(loss_train)
    plt.plot(loss_eval, c="red")
    plt.title('{} model loss'.format(name))
    plt.ylabel('loss')
    plt.xlabel('batch')
    plt.legend(['train', 'eval'], loc='upper left')
    plt.savefig("../plots/loss_{}.png".format(name), bbox_inches="tight", pad_inches=1)
    plt.clf()
    plt.cla()
    plt.close()

    plt.plot(acc_train)
    plt.plot(acc_eval, c="red")
    plt.title('{} model accuracy'.format(name))
    plt.ylabel('accuracy')
    plt.xlabel('batch')
    plt.ylim([0.9, 1])
    plt.legend(['train', 'eval'], loc='lower right')
    os.makedirs("../plots", exist_ok=True)
    plt.savefig("../plots/acc_{}.png".format(name), bbox_inches="tight", pad_inches=1)
    plt.clf()
    plt.cla()
    plt.close()
项目:decaptcha    作者:ksopyla    | 项目源码 | 文件源码
def save_plots(losses, train_acc, test_acc, training_iters,step,plot_title):

    # iters_steps
    iter_steps = [step *
                k for k in range((training_iters // step) + 1)]

    imh = plt.figure(1, figsize=(15, 12), dpi=160)
    # imh.tight_layout()
    # imh.subplots_adjust(top=0.88)

    imh.suptitle(plot_title)
    plt.subplot(311)
    #plt.plot(iter_steps,losses, '-g', label='Loss')
    plt.semilogy(iter_steps, losses, '-g', label='Loss')
    plt.title('Loss function')
    plt.subplot(312)
    plt.plot(iter_steps, train_acc, '-r', label='Trn Acc')
    plt.title('Train Accuracy')

    plt.subplot(313)
    plt.plot(iter_steps, test_acc, '-r', label='Tst Acc')
    plt.title('Test Accuracy')


    plt.tight_layout()
    plt.subplots_adjust(top=0.88)

    plt.savefig(plot_title)
项目:GPS    作者:golsun    | 项目源码 | 文件源码
def test_est_tau0():

    atm_list = [20]# [1,10,20]
    T0_list = [900]#[600, 800, 1000, 1200, 1400, 1600]
    marker = ['o','x','+']
    for i_atm in range(len(atm_list)):
        atm = atm_list[i_atm]
        tau = []
        for T0 in T0_list:
            tau.append(estimate_tau0(T0, atm))
        #plt.semilogy(1000.0/np.array(T0_list), tau, label=str(atm)+'atm', marker=marker[i_atm],fillstyle='none')
        print tau

    plt.legend(loc='lower right')
    plt.savefig('est_tau.jpg')
项目:radwatch-analysis    作者:bearing    | 项目源码 | 文件源码
def plot_spectrum(spec, ax=None, **kwargs):
    """
    Plot the spectrum, spec (a SpectrumFile object).

    If ax is specified, plot it on that axes.
    Other **kwargs are passed to plt.semilogy.
    """

    if not spec.data.size or not spec.energy.size or np.all(spec.energy == 0):
        raise ValueError('Spectrum must be loaded and calibrated')

    ax = plot_xy(spec.energy, spec.data, ax=ax, **kwargs)

    return ax
项目:Fluid2d    作者:pvthinker    | 项目源码 | 文件源码
def plot_De(data):
    ens=data['ens']
    De = -np.diff(np.log(data['ke']))/np.diff(data['tv'])
    nu = De/np.sqrt(ens[1:])*4*np.pi * data['ke'][1:]
    Re = np.sqrt(data['ke'][1:]) / nu # assuming L=1
    #Re = data['ke'][1:] / ( np.sqrt(data['ens'][1:])* nu) # assuming L=1
    plt.figure()
    plt.semilogy(data['tv'][1:],De,label=r'$D_E$')
    plt.semilogy(data['tv'][1:],nu,label=r'$\nu$')
    plt.semilogy(data['tv'][1:],1/Re,label=r'$Re^{-1}$')
    #plt.semilogy(data['tv'][:],data['ke'][:],label=r'$E$')
    plt.xlabel(r'$t_V$')
    plt.ylabel(r'$D_E,\ \nu$')
    plt.legend()
    plt.show()
项目:cma    作者:hardmaru    | 项目源码 | 文件源码
def plot_correlations(self, iabscissa=1):
        """spectrum of correlation matrix and largest correlation"""
        if not hasattr(self, 'corrspec'):
            self.load()
        if len(self.corrspec) < 2:
            return self
        x = self.corrspec[:, iabscissa]
        y = self.corrspec[:, 6:]  # principle axes
        ys = self.corrspec[:, :6]  # "special" values

        from matplotlib.pyplot import semilogy, hold, text, grid, axis, title
        self._enter_plotting()
        semilogy(x, y, '-c')
        hold(True)
        semilogy(x[:], np.max(y, 1) / np.min(y, 1), '-r')
        text(x[-1], np.max(y[-1, :]) / np.min(y[-1, :]), 'axis ratio')
        if ys is not None:
            semilogy(x, 1 + ys[:, 2], '-b')
            text(x[-1], 1 + ys[-1, 2], '1 + min(corr)')
            semilogy(x, 1 - ys[:, 5], '-b')
            text(x[-1], 1 - ys[-1, 5], '1 - max(corr)')
            semilogy(x[:], 1 + ys[:, 3], '-k')
            text(x[-1], 1 + ys[-1, 3], '1 + max(neg corr)')
            semilogy(x[:], 1 - ys[:, 4], '-k')
            text(x[-1], 1 - ys[-1, 4], '1 - min(pos corr)')
        grid(True)
        ax = array(axis())
        # ax[1] = max(minxend, ax[1])
        axis(ax)
        title('Spectrum (roots) of correlation matrix')
        # pyplot.xticks(xticklocs)
        self._xlabel(iabscissa)
        self._finalize_plotting()
        return self
项目:cma    作者:hardmaru    | 项目源码 | 文件源码
def __init__(self, func, x, args=(), basis=None, name=None,
                 plot_cmd=pyplot.plot if pyplot else None, load=True):
        """
        Parameters
        ----------
            `func`
                objective function
            `x`
                point in search space, middle point of the sections
            `args`
                arguments passed to `func`
            `basis`
                evaluated points are ``func(x + locations[j] * basis[i])
                for i in len(basis) for j in len(locations)``,
                see `do()`
            `name`
                filename where to save the result
            `plot_cmd`
                command used to plot the data, typically matplotlib pyplots `plot` or `semilogy`
            `load`
                load previous data from file ``str(func) + '.pkl'``

        """
        self.func = func
        self.args = args
        self.x = x
        self.name = name if name else str(func).replace(' ', '_').replace('>', '').replace('<', '')
        self.plot_cmd = plot_cmd  # or semilogy
        self.basis = np.eye(len(x)) if basis is None else basis

        try:
            self.load()
            if any(self.res['x'] != x):
                self.res = {}
                self.res['x'] = x  # TODO: res['x'] does not look perfect
            else:
                print(self.name + ' loaded')
        except:
            self.res = {}
            self.res['x'] = x
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def write_histogram(self):

        """
        This function ...
        :return:
        """

        # Inform the user
        log.info("Writing sky histogram to " + self.config.writing.histogram_path +  " ...")

        # Create a masked array
        masked = np.ma.masked_array(self.image.frames.primary, mask=self.mask)
        masked_clipped = np.ma.masked_array(self.image.frames.primary, mask=self.clipped_mask)

        # Create a figure
        fig = plt.figure()

        min = self.mean - 4.0 * self.stddev
        max = self.mean + 4.0 * self.stddev

        # Plot the histograms
        #b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white
        plt.subplot(211)
        plt.hist(masked.compressed(), 200, range=(min,max), alpha=0.5, normed=1, facecolor='g', histtype='stepfilled', label='not clipped')
        if self.config.histogram.log_scale: plt.semilogy()

        plt.subplot(212)
        plt.hist(masked_clipped.compressed(), 200, range=(min,max), alpha=0.5, normed=1, facecolor='g', histtype='stepfilled', label='clipped')
        if self.config.histogram.log_scale: plt.semilogy()

        # Save the figure
        plt.savefig(self.config.writing.histogram_path, bbox_inches='tight', pad_inches=0.25)
        plt.close()

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def write_histogram(self):

        """
        This function ...
        :return:
        """

        # Inform the user
        log.info("Writing sky histogram to " + self.config.writing.histogram_path +  " ...")

        # Create a masked array
        masked = np.ma.masked_array(self.image.frames.primary, mask=self.mask)
        masked_clipped = np.ma.masked_array(self.image.frames.primary, mask=self.clipped_mask)

        # Create a figure
        fig = plt.figure()

        min = self.mean - 4.0 * self.stddev
        max = self.mean + 4.0 * self.stddev

        # Plot the histograms
        #b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white
        plt.subplot(211)
        plt.hist(masked.compressed(), 200, range=(min,max), alpha=0.5, normed=1, facecolor='g', histtype='stepfilled', label='not clipped')
        if self.config.histogram.log_scale: plt.semilogy()

        plt.subplot(212)
        plt.hist(masked_clipped.compressed(), 200, range=(min,max), alpha=0.5, normed=1, facecolor='g', histtype='stepfilled', label='clipped')
        if self.config.histogram.log_scale: plt.semilogy()

        # Save the figure
        plt.savefig(self.config.writing.histogram_path, bbox_inches='tight', pad_inches=0.25)
        plt.close()

    # -----------------------------------------------------------------
项目:babusca    作者:georglind    | 项目源码 | 文件源码
def g2_test(d, phi):
    deltas = np.linspace(-10, 10, 255)
    taus = np.array([0])

    g2n = g2s_num_00(d, phi, 1e8, deltas)
    g2s = g2s_exact_00(d, phi, deltas, taus)

    plt.semilogy(deltas, g2n['g2'], label='num')
    plt.semilogy(deltas, g2s, label='exc')

    plt.legend()

    plt.tight_layout()
    plt.show()
项目:babusca    作者:georglind    | 项目源码 | 文件源码
def test_g2_fock_state():

    N, U, = 2, 0
    gs = (.2, .1)

    model = scattering.Model(
        omegas=[0]*N,
        links=[(0, 1, 1)],
        U=[2*U]*N)

    channels = []
    channels.append(scattering.Channel(site=0, strength=gs[0]))
    channels.append(scattering.Channel(site=N-1, strength=gs[1]))

    setup = scattering.Setup(model, channels)

    Es = np.linspace(-3, 12, 1024)
    dE = 0

    g2s = np.zeros(Es.shape, dtype=np.complex128)
    g2n = np.zeros(Es.shape, dtype=np.complex128)
    g2d = np.zeros(Es.shape, dtype=np.complex128)

    for i, E in enumerate(Es):
        g2s[i], g2n[i], g2d[i] = g2.fock_state(setup, (0, 0), (1, 1), E, dE)

    plt.semilogy(Es, g2s, label='g2')
    plt.semilogy(Es, g2n, label='g2n')
    plt.semilogy(Es, g2d, label='g1g1')
    plt.legend()
    plt.show()
项目:babusca    作者:georglind    | 项目源码 | 文件源码
def g2_test(d, phi):
    # deltas = np.linspace(-10, 10, 255)
    deltas = np.array([0])
    taus = np.linspace(0, 10, 255)

    g2n = g2s_num_00(d, phi, 1e8, deltas, taus)
    g2s = g2s_exact_00(d, phi, deltas, taus)

    plt.semilogy(taus, g2n.T, label='num')
    plt.semilogy(taus, g2s.T, label='exc', ls=':')

    plt.legend()

    plt.tight_layout()
    plt.show()
项目:babusca    作者:georglind    | 项目源码 | 文件源码
def g2_test(d, phi):
    deltas = np.linspace(-10, 10, 255)
    taus = np.array([0])

    g2n = g2s_num_00(d, phi, 1e8, deltas)
    g2s = g2s_exact_00(d, phi, deltas, taus)

    plt.semilogy(deltas, g2n, label='num')
    plt.semilogy(deltas, g2s, label='exc', ls=':')

    plt.legend()

    plt.tight_layout()
    plt.show()
项目:QuantumClassicalDynamics    作者:dibondar    | 项目源码 | 文件源码
def plot_spectrum(sys):
    """
    Plot the High Harmonic Generation spectrum
    """
    # Power spectrum emitted is calculated using the Larmor formula
    #   (https://en.wikipedia.org/wiki/Larmor_formula)
    # which says that the power emitted is proportional to the square of the acceleration
    # i.e., the RHS of the second Ehrenfest theorem

    N = len(sys.P_average_RHS)
    k = np.arange(N)

    # frequency range
    omegas = (k - N / 2) * np.pi / (0.5 * sys.t)

    # spectra of the
    spectrum = np.abs(
        # used windows fourier transform to calculate the spectra
        # rhttp://docs.scipy.org/doc/scipy/reference/tutorial/fftpack.html
        fftpack.fft((-1) ** k * blackman(N) * sys.P_average_RHS)
    ) ** 2
    spectrum /= spectrum.max()

    plt.semilogy(omegas / sys.omega_laser, spectrum)
    plt.ylabel('spectrum (arbitrary units)')
    plt.xlabel('frequency / $\\omega_L$')
    plt.xlim([0, 45.])
    plt.ylim([1e-15, 1.])
项目:spectroscopy    作者:jgoodknight    | 项目源码 | 文件源码
def plotLogScaleY(self):
        plt.figure()
        w = self.omegaSeries
        w = self.mySpace.unitHandler.wavenumbersFromEnergyUnits(w)
        plt.semilogy(w, self.frequencyIntensity / np.max(self.frequencyIntensity))
        plt.title("Absorption Spectrum")
        plt.xlabel(r"$\omega$ (cm$^{-1}$)")
        plt.ylabel(r"$I(\omega)/I_max$")
项目:gail-driver    作者:sisl    | 项目源码 | 文件源码
def plot_correlations(self, iabscissa=1):
        """spectrum of correlation matrix and largest correlation"""
        if not hasattr(self, 'corrspec'):
            self.load()
        if len(self.corrspec) < 2:
            return self
        x = self.corrspec[:, iabscissa]
        y = self.corrspec[:, 6:]  # principle axes
        ys = self.corrspec[:, :6]  # "special" values

        from matplotlib.pyplot import semilogy, hold, text, grid, axis, title
        self._enter_plotting()
        semilogy(x, y, '-c')
        hold(True)
        semilogy(x[:], np.max(y, 1) / np.min(y, 1), '-r')
        text(x[-1], np.max(y[-1, :]) / np.min(y[-1, :]), 'axis ratio')
        if ys is not None:
            semilogy(x, 1 + ys[:, 2], '-b')
            text(x[-1], 1 + ys[-1, 2], '1 + min(corr)')
            semilogy(x, 1 - ys[:, 5], '-b')
            text(x[-1], 1 - ys[-1, 5], '1 - max(corr)')
            semilogy(x[:], 1 + ys[:, 3], '-k')
            text(x[-1], 1 + ys[-1, 3], '1 + max(neg corr)')
            semilogy(x[:], 1 - ys[:, 4], '-k')
            text(x[-1], 1 - ys[-1, 4], '1 - min(pos corr)')
        grid(True)
        ax = array(axis())
        # ax[1] = max(minxend, ax[1])
        axis(ax)
        title('Spectrum (roots) of correlation matrix')
        # pyplot.xticks(xticklocs)
        self._xlabel(iabscissa)
        self._finalize_plotting()
        return self
项目:gail-driver    作者:sisl    | 项目源码 | 文件源码
def __init__(self, func, x, args=(), basis=None, name=None,
                 plot_cmd=pyplot.plot if pyplot else None, load=True):
        """
        Parameters
        ----------
            `func`
                objective function
            `x`
                point in search space, middle point of the sections
            `args`
                arguments passed to `func`
            `basis`
                evaluated points are ``func(x + locations[j] * basis[i])
                for i in len(basis) for j in len(locations)``,
                see `do()`
            `name`
                filename where to save the result
            `plot_cmd`
                command used to plot the data, typically matplotlib pyplots `plot` or `semilogy`
            `load`
                load previous data from file ``str(func) + '.pkl'``

        """
        self.func = func
        self.args = args
        self.x = x
        self.name = name if name else str(func).replace(
            ' ', '_').replace('>', '').replace('<', '')
        self.plot_cmd = plot_cmd  # or semilogy
        self.basis = np.eye(len(x)) if basis is None else basis

        try:
            self.load()
            if any(self.res['x'] != x):
                self.res = {}
                self.res['x'] = x  # TODO: res['x'] does not look perfect
            else:
                print(self.name + ' loaded')
        except:
            self.res = {}
            self.res['x'] = x
项目:BEGAN    作者:artcg    | 项目源码 | 文件源码
def plot_gens(images, rowlabels, losses):
    '''
    From great jupyter notebook by Tim Sainburg:
    http://github.com/timsainb/Tensorflow-MultiGPU-VAE-GAN
    '''
    examples = 8
    fig, ax = plt.subplots(nrows=len(images), ncols=examples, figsize=(18, 8))
    for i in range(examples):
        for j in range(len(images)):
            ax[(j, i)].imshow(create_image(images[j][i]), cmap=plt.cm.gray,
                              interpolation='nearest')
            ax[(j, i)].axis('off')
    title = ''
    for i in rowlabels:
        title += ' {}, '.format(i)
    fig.suptitle('Top to Bottom: {}'.format(title))
    plt.show()
    #fig.savefig(''.join(['imgs/test_',str(epoch).zfill(4),'.png']),dpi=100)
    fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(20, 10), linewidth = 4)

    D_plt, = plt.semilogy((losses['discriminator']), linewidth=4, ls='-',
                          color='b', alpha=.5, label='D')
    G_plt, = plt.semilogy((losses['generator']), linewidth=4, ls='-',
                          color='k', alpha=.5, label='G')

    plt.gca()
    leg = plt.legend(handles=[D_plt, G_plt],
                     fontsize=20)
    leg.get_frame().set_alpha(0.5)
    plt.show()
项目:GMAN    作者:iDurugkar    | 项目源码 | 文件源码
def make_plots(saveto_1, saveto_2, sum_configs, plt_configs):
    seqs = [get_summary_values(*sconf) for sconf in sum_configs]
    t, seq_tups, t_cumstd, seq_tups_cumstd = get_means_stdevs(seqs, step=sum_configs[0][-1])

    for sum_id, pconf in enumerate(plt_configs):
        color, linetyp, alpha, label = pconf
        seq_mean, seq_std = seq_tups[sum_id]
        plt.plot(t, seq_mean, color + linetyp, label=label)
        plt.fill_between(t, seq_mean - seq_std, seq_mean + seq_std, facecolor=color, alpha=alpha)

    plt.legend()
    plt.xlabel('Iteration #')
    plt.ylabel(r'$F(V(D,G))$')
    plt.ylim([-0.8, -0.2])
    plt.tight_layout()
    plt.savefig(saveto_1)

    plt.cla()
    plt.clf()

    for sum_id, pconf in enumerate(plt_configs):
        color, linetyp, alpha, label = pconf
        seq_mean, seq_std = seq_tups_cumstd[sum_id]
        plt.semilogy(t_cumstd,np.exp(seq_mean),color+linetyp,label=label)
        # plt.fill_between(t_cumstd, np.exp(seq_mean - seq_std), np.exp(seq_mean + seq_std), facecolor=color, alpha=alpha)

    plt.semilogy(t_cumstd, np.ones_like(t_cumstd) * 1e-2, 'k--')

    plt.legend()
    plt.xlabel('Iteration #')
    plt.ylabel(r'Cumulative STD of $F(V(D,G))$')
    plt.tight_layout()
    plt.savefig(saveto_2)
项目:tfr    作者:bzamecnik    | 项目源码 | 文件源码
def mean_energy(x_frames):
    """
    Example usage:

    import matplotlib.pyplot as plt
    import soundfile as sf
    from analysis import read_frames

    def analyze_mean_energy(file, frame_size=1024):
        frames, t, fs = read_frames(x, frame_size)
        y = mean_energy(frames)
        plt.semilogy(t, y)
        plt.ylim(0, 1)
    """
    return np.mean(x_frames**2, axis=-1)
项目:sketchrls    作者:LCAV    | 项目源码 | 文件源码
def test_adaptive_filter(x, d, fil, h, rng_seed=0, loops=1):
    """ Run the adaptive filter on data and plot output """

    # fix randomness
    np.random.seed(rng_seed)

    e = np.zeros(x.shape[1])
    ellapsed = 0.

    if x.ndim == 1:
        x = np.array([x])
    elif x.ndim > 2:
        raise ValueError('Too many dimensions')

    for l in xrange(x.shape[0]):

        fil.reset()

        start = time.time()

        w = run_filter(x[l], d[l], fil)

        end = time.time()
        ellapsed += end - start

        e += np.linalg.norm(h[l] - w, axis=1)**2

    M = np.minimum(3, h.shape[1])
    print(fil.name(),fil.w[:M],'time:',ellapsed/loops,'error:',np.linalg.norm(fil.w-h[-1])**2)

    plt.semilogy(e/loops)
    plt.ylim((0, 1.05))

    return e
项目:faampy    作者:ncasuk    | 项目源码 | 文件源码
def _isotherms():
    for temp in np.arange(-140,50,10):
        plt.semilogy(temp + _skewnessTerm(plevs), plevs,  basey=math.e, \
                     color = ('blue' if temp <= 0 else 'red'), \
                     linestyle=('solid' if temp == 0 else 'dashed'), linewidth = .5)