Esempio n. 1
0
 def __init__(self, baseConfig) :
     self.basecolors = ['red', 'green', 'yellow', 'blue', 'black', 'cyan', 'magenta']
     self.basemarkers = ['D', 'o', 'v', '+', 's', 'p', 'x']
     
     self.figsize = baseConfig.get('figsize', None)
     self.axis = baseConfig.get('axis', None)
     self.title = baseConfig.get('title', 'NoName')
     self.xlabel = baseConfig.get('xlabel', 'NoName')
     self.ylabel = baseConfig.get('ylabel', 'NoName')
     self.grid = baseConfig.get('grid', False)
     self.xaxis_locator = baseConfig.get('xaxis_locator', None)
     self.yaxis_locator = baseConfig.get('yaxis_locator', None)
     self.legend_loc = baseConfig.get('legend_loc', 0)
     
     if self.figsize != None :
         pylab.figure(figsize=self.figsize)
     if self.axis != None :
         pylab.axis(self.axis)
     
     pylab.title(self.title)
     pylab.xlabel(self.xlabel)
     pylab.ylabel(self.ylabel)
     ax = pylab.gca()
     pylab.grid(self.grid)
     if self.xaxis_locator != None :
         ax.xaxis.set_major_locator(pylab.MultipleLocator(self.xaxis_locator))
     if self.yaxis_locator != None :
         ax.yaxis.set_major_locator(pylab.MultipleLocator(self.yaxis_locator))
         
     self.lineList = []
     self.id = 1
Esempio n. 2
0
    def __init__(self,
                 xLim=[0, 10],
                 yLim=[0, 10],
                 figsize=(6, 8),
                 title='hello title',
                 left=None,
                 xlabel='hello xlabel',
                 ylabel='hello ylabel',
                 xticks=None,
                 yticks=None,
                 isGrid=True,
                 xaxis_locator=1,
                 yaxis_locator=1,
                 legend_loc='best'):
        super(barhPlot, self).__init__()

        self.barhList = []
        self.barhId = 0
        self.plotBarhList = []
        self.legendLoc = legend_loc

        # 重新另起一幅图
        pylab.figure(figsize=figsize)
        # 画幅--figure的基本配置,left 是y轴整体的位置,表示Barh底的开始位置x=?
        self.left = left
        pylab.xlim(xLim)
        pylab.ylim(yLim)
        pylab.title(title, fontsize=50)
        pylab.xlabel(xlabel, fontsize=30)
        pylab.ylabel(ylabel, fontsize=30)
        pylab.grid(isGrid)
        ax = pylab.gca()
        ax.xaxis.set_major_locator(pylab.MultipleLocator(xaxis_locator))
        ax.yaxis.set_major_locator(pylab.MultipleLocator(yaxis_locator))
        self.yticks = yticks
Esempio n. 3
0
    def __init__(self, baseConfig) :
        self.figsize = baseConfig.get('figsize',None)
        self.axis = baseConfig.get('axis',None)
        self.title = unicode(baseConfig.get('title','NoName'), 'utf-8')
        self.ylabel = unicode(baseConfig.get('ylabel','NoName'), 'utf-8')
        self.grid = baseConfig.get('grid',False)
        self.xaxis_locator = baseConfig.get('xaxis_locator',None)
        self.yaxis_locator = baseConfig.get('yaxis_locator',None)
        self.legend_loc = baseConfig.get('legend_loc',0)

        if 'xticks' in baseConfig :
            xticks_conf = baseConfig.get('xticks')
            print xticks_conf
            _rotation = int(xticks_conf.get('ticks_rotation', 0))
            x_idx = xticks_conf.get('x_idx',[])
            x_lable = xticks_conf.get('x_lable', [])
            if len(x_idx) > 0 and len(x_idx) == len(x_lable) :
                pylab.xticks(x_idx, x_lable, rotation=_rotation)
        
        if self.figsize != None :
            pylab.figure(figsize = self.figsize)
        if self.axis != None :
            pylab.axis(self.axis)
        
        pylab.title(self.title)
        pylab.ylabel(self.ylabel)
        ax = pylab.gca()
        pylab.grid(self.grid)
        if self.xaxis_locator != None :
            ax.xaxis.set_major_locator( pylab.MultipleLocator(self.xaxis_locator) )
        if self.yaxis_locator != None :
            ax.yaxis.set_major_locator( pylab.MultipleLocator(self.yaxis_locator) )
        self.lineList = []
        self.id = 1
Esempio n. 4
0
    def __init__(self, baseConfig) :
        self.figsize = baseConfig.get('figsize',None)
        self.axis = baseConfig.get('axis',None)
        self.title = baseConfig.get('title','NoName')
        self.ylabel = baseConfig.get('ylabel','NoName')
        self.grid = baseConfig.get('grid',False)
        self.xaxis_locator = baseConfig.get('xaxis_locator',None)
        self.yaxis_locator = baseConfig.get('yaxis_locator',None)
        self.legend_loc = baseConfig.get('legend_loc',0)

        if self.figsize != None :
            pylab.figure(figsize = self.figsize)
        if self.axis != None :
            pylab.axis(self.axis)

        pylab.title(self.title)
        pylab.ylabel(self.ylabel)
        ax = pylab.gca()
        pylab.grid(self.grid)
        if self.xaxis_locator != None :
            ax.xaxis.set_major_locator( pylab.MultipleLocator(self.xaxis_locator) )
        if self.yaxis_locator != None :
            ax.yaxis.set_major_locator( pylab.MultipleLocator(self.yaxis_locator) )
        self.lineList = []
        self.id = 1
 def setArcFormat(self):
     self.subplot.xaxis.set_major_formatter(PL.FuncFormatter(self.arcsec_format))
     self.subplot.xaxis.set_major_locator(PL.MultipleLocator(self.parent.M/10))
     self.subplot.yaxis.set_major_formatter(PL.FuncFormatter(self.arcsec_format))
     self.subplot.yaxis.set_major_locator(PL.MultipleLocator(self.parent.M/10))
     self.subplot.set_xlim(200., 400.)
     self.subplot.set_ylim(200., 400.)
Esempio n. 6
0
 def show(self, title=None, figsize=None, **params):
     if params.get('show') == False:  # keep call chaining
         return self
     logger.info('===============showing image============')
     self.info()
     info = self.getInfo()
     assert info['width'] and info['height'], 'img shape error!'
     params = dict(self.imshow_params, **params)
     logger.info(params)
     logger.info(f'{title or self.title}:')
     if self.isColor():
         if params['cmap'] == 'hsv':
             logger.warn('HSV format should covert back to RGB!')
         img = self.org()
         if self.CHANNELS_ORDER == ('b', 'g', 'r'):
             img = img[..., ::-1]  # swap B and R channels for plt show
     else:
         if params['cmap'] == 'viridis':
             logger.warn(
                 "Single channel image, set cmap to default 'Grey_r'")
             params['cmap'] = 'Greys_r'
             img = self.gray().org()
         else:
             img = self.org()
     fig = pylab.figure(figsize=figsize or FIGSIZE)
     x_major_locator = int(img.shape[1] / 10)
     x_minor_locator = x_major_locator / 4
     ax = plt.gca()
     ax.xaxis.set_major_locator(pylab.MultipleLocator(x_major_locator))
     ax.xaxis.set_minor_locator(pylab.MultipleLocator(x_minor_locator))
     ax.yaxis.set_minor_locator(pylab.MultipleLocator(x_minor_locator))
     pylab.imshow(img, **params)
     pylab.show()
     return self
Esempio n. 7
0
def setticks(ax,
             xlog=False,
             ylog=False,
             xmajor=5,
             xminor=1,
             ymajor=2,
             yminor=0.5):

    if not xlog:
        xmajorLocator = pylab.MultipleLocator(xmajor)
        xmajorFormatter = pylab.FormatStrFormatter('%d')
        xminorLocator = pylab.MultipleLocator(xminor)
        ax.xaxis.set_major_locator(xmajorLocator)
        #ax.xaxis.set_major_formatter(xmajorFormatter)
        ax.xaxis.set_minor_locator(xminorLocator)

    if not ylog:
        ymajorLocator = pylab.MultipleLocator(ymajor)
        ymajorFormatter = pylab.FormatStrFormatter('%d')
        yminorLocator = pylab.MultipleLocator(yminor)
        ax.yaxis.set_major_locator(ymajorLocator)
        #ax.yaxis.set_major_formatter(ymajorFormatter)
        ax.yaxis.set_minor_locator(yminorLocator)

    ax.get_yaxis().set_tick_params(which='both', direction='out')
    ax.get_xaxis().set_tick_params(which='both', direction='out')
    for tick in ax.xaxis.get_ticklines():
        tick.set_markersize(3.25)
    for tick in ax.yaxis.get_ticklines():
        tick.set_markersize(3.25)
    for tick in ax.xaxis.get_ticklines(minor=True):
        tick.set_markersize(2.75)
    for tick in ax.yaxis.get_ticklines(minor=True):
        tick.set_markersize(2.75)
Esempio n. 8
0
    def __init__(self,
                 xLim=[0, 10],
                 yLim=[0, 10],
                 figsize=(6, 8),
                 title='hello title',
                 xlabel='hello xlabel',
                 ylabel='hello ylabel',
                 isGrid=True,
                 xaxis_locator=1,
                 yaxis_locator=1,
                 legend_loc='best'):
        super(curvePlot, self).__init__()
        self.curveList = []
        self.curveId = 0
        self.legendLoc = legend_loc

        # 重新另起一幅图
        pylab.figure(figsize=figsize)
        # 画幅--figure的基本配置
        pylab.xlim(xLim)
        pylab.ylim(yLim)
        pylab.title(title, fontsize=50)
        pylab.xlabel(xlabel, fontsize=30)
        pylab.ylabel(ylabel, fontsize=30)
        pylab.grid(isGrid)
        ax = pylab.gca()
        ax.xaxis.set_major_locator(pylab.MultipleLocator(xaxis_locator))
        ax.yaxis.set_major_locator(pylab.MultipleLocator(yaxis_locator))
        # 曲线的可选选项
        self.curveColorsList = ['r', 'g', 'y', 'b', 'k', 'c', 'm']
        self.lineStyleList = ['-', '--', '-.', ':', '.', ' ', '']
        self.makerStyleList = ['s', 'p', '*', 'h', 'H', '+', 'x', 'D', 'd']
 def setUvFormat(self):
     self.subplot.xaxis.set_major_formatter(PL.FuncFormatter(self.uv_format))
     self.subplot.xaxis.set_major_locator(PL.MultipleLocator(self.parent.M/6))
     self.subplot.yaxis.set_major_formatter(PL.FuncFormatter(self.uv_format))
     self.subplot.yaxis.set_major_locator(PL.MultipleLocator(self.parent.M/6))
     self.subplot.set_xlim(100., 500.)
     self.subplot.set_ylim(100., 500.)
Esempio n. 10
0
def demo_grid():
    ax = plt.axes([0.025, 0.025, 0.95, 0.95])

    ax.set_xlim(0, 4)
    ax.set_ylim(0, 3)
    ax.xaxis.set_major_locator(plt.MultipleLocator(1.0))
    ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1))
    ax.yaxis.set_major_locator(plt.MultipleLocator(1.0))
    ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    ax.grid(which='major',
            axis='x',
            linewidth=0.75,
            linestyle='-',
            color='0.75')
    ax.grid(which='minor',
            axis='x',
            linewidth=0.25,
            linestyle='-',
            color='0.75')
    ax.grid(which='major',
            axis='y',
            linewidth=0.75,
            linestyle='-',
            color='0.75')
    ax.grid(which='minor',
            axis='y',
            linewidth=0.25,
            linestyle='-',
            color='0.75')
    ax.set_xticklabels([])
    ax.set_yticklabels([])

    # savefig('../figures/grid_ex.png',dpi=48)
    plt.show()
Esempio n. 11
0
    def __init__(self,
                 xLim=[0, 10],
                 yLim=[0, 10],
                 figsize=(6, 8),
                 title='hello title',
                 xlabel='hello xlabel',
                 ylabel='hello ylabel',
                 isGrid=True,
                 xaxis_locator=1,
                 yaxis_locator=1,
                 legend_loc='best'):
        super(scatterPlot, self).__init__()
        self.scatterList = []
        self.scatterId = 0
        self.plotScatterList = []
        self.legendLoc = legend_loc

        # 重新另起一幅图
        pylab.figure(figsize=figsize)
        # 画幅--figure的基本配置
        pylab.xlim(xLim)
        pylab.ylim(yLim)
        pylab.title(title, fontsize=50)
        pylab.xlabel(xlabel, fontsize=30)
        pylab.ylabel(ylabel, fontsize=30)
        pylab.grid(isGrid)
        ax = pylab.gca()
        ax.xaxis.set_major_locator(pylab.MultipleLocator(xaxis_locator))
        ax.yaxis.set_major_locator(pylab.MultipleLocator(yaxis_locator))
Esempio n. 12
0
    def _initFig(self):
        w, h = self.media_info['width'], self.media_info['height']
        tip_h = 300

        fig = pylab.figure()
        fig.set_figwidth(9)  # 12.8
        fig.set_figheight(9 * (h + tip_h) / w)

        left_margin, bottom_margin, width = 0.05, 0.02, 0.9
        ax_main = pylab.axes([
            left_margin, bottom_margin + 0.9 * tip_h / (tip_h + h), width,
            0.9 * h / (tip_h + h)
        ])
        ax_main.xaxis.set_ticks_position('top')
        ax_main.set_xlim((0, w))
        ax_main.set_ylim((h, 0))
        ax_main.xaxis.set_major_locator(pylab.MultipleLocator(100))
        ax_main.xaxis.set_minor_locator(pylab.MultipleLocator(20))
        ax_main.yaxis.set_minor_locator(pylab.MultipleLocator(20))

        ax_tip = pylab.axes(
            [left_margin, bottom_margin, width, 0.9 * tip_h / (tip_h + h)])
        ax_tip.set_xlim((0, w))
        ax_tip.set_ylim((tip_h, 0))
        ax_tip.set_xticks([])
        ax_tip.set_yticks([])
        ax_tip.set_facecolor('#ebe6eb')

        pylab.close()
        self.fig = fig
        self.ax_main = ax_main
        self.ax_tip = ax_tip
Esempio n. 13
0
def plotTrans(root):
    """
    Plot the fractional change in plate scale and PA over many different
    starlists that  have been aligned. You can either give align results
    for many different epochs or align results for many different cleaned
    frames in a single epoch.

    root - align output
    """
    tab = asciidata.open(root + '.trans')

    a0 = tab[3].tonumarray()
    a0e = tab[4].tonumarray()
    a1 = tab[5].tonumarray()
    a1e = tab[6].tonumarray()
    a2 = tab[7].tonumarray()
    a2e = tab[8].tonumarray()
    b0 = tab[9].tonumarray()
    b0e = tab[10].tonumarray()
    b1 = tab[11].tonumarray()
    b1e = tab[12].tonumarray()
    b2 = tab[13].tonumarray()
    b2e = tab[14].tonumarray()

    trans = []
    for ff in range(len(a0)):
        tt = objects.Transform()
        tt.a = [a0[ff], a1[ff], a2[ff]]
        tt.b = [b0[ff], b1[ff], b2[ff]]
        tt.aerr = [a0e[ff], a1e[ff], a2e[ff]]
        tt.berr = [b0e[ff], b1e[ff], b2e[ff]]
        tt.linearToSpherical(override=False)

        trans.append(tt)

    # Read epochs
    dateTab = asciidata.open(root + '.date')
    numEpochs = dateTab.ncols
    years = [dateTab[i][0] for i in range(numEpochs)]

    p.clf()
    p.subplot(211)
    p.plot(scale - 1.0, 'ko')
    p.ylabel('Fract. Plate Scale Difference')
    if (years[0] != years[1]):
        thePlot = p.gca()
        thePlot.get_xaxis().set_major_locator(p.MultipleLocator(0.1))
        thePlot.get_xaxis().set_major_formatter(p.FormatStrFormatter('%8.3f'))

    p.subplot(212)
    p.plot(angle, 'ko')
    p.ylabel('Position Angle')
    if (years[0] != years[1]):
        thePlot = p.gca()
        thePlot.get_xaxis().set_major_locator(p.MultipleLocator(0.1))
        thePlot.get_xaxis().set_major_formatter(p.FormatStrFormatter('%8.3f'))
Esempio n. 14
0
def set_xtick(major, minor, axes=None):
    """Satt *major* och *minor* tick-marks pa x-axeln
    """
    if axes is None:
        axes = pylab.gca()
    if not isinstance(axes, (list, tuple)):
        axes = [axes]
    for ax in axes:
        ax.xaxis.set_major_locator(pylab.MultipleLocator(major))
        ax.xaxis.set_minor_locator(pylab.MultipleLocator(minor))
Esempio n. 15
0
    def BaryonicTullyFisher(self, G):

        print 'Plotting the baryonic TF relationship'

        seed(2222)

        plt.figure()  # New figure
        ax = plt.subplot(111)  # 1 plot on the figure

        # w = np.where((G.Type == 0) & (G.StellarMass + G.ColdGas > 0.0) & (G.Vmax > 0.0))[0]
        w = np.where((G.Type == 0) & (G.StellarMass + G.ColdGas > 0.0) & (
            (G.ClassicalBulgeMass + G.SecularBulgeMass) / G.StellarMass > 0.1)
                     & ((G.ClassicalBulgeMass + G.SecularBulgeMass) /
                        G.StellarMass < 0.5))[0]
        if (len(w) > dilute): w = sample(w, dilute)

        mass = np.log10(
            (G.StellarMass[w] + G.ColdGas[w]) * 1.0e10 / self.Hubble_h)
        vel = np.log10(G.Vmax[w])

        plt.scatter(vel,
                    mass,
                    marker='o',
                    s=1,
                    c='k',
                    alpha=0.5,
                    label='Model Sb/c galaxies')

        # overplot Stark, McGaugh & Swatters 2009 (assumes h=0.75? ... what IMF?)
        w = np.arange(0.5, 10.0, 0.5)
        TF = 3.94 * w + 1.79
        plt.plot(w, TF, 'b-', lw=2.0, label='Stark, McGaugh \& Swatters 2009')

        plt.ylabel(
            r'$\log_{10}\ M_{\mathrm{bar}}\ (M_{\odot})$')  # Set the y...
        plt.xlabel(r'$\log_{10}V_{max}\ (km/s)$')  # and the x-axis labels

        # Set the x and y axis minor ticks
        ax.xaxis.set_minor_locator(plt.MultipleLocator(0.05))
        ax.yaxis.set_minor_locator(plt.MultipleLocator(0.25))

        plt.axis([1.4, 2.6, 8.0, 12.0])

        leg = plt.legend(loc='lower right')
        leg.draw_frame(False)  # Don't want a box frame
        for t in leg.get_texts():  # Reduce the size of the text
            t.set_fontsize('medium')

        outputFile = OutputDir + '4.BaryonicTullyFisher' + OutputFormat
        plt.savefig(outputFile)  # Save the figure
        print 'Saved file to', outputFile
        plt.close()

        # Add this plot to our output list
        OutputList.append(outputFile)
Esempio n. 16
0
    def BlackHoleBulgeRelationship(self, G):

        print 'Plotting the black hole-bulge relationship'

        seed(2222)

        plt.figure()  # New figure
        ax = plt.subplot(111)  # 1 plot on the figure

        w = np.where(((G.ClassicalBulgeMass + G.SecularBulgeMass) > 0.01)
                     & (G.BlackHoleMass > 0.00001))[0]
        if (len(w) > dilute): w = sample(w, dilute)

        bh = np.log10(G.BlackHoleMass[w] * 1.0e10 / self.Hubble_h)
        bulge = np.log10((G.ClassicalBulgeMass[w] + G.SecularBulgeMass[w]) *
                         1.0e10 / self.Hubble_h)

        plt.scatter(bulge,
                    bh,
                    marker='o',
                    s=1,
                    c='k',
                    alpha=0.5,
                    label='Model galaxies')

        # overplot Haring & Rix 2004
        w = 10.**np.arange(20)
        BHdata = 10.**(8.2 + 1.12 * np.log10(w / 1.0e11))
        plt.plot(np.log10(w),
                 np.log10(BHdata),
                 'b-',
                 label="Haring \& Rix 2004")

        plt.ylabel(r'$\log\ M_{\mathrm{BH}}\ (M_{\odot})$')  # Set the y...
        plt.xlabel(r'$\log\ M_{\mathrm{bulge}}\ (M_{\odot})$'
                   )  # and the x-axis labels

        # Set the x and y axis minor ticks
        ax.xaxis.set_minor_locator(plt.MultipleLocator(0.05))
        ax.yaxis.set_minor_locator(plt.MultipleLocator(0.25))

        plt.axis([8.0, 12.0, 6.0, 10.0])

        leg = plt.legend(loc='upper left')
        leg.draw_frame(False)  # Don't want a box frame
        for t in leg.get_texts():  # Reduce the size of the text
            t.set_fontsize('medium')

        outputFile = OutputDir + '8.BlackHoleBulgeRelationship' + OutputFormat
        plt.savefig(outputFile)  # Save the figure
        print 'Saved file to', outputFile
        plt.close()

        # Add this plot to our output list
        OutputList.append(outputFile)
Esempio n. 17
0
def xAxis():
    ax = pylab.subplot(111)
    majLoc = pylab.MultipleLocator(0.02)
    majFmat = pylab.FormatStrFormatter(
        '%f')  # or some other format - this puts the numbers on
    ax.xaxis.set_major_locator(majLoc)
    #    ax.xaxis.set_major_formatter(majFmat)

    minLoc = pylab.MultipleLocator(0.01)
    ax.xaxis.set_minor_locator(
        minLoc)  #for the minor ticks, use no labels; default NullFormatter
Esempio n. 18
0
def yAxis():
    ay = pylab.subplot(111)
    majLoc = pylab.MultipleLocator(50)
    majFmat = pylab.FormatStrFormatter(
        '%d')  # or some other format - this puts the numbers on
    ay.yaxis.set_major_locator(majLoc)
    ay.yaxis.set_major_formatter(majFmat)

    minLoc = pylab.MultipleLocator(10)
    ay.yaxis.set_minor_locator(
        minLoc)  #for the minor ticks, use no labels; default NullFormatter
Esempio n. 19
0
    def SpecificStarFormationRate(self, G):

        print 'Plotting the specific SFR'

        seed(2222)

        plt.figure()  # New figure
        ax = plt.subplot(111)  # 1 plot on the figure

        w = np.where(G.StellarMass > 0.01)[0]
        if (len(w) > dilute): w = sample(w, dilute)

        mass = np.log10(G.StellarMass[w] * 1.0e10 / self.Hubble_h)
        sSFR = np.log10((G.SfrDisk[w] + G.SfrBulge[w]) /
                        (G.StellarMass[w] * 1.0e10 / self.Hubble_h))
        plt.scatter(mass,
                    sSFR,
                    marker='o',
                    s=1,
                    c='k',
                    alpha=0.5,
                    label='Model galaxies')

        # overplot dividing line between SF and passive
        w = np.arange(7.0, 13.0, 1.0)
        plt.plot(w, w / w * sSFRcut, 'b:', lw=2.0)

        plt.ylabel(
            r'$\log_{10}\ s\mathrm{SFR}\ (\mathrm{yr^{-1}})$')  # Set the y...
        plt.xlabel(r'$\log_{10} M_{\mathrm{stars}}\ (M_{\odot})$'
                   )  # and the x-axis labels

        # Set the x and y axis minor ticks
        ax.xaxis.set_minor_locator(plt.MultipleLocator(0.05))
        ax.yaxis.set_minor_locator(plt.MultipleLocator(0.25))

        plt.axis([8.0, 12.0, -16.0, -8.0])

        leg = plt.legend(loc='lower right')
        leg.draw_frame(False)  # Don't want a box frame
        for t in leg.get_texts():  # Reduce the size of the text
            t.set_fontsize('medium')

        outputFile = OutputDir + '5.SpecificStarFormationRate' + OutputFormat
        plt.savefig(outputFile)  # Save the figure
        print 'Saved file to', outputFile
        plt.close()

        # Add this plot to our output list
        OutputList.append(outputFile)
Esempio n. 20
0
    def GasFraction(self, G):

        print 'Plotting the gas fractions'

        seed(2222)

        plt.figure()  # New figure
        ax = plt.subplot(111)  # 1 plot on the figure

        w = np.where((G.Type == 0) & (G.StellarMass + G.ColdGas > 0.0) & (
            (G.ClassicalBulgeMass + G.SecularBulgeMass) / G.StellarMass > 0.1)
                     & ((G.ClassicalBulgeMass + G.SecularBulgeMass) /
                        G.StellarMass < 0.5))[0]
        if (len(w) > dilute): w = sample(w, dilute)

        mass = np.log10(G.StellarMass[w] * 1.0e10 / self.Hubble_h)
        fraction = G.ColdGas[w] / (G.StellarMass[w] + G.ColdGas[w])

        plt.scatter(mass,
                    fraction,
                    marker='o',
                    s=1,
                    c='k',
                    alpha=0.5,
                    label='Model Sb/c galaxies')

        plt.ylabel(
            r'$\mathrm{Cold\ Mass\ /\ (Cold+Stellar\ Mass)}$')  # Set the y...
        plt.xlabel(r'$\log_{10} M_{\mathrm{stars}}\ (M_{\odot})$'
                   )  # and the x-axis labels

        # Set the x and y axis minor ticks
        ax.xaxis.set_minor_locator(plt.MultipleLocator(0.05))
        ax.yaxis.set_minor_locator(plt.MultipleLocator(0.25))

        plt.axis([8.0, 12.0, 0.0, 1.0])

        leg = plt.legend(loc='upper right')
        leg.draw_frame(False)  # Don't want a box frame
        for t in leg.get_texts():  # Reduce the size of the text
            t.set_fontsize('medium')

        outputFile = OutputDir + '6.GasFraction' + OutputFormat
        plt.savefig(outputFile)  # Save the figure
        print 'Saved file to', outputFile
        plt.close()

        # Add this plot to our output list
        OutputList.append(outputFile)
Esempio n. 21
0
def rstyle(ax, pres=False):
    """
    Styles x,y axes to appear like ggplot2
    Must be called after all plot and axis manipulation operations have been
    carried out (needs to know final tick spacing)
    """
    #Set the style of the major and minor grid lines, filled blocks
    if pres:
        ax.grid(True, 'major', color='w', linestyle='-', linewidth=0.7)
        ax.grid(True, 'minor', color='0.99', linestyle='-', linewidth=0.4)
    else:
        ax.grid(True, 'major', color='w', linestyle='-', linewidth=1.4)
        ax.grid(True, 'minor', color='0.99', linestyle='-', linewidth=0.7)
    ax.patch.set_facecolor('0.90')
    ax.set_axisbelow(True)

    #Set minor tick spacing to 1/2 of the major ticks
    ax.xaxis.set_minor_locator((pylab.MultipleLocator(
        (plt.xticks()[0][1] - plt.xticks()[0][0]) / 2.0)))
    ax.yaxis.set_minor_locator((pylab.MultipleLocator(
        (plt.yticks()[0][1] - plt.yticks()[0][0]) / 2.0)))

    #Remove axis border
    for child in ax.get_children():
        if isinstance(child, matplotlib.spines.Spine):
            child.set_alpha(0)

    #Restyle the tick lines
    for line in ax.get_xticklines() + ax.get_yticklines():
        if pres:
            line.set_markersize(4)
            line.set_color("gray")
            line.set_markeredgewidth(.8)
        else:
            line.set_markersize(5)
            line.set_color("gray")
            line.set_markeredgewidth(1.4)

    #Remove the minor tick lines
    for line in (ax.xaxis.get_ticklines(minor=True) +
                 ax.yaxis.get_ticklines(minor=True)):
        line.set_markersize(0)

    #Only show bottom left ticks, pointing out of axis
    plt.rcParams['xtick.direction'] = 'out'
    plt.rcParams['ytick.direction'] = 'out'
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')
Esempio n. 22
0
def barGraph(data, **kw):
    """Draws a bar graph for the given data"""
    from pylab import bar
    kw.setdefault('barw', 0.5)
    kw.setdefault('log', 0)
    kw.setdefault('color', 'blue')
    xs = [i + 1 for i, row in enumerate(data)]
    names, ys = zip(*data)
    names = [n.replace('_', '\n') for n in names]
    #print 'got xs %s, ys %s, names %s' % (xs, ys, names)
    bar(xs,
        ys,
        width=kw['barw'],
        color=kw['color'],
        align='center',
        log=kw['log'])
    ax = pylab.gca()

    def f(x, pos=None):
        n = int(x) - 1
        if n + 1 != x: return ''
        if n < 0: return ''
        try:
            return names[n]
        except IndexError:
            return ''

    ax.xaxis.set_major_formatter(pylab.FuncFormatter(f))
    ax.xaxis.set_major_locator(pylab.MultipleLocator(1))
    ax.set_xlim(0.5, len(names) + 0.5)
    for l in ax.get_xticklabels():
        pylab.setp(l, rotation=90)
    start = 0.08, 0.18
    pos = (start[0], start[1], 0.99 - start[0], 0.95 - start[1])
    ax.set_position(pos)
def plotAllRaw(dic):
    """This function plots the raw variables (current and voltage) in dic.
    It will plot fields that have more than 1 y variable but less than 20,"""
    count = 1
    for key in dic.keys():
        #        print key
        #        figure(count)
        arr = dic[key]
        if (type(arr) == type(np.eye(1))):
            numX = arr.shape[1]
            #          print numX
            ml = p.MultipleLocator(100000)

            if (numX < 20 and numX > 1):
                if (key == 'TaggingInfo'):
                    break
                fig = p.figure()
                fig.suptitle(key)
                nrows = math.ceil(numX / 3)
                ncols = numX if nrows == 1 else 3
                #               print nrows, ncols
                for i in range(numX):
                    sp = p.subplot(nrows, ncols, i + 1)
                    pl = p.plot(abs(arr[:, i]))[0]
                    if (sp.is_last_row()):
                        p.xlabel("Time in milliseconds")
                    if (sp.is_first_col()):
                        p.ylabel(key)
                    pl.axes.xaxis.set_major_locator(ml)

                count = count + 1
Esempio n. 24
0
def rstyle(ax):
    '''Styles x,y axes to appear like ggplot2
    Must be called after all plot and axis manipulation operations have been
    carried out (needs to know final tick spacing)

    From:
    http://nbviewer.ipython.org/github/wrobstory/climatic/blob/master/examples/ggplot_styling_for_matplotlib.ipynb
    '''
    import pylab
    import matplotlib
    import matplotlib.pyplot as plt

    #Set the style of the major and minor grid lines, filled blocks
    ax.grid(True, 'major', color='w', linestyle='-', linewidth=1.4)
    ax.grid(True, 'minor', color='0.99', linestyle='-', linewidth=0.7)
    ax.patch.set_facecolor('0.90')
    ax.set_axisbelow(True)

    #Set minor tick spacing to 1/2 of the major ticks
    ax.xaxis.set_minor_locator((pylab.MultipleLocator(
        (plt.xticks()[0][1] - plt.xticks()[0][0]) / 2.0)))
    ax.yaxis.set_minor_locator((pylab.MultipleLocator(
        (plt.yticks()[0][1] - plt.yticks()[0][0]) / 2.0)))

    #Remove axis border
    for child in ax.get_children():
        if isinstance(child, matplotlib.spines.Spine):
            child.set_alpha(0)

    #Restyle the tick lines
    for line in ax.get_xticklines() + ax.get_yticklines():
        line.set_markersize(5)
        line.set_color("gray")
        line.set_markeredgewidth(1.4)

    #Remove the minor tick lines
    for line in (ax.xaxis.get_ticklines(minor=True) +
                 ax.yaxis.get_ticklines(minor=True)):
        line.set_markersize(0)

    #Only show bottom left ticks, pointing out of axis
    plt.rcParams['xtick.direction'] = 'out'
    plt.rcParams['ytick.direction'] = 'out'
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')
Esempio n. 25
0
def plot_setticks(x=True, y=True):

    pl.minorticks_on()
    ax = pl.gca()
    if x:
        ax.xaxis.set_major_locator(pl.AutoLocator())
        x_major = ax.xaxis.get_majorticklocs()
        dx_minor = (x_major[-1] - x_major[0]) / (len(x_major) - 1) / 5.
        ax.xaxis.set_minor_locator(pl.MultipleLocator(dx_minor))
    else:
        pl.minorticks_off()

    if y:
        ax.yaxis.set_major_locator(pl.AutoLocator())
        y_major = ax.yaxis.get_majorticklocs()
        dy_minor = (y_major[-1] - y_major[0]) / (len(y_major) - 1) / 5.
        ax.yaxis.set_minor_locator(pl.MultipleLocator(dy_minor))
    else:
        pl.minorticks_off()
Esempio n. 26
0
def ggplot(ax):
    """Styles an axes to appear like ggplot2
    Must be called after all plot and axis manipulation operations have been carried out (needs to know final tick spacing)
    """
    #set the style of the major and minor grid lines, filled blocks
    ax.grid(True, 'major', color='w', linestyle='-', linewidth=1.4)
    ax.grid(True, 'minor', color='0.92', linestyle='-', linewidth=0.7)
    ax.patch.set_facecolor('0.85')
    ax.set_axisbelow(True)

    #set minor tick spacing to 1/2 of the major ticks
    ax.xaxis.set_minor_locator(
        pl.MultipleLocator((pl.xticks()[0][1] - pl.xticks()[0][0]) / 2.0))
    ax.yaxis.set_minor_locator(
        pl.MultipleLocator((pl.yticks()[0][1] - pl.yticks()[0][0]) / 2.0))

    #remove axis border
    for child in ax.get_children():
        if isinstance(child, spines.Spine):
            child.set_alpha(0)

    #restyle the tick lines
    for line in ax.get_xticklines() + ax.get_yticklines():
        line.set_markersize(5)
        line.set_color("gray")
        line.set_markeredgewidth(1.4)

    #remove the minor tick lines
    for line in ax.xaxis.get_ticklines(minor=True) + ax.yaxis.get_ticklines(
            minor=True):
        line.set_markersize(0)

    #only show bottom left ticks, pointing out of axis
    rcParams['xtick.direction'] = 'out'
    rcParams['ytick.direction'] = 'out'
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')

    if ax.legend_ <> None:
        lg = ax.legend_
        lg.get_frame().set_linewidth(0)
        lg.get_frame().set_alpha(0.5)
Esempio n. 27
0
File: sigmoid.py Progetto: jzhou/ai
def sigmoidplot():
    x = plt.linspace(-10, 10, 5)
    y = plt.linspace(-10, 10, 10)
    z = plt.linspace(-10, 10, 100)

    plt.plot(x, sigmoid(x), 'r', label='linspace(-10,10,5)')
    plt.plot(y, sigmoid(y), 'b', label='linspace(-10,10,10)')
    plt.plot(z, sigmoid(z), 'y', label='linspace(-10,10,100)')

    plt.title('Sigmoid Function')
    plt.suptitle('Math')
    plt.grid()
    plt.legend(loc='lower right')
    plt.text(-9, 0.8, r'$\sigma(x)=\frac{1}{1+e^{-x}}$', fontsize=15)
    plt.gca().xaxis.set_major_locator(plt.MultipleLocator(2))
    plt.gca().yaxis.set_major_locator(plt.MultipleLocator(0.1))
    plt.xlabel('X Axis')
    plt.ylabel('Y Axis')

    plt.show()
Esempio n. 28
0
def visualplot(size, step_size):
    """Takes size of required field and step size as input and initializes a plot"""
    fig = pylab.figure()
    ax = fig.add_subplot(1, 1, 1)
    pylab.ylim(size / -2, size / 2)
    pylab.xlim(size / -2, size / 2)
    loc = pylab.MultipleLocator(
        base=step_size)  # this locator puts ticks at regular intervals
    ax.xaxis.set_major_locator(loc)
    ax.yaxis.set_major_locator(loc)
    pylab.grid()
Esempio n. 29
0
def imshow_cube_image(image, header=None, compass=True, blackhole=True, 
                      cmap=None):
    """
    Call imshow() to plot a cube image. Make sure it is already 
    masked. Also pass in the header to do the compass rose calculations.
    """
    # Setup axis info (x is the 2nd axis)
    xcube = (np.arange(image.shape[1]) - m31pos[0]) * 0.05
    ycube = (np.arange(image.shape[0]) - m31pos[1]) * 0.05
    xtickLoc = py.MultipleLocator(0.4)

    if cmap is None:
        cmap = py.cm.jet

    # Plot the image.
    py.imshow(image, 
              extent=[xcube[0], xcube[-1], ycube[0], ycube[-1]],
              cmap=cmap)
    py.gca().get_xaxis().set_major_locator(xtickLoc)
    
    py.xlabel('X (arcsec)')
    py.ylabel('Y (arcsec)')

    # Get the spectrograph position angle for compass rose
    if compass is True:
        if header is None:
            pa = paSpec
        else:
            pa = header['PA_SPEC']


        # Make a compass rose
        cosSin = np.array([ math.cos(math.radians(pa)), 
                            math.sin(math.radians(pa)) ])
        arr_base = np.array([ xcube[-1]-0.5, ycube[-1]-0.6 ])
        arr_n = cosSin * 0.2
        arr_w = cosSin[::-1] * 0.2
        py.arrow(arr_base[0], arr_base[1], arr_n[0], arr_n[1],
                 edgecolor='w', facecolor='w', width=0.03, head_width=0.08)
        py.arrow(arr_base[0], arr_base[1], -arr_w[0], arr_w[1],
                 edgecolor='w', facecolor='w', width=0.03, head_width=0.08)
        py.text(arr_base[0]+arr_n[0]+0.1, arr_base[1]+arr_n[1]+0.1, 'N', 
                color='white', 
                horizontalalignment='left', verticalalignment='bottom')
        py.text(arr_base[0]-arr_w[0]-0.15, arr_base[1]+arr_w[1]+0.1, 'E', 
                color='white',
                horizontalalignment='right', verticalalignment='center')

    if blackhole is True:
        py.plot([0], [0], 'ko')


    py.xlim([-0.5, 0.6])
    py.ylim([-2.0, 1.8])
Esempio n. 30
0
 def smart_locate(ax, n_max, bases=[1, 2, 5]):
     x0, x1 = ax.get_view_interval()
     if x1 == x0:
         return
     delta = (x1 - x0) / (n_max - 1)
     # Find smallest base and p such delta < base*10^p
     log_spacing = min([
         np.ceil(np.log10(delta) - np.log10(b)) + np.log10(b)
         for b in bases
     ])
     loc = pl.MultipleLocator(10**log_spacing)
     ax.set_major_locator(loc)