当前位置: 首页>>代码示例>>Python>>正文


Python FontProperties.set_name方法代码示例

本文整理汇总了Python中matplotlib.font_manager.FontProperties.set_name方法的典型用法代码示例。如果您正苦于以下问题:Python FontProperties.set_name方法的具体用法?Python FontProperties.set_name怎么用?Python FontProperties.set_name使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.font_manager.FontProperties的用法示例。


在下文中一共展示了FontProperties.set_name方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: format_plot

# 需要导入模块: from matplotlib.font_manager import FontProperties [as 别名]
# 或者: from matplotlib.font_manager.FontProperties import set_name [as 别名]
def format_plot(axes, xlim=None, ylim=None, xlabel='', ylabel=''):
    '''format 2d-plot black and with with times legends 
    '''
    #-------------------------------------------------------------------
    # configure the style of the font to be used for labels and ticks
    #-------------------------------------------------------------------
    #
    from matplotlib.font_manager import FontProperties
    font = FontProperties()
    font.set_name('Script MT')
    font.set_family('serif')
    font.set_style('normal')
#    font.set_size('small')
    font.set_size('large')
    font.set_variant('normal')
    font.set_weight('medium')
    
    if xlim != None and ylim != None:
        axes.axis([0, xlim, 0., ylim], fontproperties=font)

    # format ticks for plot
    #
    locs, labels = axes.xticks()
    axes.xticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font)
    axes.xlabel(xlabel, fontproperties=font)

    locs, labels = axes.yticks()
    axes.yticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font)
    axes.ylabel(ylabel, fontproperties=font)
开发者ID:sarosh-quraishi,项目名称:simvisage,代码行数:31,代码来源:show_results.py

示例2: show_network

# 需要导入模块: from matplotlib.font_manager import FontProperties [as 别名]
# 或者: from matplotlib.font_manager.FontProperties import set_name [as 别名]
    def show_network(self):
        """!
        @brief Shows connections in the network. It supports only 2-d and 3-d representation.
        
        """
        
        if (self.__ccore_network_pointer is not None):
            raise NameError("Not supported for CCORE");
        
        dimension = len(self._osc_loc[0]);
        if ( (dimension != 3) and (dimension != 2) ):
            raise NameError('Network that is located in different from 2-d and 3-d dimensions can not be represented');
        
        from matplotlib.font_manager import FontProperties;
        from matplotlib import rcParams;
    
        rcParams['font.sans-serif'] = ['Arial'];
        rcParams['font.size'] = 12;

        fig = plt.figure();
        axes = None;
        if (dimension == 2):
            axes = fig.add_subplot(111);
        elif (dimension == 3):
            axes = fig.gca(projection='3d');
        
        surface_font = FontProperties();
        surface_font.set_name('Arial');
        surface_font.set_size('12');
        
        for i in range(0, self._num_osc, 1):
            if (dimension == 2):
                axes.plot(self._osc_loc[i][0], self._osc_loc[i][1], 'bo');  
                if (self._conn_represent == conn_represent.MATRIX):
                    for j in range(i, self._num_osc, 1):    # draw connection between two points only one time
                        if (self.has_connection(i, j) == True):
                            axes.plot([self._osc_loc[i][0], self._osc_loc[j][0]], [self._osc_loc[i][1], self._osc_loc[j][1]], 'b-', linewidth = 0.5);    
                            
                else:
                    for j in self.get_neighbors(i):
                        if ( (self.has_connection(i, j) == True) and (i > j) ):     # draw connection between two points only one time
                            axes.plot([self._osc_loc[i][0], self._osc_loc[j][0]], [self._osc_loc[i][1], self._osc_loc[j][1]], 'b-', linewidth = 0.5);    
            
            elif (dimension == 3):
                axes.scatter(self._osc_loc[i][0], self._osc_loc[i][1], self._osc_loc[i][2], c = 'b', marker = 'o');
                
                if (self._conn_represent == conn_represent.MATRIX):
                    for j in range(i, self._num_osc, 1):    # draw connection between two points only one time
                        if (self.has_connection(i, j) == True):
                            axes.plot([self._osc_loc[i][0], self._osc_loc[j][0]], [self._osc_loc[i][1], self._osc_loc[j][1]], [self._osc_loc[i][2], self._osc_loc[j][2]], 'b-', linewidth = 0.5);
                        
                else:
                    for j in self.get_neighbors(i):
                        if ( (self.has_connection(i, j) == True) and (i > j) ):     # draw connection between two points only one time
                            axes.plot([self._osc_loc[i][0], self._osc_loc[j][0]], [self._osc_loc[i][1], self._osc_loc[j][1]], [self._osc_loc[i][2], self._osc_loc[j][2]], 'b-', linewidth = 0.5);
                               
        plt.grid();
        plt.show();
开发者ID:Gudui,项目名称:pyclustering,代码行数:60,代码来源:syncnet.py

示例3: plot

# 需要导入模块: from matplotlib.font_manager import FontProperties [as 别名]
# 或者: from matplotlib.font_manager.FontProperties import set_name [as 别名]
    def plot(self, n_bins=100):
        """
        Plots MCMC posterior data.
        """

        from matplotlib.font_manager import FontProperties
        import matplotlib.pyplot as plt

        font = FontProperties()
        font.set_name('serif')
        plt.style.use('classic')

        # plot chains versus iterations.
        plt.figure(1)

        for num, parameter in zip(range(self.n_params), self.parameters):
            plt.subplot(self.n_params, 1, num + 1)
            plt.plot(self.posteriors[parameter], 'b-')

        plt.figure(2)

        from matplotlib.gridspec import GridSpec
        gs = GridSpec(self.n_params, self.n_params)

        count = 0

        for num1, parameter1 in zip(range(self.n_params), self.parameters):
            for num2, parameter2 in zip(range(self.n_params), self.parameters):
                if (num1 == num2):
                    plt.subplot(gs[num1, num2])
                    plt.hist(self.posteriors[parameter1], bins=n_bins, histtype='step')
                    plt.xticks([])
                    plt.yticks([])
                elif (num1 > num2):
                    plt.subplot(gs[num1, num2])
                    hist2D, xedges, yedges = np.histogram2d(self.posteriors[parameter2], self.posteriors[parameter1], bins=50)
                    dx = xedges[1] - xedges[0]
                    dy = yedges[1] - yedges[0]
                    x = np.linspace(xedges[0] + dx, xedges[len(xedges)-2] + dx, num=len(xedges)-1)
                    y = np.linspace(yedges[0] + dy, yedges[len(yedges)-2] + dy, num=len(yedges)-1)
                    plt.pcolormesh(x, y, hist2D, cmap='Blues')
                else:
                    pass
                count += 1

        plt.show()
开发者ID:emmanuelfonseca,项目名称:PSRpy,代码行数:48,代码来源:sampler.py

示例4: set_ax_param

# 需要导入模块: from matplotlib.font_manager import FontProperties [as 别名]
# 或者: from matplotlib.font_manager.FontProperties import set_name [as 别名]
def set_ax_param(ax, x_title = None, y_title = None, x_lim = None, y_lim = None, x_labels = True, y_labels = True, grid = True):
    """!
    @brief Sets parameters for matplotlib ax.
    
    @param[in] ax (Axes): Axes for which parameters should applied.
    @param[in] x_title (string): Title for Y.
    @param[in] y_title (string): Title for X.
    @param[in] x_lim (double): X limit.
    @param[in] y_lim (double): Y limit.
    @param[in] x_labels (bool): If True - shows X labels.
    @param[in] y_labels (bool): If True - shows Y labels.
    @param[in] grid (bool): If True - shows grid.
    
    """
    from matplotlib.font_manager import FontProperties;
    from matplotlib import rcParams;
    
    if (_platform == "linux") or (_platform == "linux2"):
        rcParams['font.sans-serif'] = ['Liberation Serif'];
    else:
        rcParams['font.sans-serif'] = ['Arial'];
        
    rcParams['font.size'] = 12;
        
    surface_font = FontProperties();
    if (_platform == "linux") or (_platform == "linux2"):
        surface_font.set_name('Liberation Serif');
    else:
        surface_font.set_name('Arial');
        
    surface_font.set_size('12');
    
    if (y_title is not None): ax.set_ylabel(y_title, fontproperties = surface_font);
    if (x_title is not None): ax.set_xlabel(x_title, fontproperties = surface_font);
    
    if (x_lim is not None): ax.set_xlim(x_lim[0], x_lim[1]);
    if (y_lim is not None): ax.set_ylim(y_lim[0], y_lim[1]);
    
    if (x_labels is False): ax.xaxis.set_ticklabels([]);
    if (y_labels is False): ax.yaxis.set_ticklabels([]);
    
    ax.grid(grid);
开发者ID:manderle01,项目名称:pyclustering,代码行数:44,代码来源:__init__.py

示例5: Plugin

# 需要导入模块: from matplotlib.font_manager import FontProperties [as 别名]
# 或者: from matplotlib.font_manager.FontProperties import set_name [as 别名]

#.........这里部分代码省略.........
                          'S':'g', 'T':'g', 'V':'b', 'W':'b', 'Y':'b',
                          'U':'m', 'O':'m', 'B':'g', 'Z':'g', 'J':'b',
                          'X':'w', ' ':'w', '.':'k', '-':'k'}

    def MessageDia(self, string):
        dialog = wx.MessageDialog(self.frame, string, 'Error', style=wx.OK)
        dialog.ShowModal()
        dialog.Destroy()
                
    def CreateRecMat(self):
        self.recMat = []
        for seq in self.rec[0].seq:
            self.recMat.append([])
        for record in self.rec:
            for i,r in enumerate(record.seq):
                self.recMat[i].append(r)
                
    def CharSort(self):
        self.sort = []
        for r in self.recMat:
            self.sort.append([])
            temp = dict()
            chars = dict()
            sumV = 0
            for c in r:
                if not c in chars.keys():
                    chars[c] = 0.
                chars[c] += 1.
            for c in chars.keys():
                if not chars[c] in temp.keys():
                    temp[chars[c]] = []
                sumV += chars[c]
                temp[chars[c]].append(c)
            i = len(r)
            while i > 1:
                if i in temp.keys():
                    for x in temp[i]:
                        self.sort[-1].append([x,i])
                i -= 1
            self.sort[-1].append(sumV)

    def DoEnt(self):
        figWidth = self.bPSize[0] - 277
        xPos = 0
        yPos = 0
        seqLen = int(self.options[3][2].GetValue())
        seqLen -= int(self.options[2][2].GetValue())
        numLines = self.options[0][2].GetValue()
        cpr = seqLen / self.options[0][2].GetValue()
        if seqLen % self.options[0][2].GetValue() > 0:
            cpr += 1
        for i,s in enumerate(self.sort[:-1]):
            sV = s[-1]
            if i%cpr == 0:
                yPos = 1 - (int(i / cpr + 1) * 1. / numLines)
                xPos = 0
            yp = yPos
            for c in s[:-1]:
                fs = 720.*c[1]/sV*figWidth/473./seqLen*(numLines**.99)
                self.axes1.text(xPos, yp, c[0], fontsize = fs,
                                color = self.colorDict[c[0]], ha = 'left', 
                                fontproperties = self.font, va = 'bottom')
                yp += fs / 200.
            xPos += 2.*s[0][1]/sV*figWidth/473./seqLen*.7*(numLines**.8)

    def ShowImage(self, event):
        self.axes1.clear()
        self.plotter.remove()
        self.plotter.Show(False)
        self.axes1 = self.plotter.add('figure 1').gca()
        self.font = FontProperties()
        self.font.set_name('Georgia')
        self.recMat = []
        self.CreateRecMat()
        self.CharSort()
        if self.options[1][2].GetValue() == 'entropy':
            self.DoEnt()
        else:
            self.DoProb()
        self.axes1.set_ylim(0,1)
        #self.axes1.set_xlim(0,len(self.rec[0].seq))
        self.axes1.axis('off')
        self.plotter.resize([3.05 / 244, 3.05 / 244])
        self.plotter.Show(True)
        
    def GetExec(self, fr, bp, rec, cL):
        self.frame = fr
        self.bigPanel = bp
        self.bPSize = bp.GetSize()
        self.colorList = cL
        self.rec = rec
        self.CoverInit()
        self.OptionsInit()
        self.Colors()
        self.createButton = wx.Button(self.frame, -1, "CREATE",
                                      pos = (5,self.frame.GetSize()[1] - 35),
                                      size = (self.frame.GetSize()[0] - 10,25))
        self.frame.Bind(wx.EVT_BUTTON, self.ShowImage, self.createButton)
        self.frameBox.SetScrollbars(0, 1, 0, len(self.options)*30+13)
        self.frameBox.SetScrollRate(15, 35)
开发者ID:fxb22,项目名称:BioGUI,代码行数:104,代码来源:RecLogo.py

示例6: plot_trial_steps

# 需要导入模块: from matplotlib.font_manager import FontProperties [as 别名]
# 或者: from matplotlib.font_manager.FontProperties import set_name [as 别名]
    def plot_trial_steps(self):
        '''Plot target (sig-eps-curve of the tensile test) and trial curves
        and corresponding phi function together with trail steps from the iteration process.
        NOTE: the global variable 'rec_trial_steps' must be set to 'True' in order to store the iteration values
              within the global variables 'phi_trial_list_n' and 'sig_trial_list_n'
        n - index of the time steps to be considered
        i - index of the iteration steps performed in order to fit the target curve
        '''
        #-------------------------------------------------------------------
        # configure the style of the font to be used for labels and ticks
        #-------------------------------------------------------------------
        #
        from matplotlib.font_manager import FontProperties
        font = FontProperties()
#        font.serif         : Times, Palatino, New Century Schoolbook, Bookman, Computer Modern Roman
#        font.sans-serif    : Helvetica, Avant Garde, Computer Modern Sans serif
#        font.cursive       : Zapf Chancery
#        font.monospace     : Courier, Computer Modern Typewriter
        font.set_name('Script MT')
        # name = ['Times New Roman', 'Helvetica', 'Script MT'] #?
        font.set_family('serif')
        # family = ['serif', 'sans-serif', 'cursive', 'fantasy', 'monospace']
        font.set_style('normal')
        # style  = ['normal', 'italic', 'oblique']
        font.set_size('small')
        # size  = ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', '11']
        font.set_variant('normal')
        # variant= ['normal', 'small-caps']
        font.set_weight('medium')
        # weight = ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black']

        #-------------------------------------------------------------------

        p.figure(facecolor='white', dpi=600,
                 figsize=(8, 6))  # white background

        # time list corresponding to the specified numbers of steps and step size
        #
        step_list = [n * self.step_size for n in range(self.n_steps + 1)]

        # get list of lists containing the trial values of 'sig_app' and 'phi_trail'
        # the lists are defined as global variables of 'MATSCalibDamageFn' and are filled
        # within the iteration process when the method 'get_lack_of_fit" is called
        #
        phi_trial_list_n = [[1.]] + self.phi_trial_list_n
        sig_trial_list_n = [[0.]] + self.sig_trial_list_n

        xrange = 10.  # plotting range for strain [mm/m]
        yrange = 15.  # plotting range for stress [MPa]

        for n in range(self.n_steps):
            for i in range(len(phi_trial_list_n[n + 1])):
                x = np.array([step_list[n], step_list[n + 1]])
                eps = 1000. * x  # plot strains in permil on the x-axis
                #--------------------------------------
                # sig-eps trial
                #--------------------------------------
                # plot the numerically calculated sig-eps-curve (tensile test)
                # (with trial steps)
                #
                sig_trail = np.array(
                    [sig_trial_list_n[n][-1], sig_trial_list_n[n + 1][i]])
                p.subplot(222)
                p.plot(eps, sig_trail, color='k', linewidth=1)
                p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font)
                p.ylabel('stress $\sigma$ [MPa]', fontproperties=font)
                if self.format_ticks:
                    # format ticks for plot
                    p.axis([0, xrange, 0., yrange], fontproperties=font)
                    locs, labels = p.xticks()
                    p.xticks(locs, map(lambda x: "%.0f" %
                                       x, locs), fontproperties=font)
                    locs, labels = p.yticks()
                    p.yticks(locs, map(lambda x: "%.0f" %
                                       x, locs), fontproperties=font)

                #--------------------------------------
                # phi_trail
                #--------------------------------------
                # plot the fitted phi-function
                # (with trial steps)
                #
                p.subplot(224)
                phi_trail = np.array(
                    [phi_trial_list_n[n][-1], phi_trial_list_n[n + 1][i]])
                p.plot(eps, phi_trail, color='k', linewidth=1)
                p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font)
                p.ylabel('integrity $\phi$ [-]', fontproperties=font)
                if self.format_ticks:
                    # format ticks for plot
                    p.yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0])
                    p.axis([0, xrange, 0., 1.])
                    locs, labels = p.xticks()
                    p.xticks(locs, map(lambda x: "%.0f" %
                                       x, locs), fontproperties=font)
                    locs, labels = p.yticks()
                    p.yticks(locs, map(lambda x: "%.1f" %
                                       x, locs), fontproperties=font)

        #--------------------------------------
#.........这里部分代码省略.........
开发者ID:simvisage,项目名称:simvisage,代码行数:103,代码来源:mats_calib_damage_fn.py

示例7: FontProperties

# 需要导入模块: from matplotlib.font_manager import FontProperties [as 别名]
# 或者: from matplotlib.font_manager.FontProperties import set_name [as 别名]
#! /usr/bin/python

from matplotlib.font_manager import FontProperties
from PSRpy.const import T_sun, d2r
from PSRpy.parfile import DerivePar
from pkcorr import doppler
import matplotlib.pyplot as plt
import numpy as np

font = FontProperties()
font.set_name('serif')

def om1dot_m1m2(omd,omderr,a1,e,pb,om,m1,npts):
    """Calculate upper/lower bounds of OMDOT curve in the m1-m2 plane."""
    m2omh = ((omd+omderr)*d2r*(1.-e**2)*(pb/2./np.pi)**(5./3.)/3./\
              T_sun**(2./3.)/86400./365.25)**(3./2.) - m1
    m2oml = ((omd-omderr)*d2r*(1.-e**2)*(pb/2./np.pi)**(5./3.)/3./\
              T_sun**(2./3.)/86400./365.25)**(3./2.) - m1
    return m2omh, m2oml


def pbdot_m1m2(pbdot,pbdoterr,pb,e,m1,npts):
    """Calculate the upper/lower bounds of PBDOT curve in the m1-m2 plane."""
    m2pbdh = np.zeros(npts)
    m2pbdl = np.zeros(npts)
    fe = 1.+73./24.*e**2+37./96.*e**4
    A  = -192.*np.pi/5.*(pb/2./np.pi)**(-5./3.)*fe*(1.-e**2)**(-7./2.)*\
         T_sun**(5./3.)
    for i in range(npts):
        m2 = 1.
        # use Newton-Raphson method to get upper-bound curve.
开发者ID:emmanuelfonseca,项目名称:PSRpy,代码行数:33,代码来源:m1m2.py

示例8: open

# 需要导入模块: from matplotlib.font_manager import FontProperties [as 别名]
# 或者: from matplotlib.font_manager.FontProperties import set_name [as 别名]
sampled_z = np.array(nu_traces[:,:,numiter-1] > 0.95,dtype=float)
ey = (np.dot(x,np.dot(sampled_z,phi_mean_traces[:,:,numiter-1])));
np.savetxt(output_dir+"est_y.csv", ey, delimiter=",")

rank = np.sum(((np.sum(sampled_z > threshold,axis=0)>0) * (np.sum(phi_mean_traces[:,:,numiter-1]> threshold,axis=1)>0)));
f = open(output_dir+"rank.csv",'w')
f.write(str(rank)) 
f.close()
f = open(output_dir+"metrics.csv", 'w');
f.write(str(rss)+","+str(cv)+","+str(rank));
f.close();

# Plot and Save the Convergence and Results
if (makeplots==1):
	fontP = FontProperties();
	fontP.set_name('Arial')
	
	plt.clf();
	plt.imshow(nu_traces[:,:,numiter-1].T,interpolation='none')
	plt.colorbar()
	plt.ylabel('Factor')
	plt.xlabel('SNP')
	plt.title('Estimated Z')
	plt.savefig(output_dir+'EstimatedZ.png')
	
	plt.clf();
	plt.imshow(phi_mean_traces[:,:,numiter-1].T,interpolation='none')
	plt.colorbar()
	plt.ylabel('Gene')
	plt.xlabel('Factor')
	plt.title('Estimated A')
开发者ID:ashlee1031,项目名称:BERRRI,代码行数:33,代码来源:BERRRI.py

示例9: FontProperties

# 需要导入模块: from matplotlib.font_manager import FontProperties [as 别名]
# 或者: from matplotlib.font_manager.FontProperties import set_name [as 别名]
from matplotlib import patches
from matplotlib.font_manager import FontProperties


font24 = FontProperties()
font24.set_family('sans-serif')
font24.set_name('Helvetica')
font24.set_size(24)
font18 = font24.copy()
font18.set_size(18)
font36 = font24.copy()
font36.set_size(36)

outage0 = []
out_withd0 = []

with open("out_age.csv",'r') as filename1:
	for l in filename1:
		outage0.append(l.strip('\n').split(','))

with open("out_withd.csv",'r') as filename2:
	for l in filename2:
		out_withd0.append(l.strip('\n').split(','))


outage1 = array([(int(x),float(y),int(z)) for x,y,z in outage0[1:]])
out_withd1 = array([(int(x),float(y),int(z)) for x,y,z in out_withd0[2:]])


N = len(outage1)
xx = outage1[:,0]
开发者ID:Chuphay,项目名称:school,代码行数:33,代码来源:vfy.py

示例10: SimDB

# 需要导入模块: from matplotlib.font_manager import FontProperties [as 别名]
# 或者: from matplotlib.font_manager.FontProperties import set_name [as 别名]
from matresdev.db.matdb.trc.ccs_unit_cell import \
    CCSUnitCell, DamageFunctionEntry

from matresdev.db.simdb import \
    SimDB

from matresdev.db.simdb.simdb_class import \
    SimDBClass, SimDBClassExt

simdb = SimDB()

from pickle import dump, load

from matplotlib.font_manager import FontProperties
font = FontProperties()
font.set_name('Script MT')
font.set_family('serif')
font.set_style('normal')
font.set_size('large')
font.set_variant('normal')
font.set_weight('medium')

def format_plot(axes, xlim=None, ylim=None, xlabel='', ylabel=''):
    '''format 2d-plot black and with with times legends 
    '''
    #-------------------------------------------------------------------
    # configure the style of the font to be used for labels and ticks
    #-------------------------------------------------------------------
    #
    from matplotlib.font_manager import FontProperties
    font = FontProperties()
开发者ID:sarosh-quraishi,项目名称:simvisage,代码行数:33,代码来源:show_results.py

示例11: FontProperties

# 需要导入模块: from matplotlib.font_manager import FontProperties [as 别名]
# 或者: from matplotlib.font_manager.FontProperties import set_name [as 别名]
ax.set_xlabel('time [s]', position=(0., 1e6),
                      horizontalalignment='left')
ax.set_ylabel('Damped oscillation [V]')

plt.show()

##############################################################################
# All the labelling in this tutorial can be changed by manipulating the
# `matplotlib.font_manager.FontProperties` method, or by named kwargs to
# `~matplotlib.axes.Axes.set_xlabel`

from matplotlib.font_manager import FontProperties

font = FontProperties()
font.set_family('serif')
font.set_name('Times New Roman')
font.set_style('italic')

fig, ax = plt.subplots(figsize=(5, 3))
fig.subplots_adjust(bottom=0.15, left=0.2)
ax.plot(x1, y1)
ax.set_xlabel('time [s]', fontsize='large', fontweight='bold')
ax.set_ylabel('Damped oscillation [V]', fontproperties=font)

plt.show()

##############################################################################
# Finally, we can use native TeX rendering in all text objects and have
# multiple lines:

fig, ax = plt.subplots(figsize=(5, 3))
开发者ID:dopplershift,项目名称:matplotlib,代码行数:33,代码来源:text_intro.py

示例12: plot

# 需要导入模块: from matplotlib.font_manager import FontProperties [as 别名]
# 或者: from matplotlib.font_manager.FontProperties import set_name [as 别名]
    def plot(self, x='mjd', y='res', reserr=True, info=False, grid=False, 
        resHist=False, savefig=False, figfilename='fig', figfiletype='png', bins=50, 
        fontsize=15, alpha=1, yscalefac=1.5, years=False, plotbothres=True, useclassic=True, ylim=[]):
        """
        Plot data of choice. 
        """

        from matplotlib.font_manager import FontProperties
        import matplotlib.pyplot as plt
        font = FontProperties()
        font.set_name('serif')

        # define axis-label dictionary.
        axlabel = {
            'mjd': 'MJD',
            'year': 'Year',
            'res': r'TOA Residual ($\mu$s)',
            'res_P': r'Pulse-number Residual',
            'orb_phase': 'Orbital Phase',
            'uncertainty': "Post-fit Residual Uncertainty ($\mu$s)"
        }

        # if desired, read in info.tmp file.
        info_flags = []
        if (info):
            try:
                info_flags = np.loadtxt(info, dtype=str)
            except:
                sys.exit("Cannot read info-flag file.")

        # if desired, use classic look for matplotlib.
        if useclassic:
            plt.style.use('classic')

        fig, ax = plt.subplots()

        # generate the desired plot.
        if (resHist):
            ax.hist(getattr(self, 'res'), bins, alpha=alpha)
        else:

            x_data = getattr(self, x)
            y_data = getattr(self, y)
            # if desired x-axis is time in years, convert.
            if (x == 'mjd' and years):
                x = 'year'
                x_data = (x_data - 53005.) / 365.25 + 2004.
            if (y == 'res' and reserr):
                yerr_data = self.uncertainty
                if (info):
                    color_count = 0

                    for label in np.unique(info_flags):
                        x_data_int = x_data[(np.where(info_flags == label))[0]]
                        y_data_int = y_data[(np.where(info_flags == label))[0]]
                        yerr_data_int = yerr_data[(np.where(info_flags == label))[0]]
                        color = colors_residuals[color_count]
                        ax.errorbar(x_data_int, y_data_int, yerr=yerr_data_int, color=color, fmt='+')
                        color_count += 1
                        
                else:
                    ax.errorbar(x_data, y_data, yerr=yerr_data, fmt='+')
            else:
                plt.plot(x_data, y_data, 'b+')

        ax.set_xlabel(axlabel[x], fontproperties=font, fontsize=fontsize)
        ax.set_ylabel(axlabel[y], fontproperties=font, fontsize=fontsize)

        # add grids, if desired.
        if (grid): 
            ax.grid()

        # now, set y-axis limits. 
        ax.set_ylim(np.min(y_data) * yscalefac, np.max(y_data) * yscalefac)

        if (len(ylim) == 2):
            ax.ylim(ylim)

        if plotbothres:
            ax2 = ax.twinx()
            ax2.set_ylabel(axlabel['res_P'], fontproperties=font, fontsize=fontsize)
            ax2.set_ylim(np.min(self.res_P) * yscalefac, np.max(self.res_P) * yscalefac)
            plt.tight_layout()

        # save figure in png format, if desired.
        if savefig:
            plt.savefig(figfilename + '.' + figfiletype, fmt=figfiletype)

        plt.show()
开发者ID:emmanuelfonseca,项目名称:PSRpy,代码行数:91,代码来源:residuals.py

示例13: FontProperties

# 需要导入模块: from matplotlib.font_manager import FontProperties [as 别名]
# 或者: from matplotlib.font_manager.FontProperties import set_name [as 别名]
from matplotlib import patches
from matplotlib.font_manager import FontProperties
from matplotlib import pyplot as plt
import numpy as np
from pandas import read_csv

font24 = FontProperties()
font24.set_family('sans-serif')
font24.set_name('Liberation Sans') #'Helvetica'
font24.set_size(24)
font18 = font24.copy()
font18.set_size(18)
font36 = font24.copy()
font36.set_size(36)


data = read_csv("out_age.csv")
zz = data['n']
N = len(zz)

def make_plot(x_name, x_label, y_name, y_label, title):
    fig,ax = plt.subplots(figsize=(14.3,7))
    max_y = np.ceil(max(data[y_name])+1)
    plt.xlim(28,105); plt.ylim(-1, max_y) #(0,33)
    #plt.subplots_adjust(.09,.12,.995,.91)

    dx = 105 - 28
    dy = max_y + 6 #6 instead of 1, hack, not sure why it works
    maxd = max(dx, dy)

    for i in range(N):
开发者ID:Chuphay,项目名称:school,代码行数:33,代码来源:vfy2.py

示例14: main

# 需要导入模块: from matplotlib.font_manager import FontProperties [as 别名]
# 或者: from matplotlib.font_manager.FontProperties import set_name [as 别名]
def main(argv):
    parser = argparse.ArgumentParser(description='Analyse the distribution of MMPBSA/MMGBSA delta G')
    parser.add_argument('infile', help='input file containing energy totals (CSV format)')
    parser.add_argument('sumfile', help='summary file (text format)')
    parser.add_argument('trendfile', help='trend plot with confidence intervals (.png, .bmp, .pdf)')
    parser.add_argument('distfile', help='distribution plot of energy totals (.png, .bmp, .pdf)')
    parser.add_argument('-c', '--column', help='name of column to use (default TOTAL)')
    args = parser.parse_args()
    column = 'TOTAL' if not args.column else args.column
    
    global mean_results
    
    font = FontProperties()
    font.set_name('Calibri')
    font.set_size(28)

    means = []
    with open(args.infile) as infile:
        reader = csv.DictReader(infile)
        for row in reader:
            if len(row[column]) > 0:
                means.append(float(row[column]))

    means = np.array(means)

    results_m = []
    results_u = []
    results_l = []
    xs = []

    with open(args.sumfile, 'w') as fo:
        for i in range(5, len(means)+5, 5):
            if i >= 10000:
                print('Stopping after 10000 values due to limitations in the bootstrap function.')
                break
            mean_results = []
            bounds = conf_intervals(means[:i])
            fo.write("%d mean %0.2f +%0.2f -%0.2f\n" % (i, bounds[0], bounds[1], bounds[2]))
            results_m.append(bounds[0])
            results_u.append(bounds[1]+bounds[0])
            results_l.append(bounds[2]+bounds[0])
            xs.append(i)

        plt.plot(xs, results_m, color='g')
        plt.plot(xs, results_u, linestyle='--', color='g')
        plt.plot(xs, results_l, linestyle='--', color='g')
        plt.locator_params(nbins=5, axis='y')
        plt.xlabel(u'Samples', fontproperties=font)
        plt.ylabel(u'\u0394G (kcal/mol)', fontproperties=font)  
        plt.tight_layout()
        plt.savefig(args.trendfile)

    lim_l = round(bounds[0] - 2.5, 0)
    
    plt.xlim(lim_l, lim_l+5)
    plt.ylim(0, 900)
    plt.locator_params(nbins=5, axis='y')
    plt.xlabel(u'Bootstrapped mean \u0394G (kcal/mol)', fontproperties=font)
    plt.ylabel(u'Frequency', fontproperties=font)
    plt.hist(mean_results, bins=50)
    plt.savefig(args.distfile)
开发者ID:williamdlees,项目名称:AmberUtils,代码行数:63,代码来源:CalcBounds.py


注:本文中的matplotlib.font_manager.FontProperties.set_name方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。