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


Python GridSpec.update方法代码示例

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


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

示例1: nbo_vs_year

# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import update [as 别名]
  def nbo_vs_year(self):
    """
    Plot percent of structures, with different NBO per 1000 atoms levels,
    from "good" pdb structures (all PDB files with a single model, no unknown
    atom types and good CRYST1 records) VS. year

    Second sub plot: the total of "good" structures deposited VS. year
    """
    plt.close('all')
    # figure parameters
    # plt.ion() # enables interactive mode
    max_y = 105
    fontsize = 20
    fig = plt.figure(figsize=(8,10))
    gs = GridSpec(2,1,height_ratios=[2,1])
    # first subplot
    ax1 = plt.subplot(gs[0,0])
    ax2 = plt.subplot(gs[1,0])
    lines = []
    line_type = ['.:','.-','.--']
    n = len(line_type)
    for i,pd in enumerate(self.plot_data_list):
      lt = line_type[i%n]
      l, = ax1.plot(pd.years,pd.percent,lt)
      lines.append(l)
    ax1.set_ylabel('Percent of PDB structures',fontsize=fontsize)
    ax1.text(min(self.years)+0.5,max_y-4,'a.',fontsize=fontsize)
    ax1.tick_params(axis='both',labelsize=fontsize - 2)
    ax1.axes.get_xaxis().set_visible(False)
    ax1.set_yticks([5,10,40,70,100])
    ax1.set_ylim([0,max_y])
    ax1.set_xlim([self.start_year,self.end_year])
    # legend
    labels = ['NBO per 1000 atom > {}']*len(self.nbo_per_1000_atoms)
    labels = [x.format(y) for x,y in zip(labels,self.nbo_per_1000_atoms)]
    if self.sym:
      legend_pos = [0.96,0.70]
    else:
      legend_pos = [0.54,0.30]
    ax1.legend(
      lines,labels,
      bbox_to_anchor=legend_pos,
      loc=1,borderaxespad=0.0)
    # Second subplot
    ax2.plot(self.years,self.n_total,'.:g')
    ax2.set_xlim([self.start_year,self.end_year])
    ax2.set_xlabel('Year',fontsize=fontsize)
    ax2.set_ylabel('Number of structures',fontsize=fontsize)
    ax2.text(min(self.years)+0.5,max(self.n_total)-5,'b.',fontsize=fontsize)
    ax2.tick_params(axis='both',labelsize=fontsize - 2)
    ax2.set_xticks([self.start_year,1990,2000,self.end_year])
    ax2.set_yscale('log')
    ax2.set_yticks([10,100,1000])
    #
    gs.tight_layout(fig)
    gs.update(hspace=0)
    s = 'all'*(not self.sym) + 'sym'*self.sym
    fig_name = 'nbo_vs_year_{}.png'.format(s)
    plt.savefig(fig_name)
    fig.show()
开发者ID:youdar,项目名称:work,代码行数:62,代码来源:collecting_overlap_data.py

示例2: initialize_figure

# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import update [as 别名]
def initialize_figure(start_hour, stop_hour):
    f = plt.figure(figsize=(17, 21))

    font_1 = font_0.copy()
    font_1.set_size('20')
    font_1.set_weight('bold')
    plt.suptitle(u"Schemat wyznaczania HRA dla pojedynczego 24-godzinnego nagrania odstępów RR.",
                fontproperties=font_1, y=0.995, fontsize=25)

    empty_ratio = 0.2
    height_ratios = [
                     0.5, #1 24-tachogram
                     0.3, #2 plot 24h -> 2h pass
                     0.9, #3 2-hour tachogram
                     empty_ratio, #4 empty
                     0.45, #5 5-min window arrow plot
                     #empty_ratio, #6
                     0.9, #7 2-hour windowed tachogram
                     empty_ratio, #8 empty plot
                     0.55, #9 calculate descriptors arrow plot
                     empty_ratio, #10 empty plot
                     0.9,  #11 2-hour windowed tachogram with asymmetry signs
                     2.0   #12 schema for binomial test
                     ]

    num_rows = len(height_ratios)
    num_cols = 1

    row_number = 0

    gs1 = GridSpec(num_rows, num_cols, height_ratios=height_ratios) #[3, 0.3, 3, 0.5, 4])
    gs1.update(left=0.04, right=0.99, wspace=0.1, hspace=0.0, bottom=0.04, top=0.98)
    return f, gs1
开发者ID:TEAM-HRA,项目名称:hra_suite,代码行数:35,代码来源:schema_for_single_recording.py

示例3: main

# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import update [as 别名]
def main():
    matplotlib.rc('font', size=12)
    fig = plt.figure(figsize=(16,9))
    gs = GridSpec(2, 1, height_ratios=[20, 1])#, 20])
    gs.update(hspace=0., wspace=0.)

    ax1 = plt.subplot(gs[0])
    label_ax = plt.subplot(gs[1])

    [ax.set_xlim(0, 599) for ax in (ax1, label_ax)]
    ax1.set_ylim(0, 350)

    # New way
    regiondict = dict(zip(range(1,600), ['MA']*(133-1) + ['CA']*(364-133) + ['p2']*(378-364) + ['NC']*(433-378) + ['p1']*(449-433) + ['p6']*(501-449) + ['PR']*(600-501)))

    N_lines = 50
    muts = get_muts('gag-gag') + get_muts('gag-pr')
    muts = [mut for mut in muts if regiondict[mut[1]] != regiondict[mut[0]]]
    muts.sort(key=lambda x: x[-1], reverse=True)
    min_mi = muts[N_lines-1][2]

    counter = 0
    for mut in muts[:N_lines]:
        r1, r2 = regiondict[mut[0]], regiondict[mut[1]]
        c = 'r' if r2 == 'PR' else 'b'
        ax1.add_patch(make_circ(*mut, ec=c))
        counter += 1

    print counter

    r = range(1)
    proxy1 = plt.Line2D(r, r, color='b', markerfacecolor='none', lw=3)
    proxy2 = plt.Line2D(r, r, color='r', markerfacecolor='none', lw=3)
    ax1.legend((proxy1, proxy2), ('Gag-Gag', 'Gag-PR'))

    # Add x-axis boxes
    locs = [(132, 'MA'), (363, 'CA'), (377, 'p2'), (432, 'NC'), (448, 'p1'), (500, 'p6'),
            (599, 'PR')]
    x_start = 0
    colors = ('#AAAAAA', '#EEEEEE')
    for i, (junc, name) in enumerate(locs):
        color = colors[i%2]
        width = junc - x_start
        rect = patches.Rectangle((x_start, 0), width, 1, color=color)
        label_ax.add_patch(rect)
        label_ax.text(x_start + width/2., 1/2., name, ha='center', va='center')
        x_start = junc
    label_ax.set_xlim(0, 599)
    label_ax.set_xticks([1]+range(50, 650, 50))
    label_ax.set_xticklabels([1]+range(50, 500, 50)+[1]+range(50, 150, 50))

    [plt.setp(ax.get_xticklabels(), visible=False) for ax in (ax1, )]
    [plt.setp(ax.get_yticklabels(), visible=False) for ax in (ax1, label_ax)]
    [ax.tick_params(top=False, left=False, right=False, bottom=False) for ax in (ax1, label_ax)]
    ax1.tick_params(bottom=True)
    ax1.set_xticks(np.arange(0, 599, 10))

    label_ax.set_xlabel('Sequence position')

    plt.show()
开发者ID:wflynny,项目名称:miseq-analysis,代码行数:62,代码来源:circular_correlation_map.py

示例4: plot_fd

# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import update [as 别名]
def plot_fd(fd_file, fd_radius, mean_fd_dist=None, figsize=DINA4_LANDSCAPE):

    fd_power = _calc_fd(fd_file, fd_radius)

    fig = plt.Figure(figsize=figsize)
    FigureCanvas(fig)

    if mean_fd_dist:
        grid = GridSpec(2, 4)
    else:
        grid = GridSpec(1, 2, width_ratios=[3, 1])
        grid.update(hspace=1.0, right=0.95, left=0.1, bottom=0.2)

    ax = fig.add_subplot(grid[0, :-1])
    ax.plot(fd_power)
    ax.set_xlim((0, len(fd_power)))
    ax.set_ylabel("Frame Displacement [mm]")
    ax.set_xlabel("Frame number")
    ylim = ax.get_ylim()

    ax = fig.add_subplot(grid[0, -1])
    sns.distplot(fd_power, vertical=True, ax=ax)
    ax.set_ylim(ylim)

    if mean_fd_dist:
        ax = fig.add_subplot(grid[1, :])
        sns.distplot(mean_fd_dist, ax=ax)
        ax.set_xlabel("Mean Frame Displacement (over all subjects) [mm]")
        mean_fd = fd_power.mean()
        label = r'$\overline{{\text{{FD}}}}$ = {0:g}'.format(mean_fd)
        plot_vline(mean_fd, label, ax=ax)

    return fig
开发者ID:poldracklab,项目名称:mriqc,代码行数:35,代码来源:viz_utils.py

示例5: plot_ext_laws

# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import update [as 别名]
    def plot_ext_laws(self):
        wave = np.arange(900, 20000)
        f0 = np.ones(wave.shape[0])

        for law in ['calz', 'ccm', 'allen', 'prevot', 'seaton', 'fitz']:
            getattr(self, law)(wave, f0, 1.)
        
        self.wild(wave) 

        fig = plt.figure()
        gs = GridSpec(1,1)
        gs.update(left=0.12, right=0.95, top=0.95, bottom=0.12)
        ax = fig.add_subplot(gs[0])
    
        ax.semilogx(wave, self.calz_klam, 'c', lw=1.5, label='Calzetti')
#        ax.semilogx(wave, self.ccm_klam, 'k', label='Cardelli')
        ax.semilogx(wave, self.allen_klam, 'r', lw=1.5, label='Allen')
        ax.semilogx(wave, self.prevot_klam, 'g', lw=1.5, label='Prevot')
        ax.semilogx(wave, self.seaton_klam, 'm', lw=1.5, label='Seaton')
        ax.semilogx(wave, self.fitz_klam, 'b', lw=1.5, label='Fitzpatrick')

        ax.legend(frameon=False)
        for axis in ['top', 'bottom', 'left', 'right']:
            ax.spines[axis].set_linewidth(1.5)

        
        ax.set_ylabel(r'$k(\lambda)$', fontsize=20)
        ax.set_xlabel(r'$\lambda [\AA]$', fontsize=20)
        ax.set_xlim(9e2, 2.5e4)
        ax.set_ylim(0, 20)
        plt.savefig('extlaw.pdf')
开发者ID:micaelabagley,项目名称:synthsrc,代码行数:33,代码来源:attenuation.py

示例6: make_figure

# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import update [as 别名]
 def make_figure(self, type):
     self.fig.clf()
     if type == 'gd':
         pass
     elif type == 'mc':
         gs = GridSpec(1, 1)
         gs.update(hspace=0.7, wspace=0.8)
         self.splts = [self.fig.add_subplot(gs[int(i/3), int(i%3)]) for i in range(1*1)]  # grid nxn
     else:
         pass
开发者ID:thuongnht,项目名称:Python3,代码行数:12,代码来源:Panel_Plotting.py

示例7: plot_standard

# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import update [as 别名]
def plot_standard(corr="acorr"):
    os.chdir(tables_dir)
    ref = np.loadtxt("stars_lick_val_{0}.txt".format(corr)).T
    obs = np.loadtxt("stars_lick_obs_{0}.txt".format(corr)).T
    bands = np.loadtxt("bands_matching_standards.txt", usecols=(0), dtype=str).tolist()
    bands2, units, error = np.loadtxt("bands.txt", usecols=(0,9,10), dtype=str).T
    idx = [list(bands2).index(x) for x in bands]
    idx2 = np.array([list(bands).index(x) for x in bands2])
    error = error[idx]
    units = units[idx]
    units = [x.replace("Ang", "\AA") for x in units]
    fig = plt.figure(1, figsize=(20,12))
    gs = GridSpec(5,5)
    gs.update(left=0.03, right=0.988, top=0.98, bottom=0.06, wspace=0.2,
              hspace=0.4)
    offsets, errs = [], []
    for i in range(25):
        ax = plt.subplot(gs[i])
        plt.locator_params(axis="y", nbins=6)
        plt.locator_params(axis="x", nbins=6)
        ax.minorticks_on()
        # ax.plot(obs[i], ref[i] - obs[i], "ok")
        ax.axhline(y=0, ls="--", c="k")
        diff = ref[i] - obs[i]
        diff, c1, c2 = sigmaclip(diff[np.isfinite(diff)], 2.5, 2.5)
        ax.hist(diff, bins=8, color="0.7", histtype='stepfilled')
        ylim = plt.ylim()
        xlim = plt.xlim()
        xlim = np.max(np.abs(xlim))
        ax.set_ylim(0, ylim[1] + 2)
        ax.set_xlim(-xlim, xlim)
        mean = np.nanmean(diff)
        N = len(diff)
        err = np.nanstd(diff) / np.sqrt(N)
        lab = "${0:.2f}\pm{1:.2f}$".format(mean, err)
        ax.axvline(x=mean, ls="-", c="r", label=lab)
        ax.axvline(x=0, ls="--", c="k")
        # ax.axhline(y=float(error[i]))
        # ax.axhline(y=-float(error[i]))
        # ax.set_xlabel("{0} ({1})".format(bands[i].replace("_", " "), units[i]))
        ax.legend(loc=1,prop={'size':12})
        ax.set_xlabel("$\Delta$ {0} ({1})".format(bands[i].replace("_", " "),
                                                  units[i]))
        ax.set_ylabel("Frequency")
        offsets.append(mean)
        errs.append(err)
    offsets = np.array(offsets)[idx2]
    errs = np.array(errs)[idx2]
    output = os.path.join(home, "plots/lick_stars_{0}.png".format(corr))
    plt.savefig(output)
    with open(os.path.join(tables_dir, "lick_offsets.txt"), "w") as f:
        f.write("# Index Additive Correction\n")
        np.savetxt(f, np.column_stack((np.array(bands)[idx2],offsets, errs)),
                   fmt="%s")
开发者ID:kadubarbosa,项目名称:groups,代码行数:56,代码来源:run_lector.py

示例8: kplot

# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import update [as 别名]
def kplot(curcode,startdatetime,show_log,title="none",ymarks=[]):

    df='%Y-%m-%d %H:%M:%S'
    dt=datetime.strptime(startdatetime,df)

    # fig,ax = plt.subplots(nrows=3,ncols=1, figsize=(12,5),facecolor='#D3D3D3')
    fig = plt.figure(figsize=(12,5),facecolor='#D3D3D3')
    fig.suptitle(title)
    gs1 = GridSpec(8, 8)
    gs1.update(left=0.05, right=0.95, wspace=0.05)
    ax1 = plt.subplot(gs1[0:5, :])
    ax2 = plt.subplot(gs1[6:8, 0:3])
    ax3 = plt.subplot(gs1[6:8, 4:8])

    #day
    ax2.set_title("days")
    days_range=30
    table=curcode+"_1day"
    kdatas=kdb.query(table,(dt-timedelta(days=days_range)).strftime(df),(dt+timedelta(days=days_range)).strftime(df))
    while len(kdatas) < 60:
        days_range +=5
        kdatas=kdb.query(table,(dt-timedelta(days=days_range)).strftime(df),(dt+timedelta(days=days_range)).strftime(df))

    kaxplot(ax2,dt.replace(hour=0,minute=0,second=0),'%m-%d',kdatas,ymarks)
    #hour
    ax1.set_title("hours")
    hours_range=60
    table=curcode+"_1hour"
    kdatas=kdb.query(table,(dt-timedelta(hours=hours_range)).strftime(df),(dt+timedelta(hours=hours_range)).strftime(df))
    while len(kdatas) < 120:
        hours_range +=10
        kdatas=kdb.query(table,(dt-timedelta(hours=hours_range)).strftime(df),(dt+timedelta(hours=hours_range)).strftime(df))

    kaxplot(ax1,dt.replace(minute=0,second=0),'%Y-%m-%d %H',kdatas,ymarks)
    #min
    ax3.set_title("minutes")
    mins_range=50
    table=curcode+"_1min"
    kdatas=kdb.query(table,(dt-timedelta(minutes=mins_range)).strftime(df),(dt+timedelta(minutes=mins_range)).strftime(df))
    while len(kdatas) < 100:
        mins_range +=10
        kdatas=kdb.query(table,(dt-timedelta(minutes=mins_range)).strftime(df),(dt+timedelta(minutes=mins_range)).strftime(df))

    kaxplot(ax3,dt.replace(second=0),'%H:%M',kdatas,ymarks)
    #show or log
    if show_log == "show" :
        plt.show()
    else:
        if not os.path.exists(show_log):
            os.makedirs(show_log)
        plt.savefig(show_log+startdatetime.replace(":","%")+".png")
    plt.close('all')
开发者ID:wulitu1984,项目名称:alpha,代码行数:54,代码来源:kplot.py

示例9: plot_series

# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import update [as 别名]
def plot_series(data, order='co', fig=None, subplot_spec=None):
    '''
    Parameters
    ----------
    data : ndarray
      shape (26=ntask, nbin)
    order : string, optional
      one of 'co' or 'oc', for center-out or out-center data order
      determines mapping of data to polygons
      defaults to center-out
    fig : matplotlib Figure instance
      an existing figure to use, optional
    subplotspec : matplotlib SubplotSpec instance, optional
      an existing subplotspec to use, i.e. subset of a gridspec
    '''
    if not ((np.rank(data) == 2) & (data.shape[0] == 26)):
        raise ValueError('data has wrong shape; should be (26, nbin),'
                         'actually is %s' % (str(data.shape)))
    if order == 'co':
        mapping = get_targ_co_dir_mapping()
    elif order == 'oc':
        mapping = get_targ_oc_dir_mapping()
    else:
        raise ValueError('`order` not recognized')
    
    if (fig != None) & (not isinstance(fig, Figure)):
        raise ValueError('`fig` must be an instance of Figure')
    if (fig == None):
        fig = plt.figure()
    if (subplot_spec != None):
        if not isinstance(subplot_spec, SubplotSpec):
            raise ValueError('subplot_spec must be instance of '
                             'SubplotSpec')
    ntask, nbin = data.shape
    clim = (np.nanmin(data), np.nanmax(data))
    if subplot_spec == None:
        gs = GridSpec(nbin + 1,1, height_ratios=[1,] * nbin + [0.5,])
        gs.update(left=0.02, right=0.98, top=0.98, bottom=0.05)
    else:
        gs = GridSpecFromSubplotSpec(\
            nbin + 1,1, subplot_spec=subplot_spec, \
                height_ratios=[1,] * nbin + [0.5,])
    for i in xrange(nbin):
        ax = fig.add_subplot(gs[i], projection='split_lambert')
        plot_gem(data[:,i], order=order, ax=ax, clim=clim)
    cbax = fig.add_subplot(gs[-1], aspect=.25)
    cb = plt.colorbar(ax.collections[0], cbax, orientation='horizontal')
    clim = cb.get_clim()
    cb.set_ticks(clim)
    cb.set_ticklabels(['%0.1f' % x for x in clim])
    return fig
开发者ID:amcmorl,项目名称:motorlab,代码行数:53,代码来源:gems.py

示例10: plot

# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import update [as 别名]
    def plot(self, *args, **kwargs):
        g_idx = self.myc['g_idx']
        neuron_idx = self.myc['neuron_idx']
        l, b, r, t = self.myc['bbox_rect']

        fig = self._get_final_fig(self.myc['fig_size'])
        gs = GridSpec(2, 2)
        gs.update(left=l, right=r, bottom=b, top=t, hspace=0)

        # E-->I outgoing
        ax = fig.add_subplot(gs[0, 0])
        self.plotOutgoing(g_idx, "E", neuron_idx, ax=ax, xlabel='', ylabel='',
                          use_title=False)
        ax.set_xticks([])

        # I-->E input
        ax = fig.add_subplot(gs[0, 1])
        self.plotIncoming(g_idx, "E", neuron_idx, ax=ax, ylabel='', xlabel='',
                          use_title=False)
        ax.set_xticks([])
        ax.set_yticks([])

        # I-->E outgoing
        ax = fig.add_subplot(gs[1, 0])
        self.plotOutgoing(g_idx, "I", neuron_idx, ax=ax, use_title=False,
                          xlabel='', ylabel='')

        # E-->I input
        ax = fig.add_subplot(gs[1, 1])
        self.plotIncoming(g_idx, "I", neuron_idx, ax=ax, xlabel='', ylabel='',
                          use_title=False)
        ax.set_yticks([])

        fname = self.get_fname("/connections_pcolor_grid.pdf")
        plt.savefig(fname, dpi=300, transparent=True)
        plt.close()

        # Add an extra colorbar
        fig = self._get_final_fig(self.myc['cbar_fig_size'])
        ax_cbar = fig.add_axes([0.05, 0.80, 0.8, 0.15])
        cbar = mpl.colorbar.ColorbarBase(ax_cbar, cmap=mpl.cm.jet,
                                         norm=mpl.colors.Normalize(vmin=0,
                                                                   vmax=1),
                                         ticks=[0, 1],
                                         orientation='horizontal')
        ax_cbar.xaxis.set_ticklabels(['0', '$g_{E/I}$'])
        fname_cbar = self.get_fname("/connections_pcolor_grid_colorbar.pdf")
        plt.savefig(fname_cbar, dpi=300, transparent=True)
        plt.close()
开发者ID:MattNolanLab,项目名称:ei-attractor,代码行数:51,代码来源:connections.py

示例11: __init__

# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import update [as 别名]
	def __init__(self, window):
		"""Initialize spectrogram canvas graphs."""
		# Initialize variables to default values.
		self.window = window
		self.samples = 100 # Number of samples to store
		self.fftSize = 256 # Initial FFT size just to render something in the charts
		self.sampleRate = 0
		self.binFreq = 0
		self.binCount = self.fftSize/2
		self.graphUpdateHz = 10 # Update rate of the animation
		self.coloredBin = None
		self.magnitudes = np.zeros((self.samples, self.binCount))
		# Tell numpy to ignore errors like taking the log of 0
		np.seterr(all='ignore')
		# Set up figure to hold plots
		self.figure = Figure(figsize=(1024,768), dpi=72, facecolor=(1,1,1), edgecolor=(0,0,0))
		# Set up 2x1 grid to hold initial plots
		gs = GridSpec(2, 1, height_ratios=[1,2], width_ratios=[1])
		gs.update(left=0.075, right=0.925, bottom=0.05, top=0.95, wspace=0.05)

		# Set up frequency histogram bar plot
		self.histAx = self.figure.add_subplot(gs[0])
		self.histAx.set_title('Frequency Histogram')
		self.histAx.set_ylabel('Intensity (decibels)')
		self.histAx.set_xlabel('Frequency Bin (hz)')
		self.histAx.set_xticks([])
		self.histPlot = self.histAx.bar(np.arange(self.binCount), np.zeros(self.binCount), width=1.0, linewidth=0.0, facecolor='blue')

		# Set up spectrogram waterfall plot
		self.spectAx = self.figure.add_subplot(gs[1])
		self.spectAx.set_title('Spectrogram')
		self.spectAx.set_ylabel('Sample Age (seconds)')
		self.spectAx.set_xlabel('Frequency Bin (hz)')
		self.spectAx.set_xticks([])
		self.spectPlot = self.spectAx.imshow(self.magnitudes, aspect='auto', cmap=get_cmap('jet'))
		# Add formatter to translate position to age in seconds
		self.spectAx.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: '%d' % (x*(1.0/self.graphUpdateHz))))

		# Set up spectrogram color bar
		#cbAx = self.figure.add_subplot(gs[3])
		#self.figure.colorbar(self.spectPlot, cax=cbAx, use_gridspec=True, format=FuncFormatter(lambda x, pos: '%d' % (x*100.0)))
		#cbAx.set_ylabel('Intensity (decibels)')

		# Initialize canvas
		super(SpectrogramCanvas, self).__init__(self.figure)
		
		# Hook up mouse and animation events
		self.mpl_connect('motion_notify_event', self._mouseMove)
		self.ani = FuncAnimation(self.figure, self._update, interval=1000.0/self.graphUpdateHz, blit=False)
开发者ID:finson,项目名称:fountain,代码行数:51,代码来源:SpectrogramUI.py

示例12: test_lector

# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import update [as 别名]
def test_lector():
    os.chdir(os.path.join(home, "MILES"))
    bands = os.path.join(tables_dir, "bands.txt")
    filename = "lector_tmputH9bu.list_LINE"
    stars = np.loadtxt(filename, usecols=(0,),
                       dtype=str)
    ref = np.loadtxt(filename,
             usecols=(2,3,4,5,6,7,8,9,14,15,16,17,18,24,25,26,
                      27,28,29,30,31,32,33,34,35))
    obs = []
    from lick import Lick
    for i, star in enumerate(stars):
        print star + ".fits"
        spec = pf.getdata(star + ".fits")
        h = pf.getheader(star + ".fits")
        w = h["CRVAL1"] + h["CDELT1"] * \
                            (np.arange(h["NAXIS1"]) + 1 - h["CRPIX1"])
        lick, tmp = lector.lector(w, spec, np.ones_like(w), bands,
                                  interp_kind="linear")
        ll = Lick(w, spec, np.loadtxt(bands, usecols=(2,3,4,5,6,7,)))
        obs.append(ll.classic)
    obs = np.array(obs)
    fig = plt.figure(1, figsize=(20,12))
    gs = GridSpec(5,5)
    gs.update(left=0.08, right=0.98, top=0.98, bottom=0.06, wspace=0.25,
              hspace=0.4)
    obs = obs.T
    ref = ref.T
    names = np.loadtxt(bands, usecols=(0,), dtype=str)
    units = np.loadtxt(bands, usecols=(9,), dtype=str).tolist()
    # units = [x.replace("Ang", "\AA") for x in units]
    for i in range(25):
        ax = plt.subplot(gs[i])
        plt.locator_params(axis="x", nbins=6)
        ax.minorticks_on()
        ax.plot(obs[i], (obs[i] - ref[i]) / ref[i], "o", color="0.5")
        ax.axhline(y=0, ls="--", c="k")
        lab = "median $= {0:.3f}$".format(
            np.nanmedian(obs[i] - ref[i])).replace("-0.00", "0.00")
        ax.axhline(y=np.nanmedian(obs[i] - ref[i]), ls="--", c="r", label=lab)
        ax.set_xlabel("{0} ({1})".format(names[i].replace("_", " "), units[i]))
        ax.legend(loc=1,prop={'size':15})
        ax.set_ylim(-0.01, 0.01)
    fig.text(0.02, 0.5, 'I$_{{\\rm pylector}}$ - I$_{{\\rm lector}}$', va='center',
             rotation='vertical', size=40)
    output = os.path.join(home, "plots/test_lector.png")
    plt.show()
    plt.savefig(output)
开发者ID:kadubarbosa,项目名称:groups,代码行数:50,代码来源:run_lector.py

示例13: make_split

# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import update [as 别名]
def make_split(ratio, gap=0.12):
    import matplotlib.pyplot as plt
    from matplotlib.gridspec import GridSpec
    from matplotlib.ticker import MaxNLocator
    cax = plt.gca()
    box = cax.get_position()
    xmin, ymin = box.xmin, box.ymin
    xmax, ymax = box.xmax, box.ymax
    gs = GridSpec(2, 1, height_ratios=[ratio, 1 - ratio], left=xmin, right=xmax, bottom=ymin, top=ymax)
    gs.update(hspace=gap)

    ax = plt.subplot(gs[0])
    plt.setp(ax.get_xticklabels(), visible=False)
    bx = plt.subplot(gs[1], sharex=ax)

    return ax, bx
开发者ID:fact-project,项目名称:matplotlib-hep,代码行数:18,代码来源:__init__.py

示例14: test_blank_subplots

# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import update [as 别名]
def test_blank_subplots():
    fig = plt.figure()
    gs = GridSpec(4, 6)
    ax1 = fig.add_subplot(gs[0,1])
    ax1.plot(D['x1'], D['y1'])
    fig.add_subplot(gs[1,1])
    fig.add_subplot(gs[2:,1])
    fig.add_subplot(gs[0,2:])
    fig.add_subplot(gs[1:3, 2:4])
    fig.add_subplot(gs[3, 2:5])
    fig.add_subplot(gs[1:3,4:])
    fig.add_subplot(gs[3,5])
    gs.update(hspace=.6, wspace=.6)
    renderer = run_fig(fig)
    equivalent, msg = compare_dict(renderer.layout, BLANK_SUBPLOTS['layout'])
    assert equivalent, msg
开发者ID:chriddyp,项目名称:matplotlylib,代码行数:18,代码来源:test_subplots.py

示例15: plot_confound

# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import update [as 别名]
def plot_confound(tseries,
                  figsize,
                  name,
                  units=None,
                  series_tr=None,
                  normalize=False):
    """
    A helper function to plot :abbr:`fMRI (functional MRI)` confounds.

    """
    import matplotlib
    matplotlib.use(config.get('execution', 'matplotlib_backend'))
    import matplotlib.pyplot as plt
    from matplotlib.gridspec import GridSpec
    from matplotlib.backends.backend_pdf import FigureCanvasPdf as FigureCanvas
    import seaborn as sns

    fig = plt.Figure(figsize=figsize)
    FigureCanvas(fig)
    grid = GridSpec(1, 2, width_ratios=[3, 1], wspace=0.025)
    grid.update(hspace=1.0, right=0.95, left=0.1, bottom=0.2)

    ax = fig.add_subplot(grid[0, :-1])
    if normalize and series_tr is not None:
        tseries /= series_tr

    ax.plot(tseries)
    ax.set_xlim((0, len(tseries)))
    ylabel = name
    if units is not None:
        ylabel += (' speed [{}/s]' if normalize else ' [{}]').format(units)
    ax.set_ylabel(ylabel)

    xlabel = 'Frame #'
    if series_tr is not None:
        xlabel = 'Frame # ({} sec TR)'.format(series_tr)
    ax.set_xlabel(xlabel)
    ylim = ax.get_ylim()

    ax = fig.add_subplot(grid[0, -1])
    sns.distplot(tseries, vertical=True, ax=ax)
    ax.set_xlabel('Frames')
    ax.set_ylim(ylim)
    ax.set_yticklabels([])
    return fig
开发者ID:kesshijordan,项目名称:nipype,代码行数:47,代码来源:confounds.py


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