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

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

项目:ChiantiPy    作者:chianti-atomic    | 项目源码 | 文件源码
def radLossPlot(self, title=0):
        '''
        to plot the radiative losses vs temperature
        '''
        fontsize = 16
        temp = self.RadLoss['temperature']
        rate = self.RadLoss['rate']
        plt.loglog(temp, rate)
#        plt.ylabel(r'erg  s$^{-1}$  ($\int\,$ N$_e\,$N$_H\,$d${\it l}$)$^{-1}$',fontsize=fontsize)
        plt.xlabel(self.RadLoss['xlabel'],fontsize=fontsize)
        plt.ylabel(self.RadLoss['ylabel'],fontsize=fontsize)
        if title:
            title = 'Radiative loss rate,  minAbund = %10.2e'%(self.MinAbund)
            if self.EDensity.size == 1:
                title += ', density = %10.2e'%(self.EDensity)
            plt.title(title, fontsize=fontsize)
项目:poi    作者:jchluo    | 项目源码 | 文件源码
def plot(self, filename=None, marker='+', color='blue'):
        """Plot Power Law picture.
        filename: if assgin, picture will write to file,
                not show on screen, else show on screen.
        marker  : see http://matplotlib.org/api/markers_api.html
        color   : point color
        """
        plt.loglog(*self.points, linestyle='None', marker=marker, markeredgecolor=color)
        if self.line_ready:
            x = self.points[0]
            x = np.linspace(x[1], max(x), 10)
            y = [self.prob(i) for i in x]
            plt.loglog(x, y, linestyle='-')

        if filename is not None:
            plt.savefig(filename)
            log.debug("plot %s ok." % filename)
        else:
            plt.show()
项目:ConvNetQuake    作者:tperol    | 项目源码 | 文件源码
def fig_memory_usage():

    # FAST memory
    x = [1,3,7,14,30,90,180]
    y_fast = [0.653,1.44,2.94,4.97,9.05,19.9,35.2]
    # ConvNetQuake
    y_convnet = [6.8*1e-5]*7
    # Create figure
    plt.loglog(x,y_fast,"o-")
    plt.hold('on')
    plt.loglog(x,y_convnet,"o-")
    # plot markers
    plt.loglog(x,[1e-5,1e-5,1e-5,1e-5,1e-5,1e-5,1e-5],'o')
    plt.ylabel("Memory usage (GB)")
    plt.xlabel("Continous data duration (days)")
    plt.xlim(1,180)
    plt.grid("on")
    plt.savefig("./figures/memoryusage.eps")
    plt.close()
项目:ConvNetQuake    作者:tperol    | 项目源码 | 文件源码
def fig_run_time():
    # fast run time
    x_fast = [1,3,7,14,30,90,180]
    y_fast = [289,1.13*1e3,2.48*1e3,5.41*1e3,1.56*1e4,
              6.61*1e4,1.98*1e5]
    x_auto = [1,3]
    y_auto = [1.54*1e4, 8.06*1e5]
    x_convnet = [1,3,7,14,30]
    y_convnet = [9,27,61,144,291]
    # create figure
    plt.loglog(x_auto,y_auto,"o-")
    plt.hold('on')
    plt.loglog(x_fast[0:5],y_fast[0:5],"o-")
    plt.loglog(x_convnet,y_convnet,"o-")
    # plot x markers
    plt.loglog(x_convnet,[1e0]*len(x_convnet),'o')
    # plot y markers
    y_markers = [1,60,3600,3600*24]
    plt.plot([1]*4,y_markers,'ko')
    plt.ylabel("run time (s)")
    plt.xlabel("continous data duration (days)")
    plt.xlim(1,35)
    plt.grid("on")
    plt.savefig("./figures/runtimes.eps")
项目:PedWorks    作者:BrnCPrz    | 项目源码 | 文件源码
def degree_histogram(pedgraph):
    """Return a list of the frequency of each degree value.

    Parameters
    ----------
    pedgraph : Networkx graph
       A graph

    Notes
    -----
    Note: the bins are width one, hence len(list) can be large
    (Order(number_of_edges))
    """
    degree_sequence = sorted(nx.degree(pedgraph).values(), reverse=True)  # degree sequence
    # print "Degree sequence", degree_sequence
    dmax = max(degree_sequence)

    plt.loglog(degree_sequence, 'b-', marker='o', markersize=5, markerfacecolor='#FF8C00', antialiased=True,
               color='#000000')
    plt.title("(out)Degree Rank Plot")
    plt.ylabel("(out)Degree")
    plt.xlabel("Rank")

    print "\t   >  Degree histogram plot created in ~/dgRankPlot.png"
    plt.savefig("dgRankPlot.png")
    #plt.show()
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def plotseds_impl(sedfiles, plotfile, labels=None, fluxlabel="Flux", figsize=(10,6), xlim=None, ylim=None):

    # Initialize figure with the appropriate size
    plt.figure(figsize=figsize)
    plt.clf()

    if labels == None: labels = sedfiles

    # setup the figure
    plt.grid(True)

    # loop over sed files and labels
    for sedfile,label in zip(sedfiles,labels):
        data = np.loadtxt(arch.opentext(sedfile))
        if len(data.shape)==2:
            plt.loglog(data[:,0], data[:,1], label=label)
        else:
            return False  # there is just one data point

    # set axis limits if requested
    if xlim != None: plt.xlim(xlim)
    if ylim != None: plt.ylim(ylim)

    # add axis labels and a legend
    plt.gca().xaxis.set_major_formatter(matplotlib.ticker.FormatStrFormatter("%g"))
    plt.xlabel(r"$\lambda\,(\mu \mathrm{m})$", fontsize='large')
    plt.ylabel(fluxlabel, fontsize='large')
    plt.legend()

    # Save the figure
    plt.savefig(plotfile, bbox_inches='tight', pad_inches=0.25)
    plt.close()

    return True

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def plotseds_impl(sedfiles, plotfile, labels=None, fluxlabel="Flux", figsize=(10,6), xlim=None, ylim=None):

    # Initialize figure with the appropriate size
    plt.figure(figsize=figsize)
    plt.clf()

    if labels == None: labels = sedfiles

    # setup the figure
    plt.grid(True)

    # loop over sed files and labels
    for sedfile,label in zip(sedfiles,labels):
        data = np.loadtxt(arch.opentext(sedfile))
        if len(data.shape)==2:
            plt.loglog(data[:,0], data[:,1], label=label)
        else:
            return False  # there is just one data point

    # set axis limits if requested
    if xlim != None: plt.xlim(xlim)
    if ylim != None: plt.ylim(ylim)

    # add axis labels and a legend
    plt.gca().xaxis.set_major_formatter(matplotlib.ticker.FormatStrFormatter("%g"))
    plt.xlabel(r"$\lambda\,(\mu \mathrm{m})$", fontsize='large')
    plt.ylabel(fluxlabel, fontsize='large')
    plt.legend()

    # Save the figure
    plt.savefig(plotfile, bbox_inches='tight', pad_inches=0.25)
    plt.close()

    return True

# -----------------------------------------------------------------
项目:Networks    作者:dencesun    | 项目源码 | 文件源码
def degree_distribution(DG):
    in_degree = DG.in_degree()
    out_degree = DG.out_degree()

    # print(in_degree)
    in_histogram = list([0]) * (in_degree[max(in_degree, key=in_degree.get)] + 1)
    out_histogram = list([0]) * (out_degree[max(out_degree, key=out_degree.get)] + 1)

    for k, v in in_degree.items():
        in_histogram[v] += 1

    # in_histogram = list([0])
    # in_degree_count = Counter(in_degree_sequence)
    # print(sum(in_histogram))

    in_pk = [z/sum(in_histogram) for z in in_histogram]
    # print(in_histogram)
    # print(in_pk)

    plt.title('in_degree')
    plt.xlabel('K+1')
    plt.ylabel('Pk')
    plt.loglog(range(len(in_histogram)), in_pk, 'bo')
    plt.savefig('c-elegans_in_degree_distribution.svg')
    # plt.show()
    for k, v in out_degree.items():
        out_histogram[v] += 1
    # print(len(out_degree_sequence))
    out_pk = [z/sum(out_histogram) for z in out_histogram]
    plt.title('out_degree_distribution')
    plt.xlabel('K+1')
    plt.ylabel('Pk')
    plt.loglog(range(len(out_histogram)), out_pk, 'bo')
    plt.savefig('c-elegans_out_degree_distribution.svg')
项目:TurbPlasma    作者:tulasinandan    | 项目源码 | 文件源码
def tfst(beta=0.6, ca=1., de2=0.000545, theta=0., kmin=1e-2, kmax=10., npoints=200,wrt='n'):
   """
      beta: Total plasma beta,
      ca: Alfven speed based on mean field, 
      de2: me/mi, 
      theta: Angle of propagation in degrees
      kkmin: Minimum Wavenumber of interest in units of kdi
      kkmax: Maximum wavenumber of interest in units of kdi

      Output is an array with 4 columns, k, w-fast, w-alf, w-slow
   """
   import matplotlib.pyplot as plt
   kmmn=np.log10(kmin)
   kmmx=np.log10(kmax)
   kk=np.logspace(kmmn,kmmx,npoints)
   warray=np.zeros((3,npoints))
   for i in range(0,npoints):
      f,s = tfps(beta, ca, de2, theta, kk[i])
      warray[:,i]=f
   plt.loglog(kk,warray[0,:], label='Fast/Magnetosonic')
   plt.loglog(kk,warray[1,:], label='Alfven/KAW')
   plt.loglog(kk,warray[2,:], label='Slow')
   plt.xlabel('$kd_i$')
   plt.ylabel('$\omega/\omega_{ci}$')
   plt.legend(loc='best',fancybox=True,framealpha=0.2)
   plt.title('Dispersion Relation for beta='+str(beta)+' and me/mi='+str(de2))
   plt.show()
   if wrt == 'y':
      ofile=open('disp'+str(theta)+'.dat','w')
      print>> ofile,'#  k', 'Acoustic', 'Alfven', 'Fast'
      for i in range(npoints):
         print>> ofile, kk[i],warray[2,i],warray[1,i],warray[0,i]
      ofile.close()
项目:TurbPlasma    作者:tulasinandan    | 项目源码 | 文件源码
def tfst(beta=0.6, ca=1., de2=0.000545, theta=0., kmin=1e-2, kmax=10., npoints=200,wrt='n'):
   """
      beta: Total plasma beta,
      ca: Alfven speed based on mean field, 
      de2: me/mi, 
      theta: Angle of propagation as fraction of pi/2), 
      kkmin: Minimum Wavenumber of interest in units of kdi
      kkmax: Maximum wavenumber of interest in units of kdi

      Output is an array with 4 columns, k, w-fast, w-alf, w-slow
   """

   kmmn=np.log10(kmin)
   kmmx=np.log10(kmax)
   kk=np.logspace(kmmn,kmmx,npoints)
   warray=np.zeros((3,npoints))
   for i in range(0,npoints):
      f,s = tfps(beta, ca, de2, theta, kk[i])
      warray[:,i]=f
   plt.loglog(kk,warray[0,:], label='Fast/Magnetosonic')
   plt.loglog(kk,warray[1,:], label='Alfven/KAW')
   plt.loglog(kk,warray[2,:], label='Slow')
   plt.xlabel('$kd_i$')
   plt.ylabel('$\omega/\omega_{ci}$')
   plt.legend(loc='best',fancybox=True,framealpha=0.2)
   plt.title('Dispersion Relation for beta='+str(beta)+' and me/mi='+str(de2))
   plt.show()
   if wrt == 'y':
      ofile=open('disp'+str(theta*pi/2.)+'.dat','w')
      print>> ofile,'#  k', 'Acoustic', 'Alfven', 'Fast'
      for i in range(npoints):
         print>> ofile, kk[i],warray[2,i],warray[1,i],warray[0,i]
      ofile.close()
项目:pymake    作者:dtrckd    | 项目源码 | 文件源码
def log_binning(counter_dict,bin_count=35):
    max_x = np.log10(max(counter_dict.keys()))
    max_y = np.log10(max(counter_dict.values()))
    max_base = max([max_x,max_y])

    min_x = np.log10(min(drop_zeros(counter_dict.keys())))

    bins = np.logspace(min_x,max_base,num=bin_count)

    # Based off of: http://stackoverflow.com/questions/6163334/binning-data-in-python-with-scipy-numpy
    #bin_means_y = (np.histogram(counter_dict.keys(),bins,weights=counter_dict.values())[0] / np.histogram(counter_dict.keys(),bins)[0])
    #bin_means_x = (np.histogram(counter_dict.keys(),bins,weights=counter_dict.keys())[0] / np.histogram(counter_dict.keys(),bins)[0])
    bin_means_y = np.histogram(counter_dict.keys(),bins,weights=counter_dict.values())[0]
    bin_means_x = np.histogram(counter_dict.keys(),bins,weights=counter_dict.keys())[0]
    return bin_means_x,bin_means_y

#def plot_degree(y, title=None, noplot=False):
#    if len(y) > 6000:
#        return
#    G = nxG(y)
#    degree = sorted(nx.degree(G).values(), reverse=True)
#    if noplot:
#        return degree
#    #plt.plot(degree)
#    x = np.arange(1, y.shape[0] + 1)
#    fig = plt.figure()
#    plt.loglog(x, degree)
#    if title:
#        plt.title(title)
#    plt.draw()
#
#def plot_degree_(y, title=None):
#    if len(y) > 6000:
#        return
#    G = nxG(y)
#    degree = sorted(nx.degree(G).values(), reverse=True)
#    x = np.arange(1, y.shape[0] + 1)
#    plt.loglog(x, degree)
#    if title:
#        plt.title(title)
项目:AdjMatrix-Generation    作者:weiyiliuIBM    | 项目源码 | 文件源码
def draw_degree(G):
    degree = nx.degree_histogram(G)
    x = range(len(degree))
    y = [z/float(sum(degree)) for z in degree]

    plt.loglog(x,y,color='blue',linewidth=2)
项目:opensbli    作者:opensbli    | 项目源码 | 文件源码
def plot():
    # Plot the error against the grid spacing dx.
    Lx = 2*pi

    degrees = range(2, 13, 2)
    errors = []
    dxs = []
    for d in range(len(degrees)):
        dx = []
        error = []
        for simulation_index in range(0, 5):
            number_of_points = 4*(2**simulation_index)
            dx.append(Lx/number_of_points)            
            error.append(compute_error(degrees[d], simulation_index, number_of_points))
        errors.append(error)
        dxs.append(dx)

    print "Errors in the L2 norm: ", errors
    plt.clf()

    colours_expected = ["-r", "-g", "-b", "-y", "-c", "-k"]
    colours = ["o--r", "o--g", "o--b", "o--y", "o--c", "o--k"]
    for d in range(0, len(degrees)):
        # Plot the errors.
        plt.loglog(dxs[d], errors[d], colours[d], label=r"Order = %d" % degrees[d])

        # Plot the expected convergence line for comparison.
        expected_convergence = (numpy.array([0.8*max(errors[d])*(1.0/2**degrees[d])**i for i in range(len(errors[d]))]))
        plt.loglog(dxs[d], expected_convergence, colours_expected[d], label=r"")

    plt.xlabel(r"Grid spacing $\Delta x$ (m)")
    plt.ylabel(r"Solution error in the L2 norm")
    plt.legend(loc='best', numpoints=1)
    plt.savefig("mms_convergence_analysis.pdf", bbox_inches='tight')
项目:pyballd    作者:Yurlungur    | 项目源码 | 文件源码
def test_errors():
    orders = [4*(i+1) for i in range(6)]
    l1_errors = [None for o in orders]
    l2_errors = [None for o in orders]
    for i,o in enumerate(orders):
        s = PyballdDiscretization(o,r_h,
                                  o,
                                  THETA_MIN,
                                  THETA_MAX,
                                  L=1*r_h)
        R,THETA = s.get_coords_2d()
        X,THETA = s.get_x2d()
        f_ana = f(R,THETA)
        dfdr_ana = dfdr(R,THETA)
        dfdr_ana[-1] = 0
        dfdr_num = s.differentiate_wrt_R(f_ana,1,0)
        dfdr_num[-1] = 0
        delta = dfdr_num - dfdr_ana
        if 2 <= i <= 4:
            plt.plot(X[:,-1],delta[:,-1],lw=3,
                     label="order = {}".format(o))
        l1_errors[i] = np.max(np.abs(delta[1:]))
        l2_errors[i] = s.l2_norm_to_infty(delta)
    plt.xlabel(r'$X$',fontsize=16)
    plt.ylabel('error',fontsize=16)
    plt.legend()
    for postfix in ['.png','.pdf']:
        name = 'domain_pointwise_errors_alg'+postfix
        if USE_FIGS_DIR:
            name = 'figs/' + name
        plt.savefig(name,
                    bbox_inches='tight')
    plt.clf()

    plt.semilogy(orders,l1_errors,'bo--',lw=3,ms=12)
    plt.xlabel('order',fontsize=16)
    plt.ylabel(r'|error|$_\infty$',fontsize=16)
    for postfix in ['.png','.pdf']:
        name = 'domain_l1_errors_alg'+postfix
        if USE_FIGS_DIR:
            name = 'figs/' + name
        plt.savefig(name,
                    bbox_inches='tight')
    plt.clf()

    plt.loglog(orders,l1_errors,'bo--',lw=3,ms=12)
    plt.xlabel('order',fontsize=16)
    plt.ylabel(r'|error|$_\infty$',fontsize=16)
    for postfix in ['.png','.pdf']:
        name = 'domain_l1_errors_alg_loglog'+postfix
        if USE_FIGS_DIR:
            name = 'figs/' + name
        plt.savefig(name,
                    bbox_inches='tight')
    plt.clf()
项目:pyballd    作者:Yurlungur    | 项目源码 | 文件源码
def test_errors():
    orders = [4*(i+1) for i in range(10)]
    l1_errors = [None for o in orders]
    l2_errors = [None for o in orders]
    for i,o in enumerate(orders):
        s = PyballdDiscretization(o,r_h,
                                  o,
                                  THETA_MIN,
                                  THETA_MAX,
                                  L=25*r_h)
        R,THETA = s.get_coords_2d()
        X,THETA = s.get_x2d()
        f_ana = f(R,THETA)
        dfdr_ana = dfdr(R,THETA)
        dfdr_ana[-1] = 0
        dfdr_num = s.differentiate_wrt_R(f_ana,1,0)
        dfdr_num[-1] = 0
        delta = dfdr_num - dfdr_ana
        if 2 <= i <= 4:
            plt.plot(X[:,-1],delta[:,-1],lw=3,
                     label="order = {}".format(o))
        l1_errors[i] = np.max(np.abs(delta[1:]))
        l2_errors[i] = s.l2_norm_to_infty(delta)
    plt.xlabel(r'$X$',fontsize=16)
    plt.ylabel('error',fontsize=16)
    plt.legend()
    for postfix in ['.png','.pdf']:
        name = 'domain_pointwise_errors_exp'+postfix
        if USE_FIGS_DIR:
            name = 'figs/' + name
        plt.savefig(name,
                    bbox_inches='tight')
    plt.clf()

    plt.semilogy(orders,l1_errors,'bo--',lw=3,ms=12)
    plt.xlabel('order',fontsize=16)
    plt.ylabel(r'|error|$_\infty$',fontsize=16)
    for postfix in ['.png','.pdf']:
        name = 'domain_l1_errors_exp'+postfix
        if USE_FIGS_DIR:
            name = 'figs/' + name
        plt.savefig(name,
                    bbox_inches='tight')
    plt.clf()

    plt.loglog(orders,l1_errors,'bo--',lw=3,ms=12)
    plt.xlabel('order',fontsize=16)
    plt.ylabel(r'|error|$_\infty$',fontsize=16)
    for postfix in ['.png','.pdf']:
        name = 'domain_l1_errors_loglog_exp'+postfix
        if USE_FIGS_DIR:
            name = 'figs/' + name
        plt.savefig(name,
                    bbox_inches='tight')
    plt.clf()
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def make_map(self, method, plot=False):

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

        data = np.genfromtxt("./eg_user_files/observations_stack.dat")
        dataID = np.genfromtxt("./eg_user_files/observations_stack.dat", usecols=0, dtype='string')

        wa = np.array([24, 100, 160, 250., 350., 500.])  # wavelengths in um

        # Loop over all pixels
        for i in range(len(data[:, 0])):

            ydata = [data[i, 30], data[i, 34], data[i, 36], data[i, 38], data[i, 40], data[i, 42]]
            yerr = [data[i, 31], data[i, 35], data[i, 37], data[i, 39], data[i, 41], data[i, 43]]
            D = data[i, 1] * 3 * 10 ** 5 / 67.30

            # Do the fit for this pixel
            if method == "grid": t1, t2, mdust, ratio = self.fit_grid(wa, ydata, yerr, D)
            elif method == "genetic": t1, t2, mdust, ratio = self.fit_genetic(wa, ydata, yerr, D)

            if plot:

                plt.plot(Mddist, Mdprob)
                plt.title(dataID[i])
                plt.xlabel('T_cold (K)')
                plt.show()

                print(Md_sav, T1_sav, T2_sav)

                plt.errorbar(wa, ydata, yerr=yerr, fmt='bo')
                x2 = np.arange(10., 600., 0.1)
                plt.loglog()
                plt.title(dataID[i])
                plt.ylim(0.001, 1)
                plt.plot(x2, two_blackbodies(x2, D, np.log10(Mdratio_sav) + Md_sav, T1_sav, np.log10(Mdratio_sav) + Md_sav, T2_sav), 'r', label="best fit")
                plt.xlabel('Wavelength (microns)')
                plt.ylabel('Flux (Jy)')
                plt.plot(x2, blackbody(x2, D, np.log10(Mdratio_sav) + Md_sav, T1_sav), ':', lw=2,
                         label="cold dust: logMd = %s, Tc= %s K " % (np.log10(Mdratio_sav) + Md_sav, T1_sav))
                plt.plot(x2, blackbody(x2, D, np.log10(Mdratio_sav) + Md_sav, T2_sav), ':', lw=2,
                         label="warm dust: logMd = %s, Tc= %s K " % (np.log10(Mdratio_sav) + Md_sav, T2_sav))
                plt.legend(loc=4)
                plt.show()

        plt.legend(frameon=False)
        plt.savefig('fit_bb.png')

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def make_map(self, method, plot=False):

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

        data = np.genfromtxt("./eg_user_files/observations_stack.dat")
        dataID = np.genfromtxt("./eg_user_files/observations_stack.dat", usecols=0, dtype='string')

        wa = np.array([24, 100, 160, 250., 350., 500.])  # wavelengths in um

        # Loop over all pixels
        for i in range(len(data[:, 0])):

            ydata = [data[i, 30], data[i, 34], data[i, 36], data[i, 38], data[i, 40], data[i, 42]]
            yerr = [data[i, 31], data[i, 35], data[i, 37], data[i, 39], data[i, 41], data[i, 43]]
            D = data[i, 1] * 3 * 10 ** 5 / 67.30

            # Do the fit for this pixel
            if method == "grid": t1, t2, mdust, ratio = self.fit_grid(wa, ydata, yerr, D)
            elif method == "genetic": t1, t2, mdust, ratio = self.fit_genetic(wa, ydata, yerr, D)

            if plot:

                plt.plot(Mddist, Mdprob)
                plt.title(dataID[i])
                plt.xlabel('T_cold (K)')
                plt.show()

                print(Md_sav, T1_sav, T2_sav)

                plt.errorbar(wa, ydata, yerr=yerr, fmt='bo')
                x2 = np.arange(10., 600., 0.1)
                plt.loglog()
                plt.title(dataID[i])
                plt.ylim(0.001, 1)
                plt.plot(x2, two_blackbodies(x2, D, np.log10(Mdratio_sav) + Md_sav, T1_sav, np.log10(Mdratio_sav) + Md_sav, T2_sav), 'r', label="best fit")
                plt.xlabel('Wavelength (microns)')
                plt.ylabel('Flux (Jy)')
                plt.plot(x2, blackbody(x2, D, np.log10(Mdratio_sav) + Md_sav, T1_sav), ':', lw=2,
                         label="cold dust: logMd = %s, Tc= %s K " % (np.log10(Mdratio_sav) + Md_sav, T1_sav))
                plt.plot(x2, blackbody(x2, D, np.log10(Mdratio_sav) + Md_sav, T2_sav), ':', lw=2,
                         label="warm dust: logMd = %s, Tc= %s K " % (np.log10(Mdratio_sav) + Md_sav, T2_sav))
                plt.legend(loc=4)
                plt.show()

        plt.legend(frameon=False)
        plt.savefig('fit_bb.png')

    # -----------------------------------------------------------------
项目:PyCS    作者:COSMOGRAIL    | 项目源码 | 文件源码
def psplot(pslist, nbins = 0, filename=None, figsize=(12, 8), showlegend=True):
        """
        Plots a list of PS objects.
        If the PS has a slope, it is plotted as well.

        if nbins > 0, I bin the spectra.

        add option for linear plot ?
        """

        plt.figure(figsize=figsize)
        for ps in pslist:


            if not np.all(np.isfinite(np.log10(ps.p))):
                print "No power to plot (probably flat curve !), skipping this one."
                continue
            # We bin the points

            if nbins > 0:
                logf = np.log10(ps.f[1:]) # we remove the first one
                logbins = np.linspace(np.min(logf), np.max(logf), nbins+1) # So nbins +1 numbers here.
                bins = 10**logbins
                bincenters = 0.5*(bins[:-1] + bins[1:]) # nbins centers
                logbins[0] -= 1.0
                logbins[-1] += 1.0
                binindexes = np.digitize(logf, logbins) # binindexes go from 1 to nbins+1
                binvals = []
                binstds = []
                for i in range(1, nbins+1):
                    vals = ps.p[1:][binindexes == i]
                    binvals.append(np.mean(vals))
                    binstds.append(np.std(vals)/np.sqrt(vals.size))

                bincenters = np.array(bincenters)
                binvals = np.array(binvals)
                binstds = np.array(binstds)

                plt.loglog(bincenters, binvals, marker=".", linestyle="-", color=ps.plotcolour, label = "%s" % (ps))

            else:
                plt.loglog(ps.f, ps.p, marker=".", linestyle="None", color=ps.plotcolour, label = "%s" % (ps))
            if ps.slope != None:
                plt.loglog(ps.slope["f"], ps.slope["p"], marker="None", color=ps.plotcolour, label = "Slope %s = %.3f" % (ps, ps.slope["slope"]))
                plt.axvline(ps.slope["fmin"], color = ps.plotcolour, dashes = (5,5))
                plt.axvline(ps.slope["fmax"], color = ps.plotcolour, dashes = (5,5))

        plt.xlabel("Frequency [1/days]")
        plt.ylabel("Power")

        if showlegend:
            plt.legend()

        #plt.text(np.min(10**fitx), np.max(10**pfit), "Log slope : %.2f" % (popt[0]), color="red")


        if filename:
            plt.save(filename)
        else:
            plt.show()
项目:bitcoin_tools    作者:sr-gi    | 项目源码 | 文件源码
def plot_distribution(xs, ys, title, xlabel, ylabel, log_axis=None, save_fig=False, legend=None, legend_loc=1,
                      font_size=20, y_sup_lim=None):
    """
    Plots a set of values (xs, ys) with matplotlib.

    :param xs: either a list with x values or a list of lists, representing different sample sets to be plotted in the
    same figure.
    :param ys: either a list with y values or a list of lists, representing different sample sets to be plotted in the
    same figure.
    :param title: String, plot title
    :param xlabel: String, label on the x axis
    :param ylabel: String, label on the y axis
    :param log_axis: String (accepted values are False, "x", "y" or "xy"), determines which axis are plotted using
    logarithmic scale
    :param save_fig: String, figure's filename or False (to show the interactive plot)
    :param legend: list of strings with legend entries or None (if no legend is needed)
    :param legend_loc: integer, indicates the location of the legend (if present)
    :param font_size: integer, title, xlabel and ylabel font size
    :param y_sup_lim: float, y axis superior limit (if None or not present, use default matplotlib value)
    :return: None
    :type: None
    """

    plt.figure()
    ax = plt.subplot(111)

    # Plot data
    if not (isinstance(xs[0], list) or isinstance(xs[0], np.ndarray)):
        plt.plot(xs, ys)  # marker='o'
    else:
        for i in range(len(xs)):
            plt.plot(xs[i], ys[i], ' ', linestyle='solid')  # marker='o'

    # Plot title and xy labels
    plt.title(title, {'color': 'k', 'fontsize': font_size})
    plt.ylabel(ylabel, {'color': 'k', 'fontsize': font_size})
    plt.xlabel(xlabel, {'color': 'k', 'fontsize': font_size})

    # Change axis to log scale
    if log_axis == "y":
        plt.yscale('log')
    elif log_axis == "x":
        plt.xscale('log')
    elif log_axis == "xy":
        plt.loglog()

    # Include legend
    if legend:
        lgd = ax.legend(legend, loc=legend_loc)

    # Force y limit
    if y_sup_lim:
        ymin, ymax = plt.ylim()
        plt.ylim(ymin, y_sup_lim)

    # Output result
    if save_fig:
        plt.savefig(CFG.figs_path + save_fig + '.pdf', format='pdf', dpi=600)
        plt.close()
    else:
        plt.show()
项目:ChiantiPy    作者:chianti-atomic    | 项目源码 | 文件源码
def intensityRatioInterpolate(self,data, scale = 'lin', plot=0, verbose=0):
        '''
        to take a set of date and interpolate against the IntensityRatio
        the scale can be one of 'lin'/'linear' [default], 'loglog', 'logx', 'logy',
        '''
        # first, what variable to use
        if self.IntensityRatio['temperature'].max() > self.IntensityRatio['temperature'].min():
            x = self.IntensityRatio['ratio']
            y = self.IntensityRatio['temperature']
            if verbose:
                print('using temperature with %i5 values'%(len(x)))
                print(' number of values')
        else:
            x = self.IntensityRatio['ratio']
            y = self.IntensityRatio['eDensity']
        #
        if x[0] > x[-1]:
            x = sorted(x)
            sy = []
            for idx in range(len(y) -1, -1, -1):
                sy.append(y[idx])
        else:
            sy = y
        #
        if 'lin' in scale:
            y2 = interpolate.splrep(x, sy, s=0)
            interpolatedData = interpolate.splev(data,y2)
            if plot:
                plt.plot(sy, x)
                plt.plot(interpolatedData, data, 'bD')
        elif scale == 'loglog':
            y2 = interpolate.splrep(np.log(x), np.log(sy), s=0)
            interpolatedData = np.exp(interpolate.splev(np.log(data),y2))
            if plot:
                plt.loglog(sy, x)
                plt.loglog(interpolatedData, data, 'bD')
        elif scale == 'logx':
            y2 = interpolate.splrep(x, np.log(sy), s=0)
            interpolatedData = np.exp(interpolate.splev(data,y2))
            if plot:
                plt.semilogx(sy, x)
                plt.semilogx(interpolatedData, data, 'bD')
        elif scale == 'logy':
            y2 = interpolate.splrep(np.log(x), sy, s=0)
            interpolatedData = interpolate.splev(np.log(data),y2)
            if plot:
                plt.semilogy(sy, x)
                plt.semilogy(interpolatedData, data, 'bD')
        else:
            print(' scale not understood = %s'%(scale))
        for i, avalue in enumerate(interpolatedData):
            print(' data, value = %12.3e %12.3e'%(data[i], avalue))
        self.IntensityRatioInterpolated = {'data':data, 'value':interpolatedData}