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')
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
Exemple #3
0
def plot_pie_bouttypes(bca, new_filename):
    print('Plotting pie chart of bout type percentages...')
    hab = bca.iloc[0, :]
    trials = bca.iloc[1::2, :].sum(axis=0)
    breaks = bca.iloc[2::2, :].sum(axis=0)
    dfs = [hab, trials, breaks]
    condition = ['Baseline', 'Trials', 'Intertrial Intervals']

    fig = plt.figure(figsize=(15, 10))
    cmp = JoaoColormap()
    gs = GridSpec(2, 3)  # 2 rows, 3 columns

    for i in np.arange(3):
        ax = plt.subplot2grid((2, 3), (0, i))
        dfs[i].plot(kind='pie',
                    colors=[colour_dict.get(x, 'white') for x in dfs[i].index],
                    ax=ax,
                    autopct=my_autopct,
                    pctdistance=1.1,
                    labels=None)
        # ax.axis('equal')
        # ax.set_title(condition[i], fontsize=18)
        ax.set(ylabel='', title=condition[i], aspect='equal')
    ax4 = plt.subplot2grid((2, 3), (1, 0), colspan=3)
    cat_sym_unique = np.arange(13)  # np.unique(cat_sym_tmp)
    for i in np.arange(13):
        tmp_str = ordered_bouts[i]
        ax4.scatter(i, 0.9, color=cmp(idx[i] - 1), s=200)
        ax4.text(i - 0.12, 0.8, tmp_str)
    ax4.set_ylim([0, 1])
    ax4.axis('off')
    gs.update(wspace=0.2, hspace=0.02)
    plt.tight_layout()
    fig.savefig(new_filename, bbox_inches='tight', format='tiff')
    plt.close('all')
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()
Exemple #5
0
def make_grid(nrows,
              ncols,
              left=0.05,
              right=0.9,
              bottom=0.05,
              top=0.95,
              hspace=0.2,
              wspace=0.2):

    gs = GridSpec(nrows, ncols)
    gs.update(left=left,
              right=right,
              hspace=hspace,
              wspace=wspace,
              bottom=bottom,
              top=top)
    ax = []
    if nrows > 1:
        for i in range(nrows):
            ax_row = []
            for j in range(ncols):
                ax_row.append(plt.subplot(gs[i, j]))
            ax.append(ax_row)
    else:
        for j in range(ncols):
            ax.append(plt.subplot(gs[j]))

    return [ax, gs]
Exemple #6
0
def __draw_images(datagen, x, result_images):
    import os, glob, shutil
    import matplotlib.pyplot as plt
    import cv2
    from matplotlib.gridspec import GridSpec
    # 出力先ディレクトリを作成
    temp_dir = "temp"
    os.mkdir(temp_dir)

    # generatorから9個の画像を生成
    # xは1サンプルのみなのでbatch_sizeは1で固定
    x = __bgr2rgb(x)
    g = datagen.flow(x,
                     batch_size=32,
                     save_to_dir=temp_dir,
                     save_prefix='img',
                     save_format='jpg')
    for i in range(9):
        batch = g.next()
    # 生成した画像を3x3で描画
    images = glob.glob(os.path.join(temp_dir, "*.jpg"))
    fig = plt.figure()
    gs = GridSpec(3, 3)
    gs.update(wspace=0.1, hspace=0.1)
    for i in range(9):
        img = cv2.imread(images[i])
        plt.subplot(gs[i])
        plt.imshow(img, aspect='auto')
        plt.axis("off")
    plt.savefig(result_images)
    # 出力先ディレクトリを削除
    shutil.rmtree(temp_dir)
Exemple #7
0
    def plot(self, outfile, wspace=None, hspace=None, figsize=8):

        grid_cols, grid_rows = self.compute_grid_size()
        fig_w, fig_h = figsize * grid_cols, figsize * grid_rows

        fig = plt.figure(figsize=(fig_w, fig_h))
        gs = GridSpec(grid_rows, grid_cols)

        if wspace is not None:
            gs.update(wspace=wspace)
        elif hspace is not None:
            gs.update(hspace=hspace)

        for j, metric_name in enumerate(sorted(self.to_plot)):
            metric = self.to_plot[metric_name]
            current_cell = gs[j // grid_cols, j % grid_cols]

            if metric['data_type'] == 'lines':
                self.plot_lines(current_cell, metric_name, metric)
            elif metric['data_type'] == 'scatter':
                self.plot_scatter(current_cell, metric_name, metric)
            elif metric['data_type'] == 'image-grid':
                self.plot_image_grid(current_cell, metric_name, metric)
            elif metric['data_type'] == 'image':
                self.plot_image(current_cell, metric_name, metric)
            elif metric['data_type'] == 'hist':
                self.plot_hist(current_cell, metric_name, metric)

        plt.savefig(outfile, dpi=200, bbox_inches='tight')
        plt.close(fig)
Exemple #8
0
def test():
    def make_ticklabels_invisible(fig):
        for i, ax in enumerate(fig.axes):
            ax.text(0.5, 0.5, "ax%d" % (i + 1), va="center", ha="center")
            for tl in ax.get_xticklabels() + ax.get_yticklabels():
                tl.set_visible(False)

    # gridspec with subplotpars set.

    f = plt.figure()

    plt.suptitle("GridSpec w/ different subplotpars")

    gs1 = GridSpec(3, 3)
    gs1.update(left=0.05, right=0.48, wspace=0.05)
    plt.subplot(gs1[:-1, :])
    plt.subplot(gs1[-1, :-1])
    plt.subplot(gs1[-1, -1])

    gs2 = GridSpec(3, 3)
    gs2.update(left=0.55, right=0.98, hspace=0.05)
    plt.subplot(gs2[:, :-1])
    plt.subplot(gs2[:-1, -1])
    plt.subplot(gs2[-1, -1])

    make_ticklabels_invisible(f)
def plot_fd(fd_file, title='FD plot', mean_fd_dist=None, figsize=(11.7, 8.3)):

    fd_power = _calc_fd(fd_file)

    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}}$ = %g' % mean_fd
        plot_vline(mean_fd, label, ax=ax)

    fig.suptitle(title)
    return fig
Exemple #10
0
def make_posemap(img, pose, video_num, img_size, f_num, gauss_size):
    posemap = pose_map(pose, img_size, gauss_size)
    posemap = np.uint8(255 * posemap)
    posemap = cv2.applyColorMap(posemap, cv2.COLORMAP_JET)
    posemap = cv2.cvtColor(posemap, cv2.COLOR_BGR2RGB)
    posemap = posemap / 255
    s_img = posemap * 1.0 + img

    fig = plt.figure(figsize=(16, 10))
    gs = GridSpec(4, 5, left=0.13, right=0.9)
    gs.update(wspace=-0.01)
    gs_1 = GridSpecFromSubplotSpec(nrows=4, ncols=3, subplot_spec=gs[0:4, 0:3])
    fig.add_subplot(gs_1[:, :])
    delete_line()
    plt.imshow(s_img)
    gs_2 = GridSpecFromSubplotSpec(nrows=2, ncols=2, subplot_spec=gs[0:2, 3:5])
    fig.add_subplot(gs_2[:, :])
    delete_line()
    plt.imshow(img)
    gs_3 = GridSpecFromSubplotSpec(nrows=2, ncols=2, subplot_spec=gs[2:4, 3:5])
    fig.add_subplot(gs_3[:, :])
    delete_line()
    plt.imshow(posemap, cmap='jet')
    plt.clim(0, 1)
    plt.colorbar()
    SAVE_PATH = "../../../demo/images/posemap"
    if not os.path.exists(os.path.join(SAVE_PATH, "posemap_" + video_num)):
        os.makedirs(os.path.join(SAVE_PATH, "posemap_" + video_num))

    plt.savefig(
        os.path.join(SAVE_PATH, "posemap_" + video_num,
                     str(f_num).zfill(5) + ".png"))
    plt.close()
def plot_residuals(x,
                   y1,
                   y2,
                   y1err=None,
                   title='Plot',
                   y1label='y1',
                   xlabel='x',
                   y2label='y2'):
    f = plt.figure()
    plt.suptitle(title)
    gs1 = GridSpec(2, 2, width_ratios=[1, 2], height_ratios=[4, 1])
    gs1.update(wspace=0.5)
    ax1 = plt.subplot(gs1[:-1, :])
    ax2 = plt.subplot(gs1[-1, :])
    ax1.grid()
    ax1.errorbar(x, y1, yerr=y1err, ecolor='g')
    ax1.set_xticklabels([])
    ax1.set_ylabel(y1label)
    ax1.set_xlim(x.min(), x.max())
    ax2.grid()
    ax2.plot(x, y2, color='green')
    plt.yticks(
        np.array([
            round(y2.min(), 3),
            round((y2.min() + y2.max()) / 2., 3),
            round(y2.max(), 3)
        ]))
    ax2.set_xlabel(xlabel)
    ax2.set_ylabel(y2label)
    ax2.set_xlim(x.min(), x.max())
    plt.close()
    return f
Exemple #12
0
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
Exemple #13
0
	def wirikan(self): #Graficos principales
		fig = plt.figure(figsize=(20,15))
		gs1 = GridSpec(7, 1)
		gs1.update(left=0.05, right=0.95, wspace=0.5, hspace=0.3, top=0.98, bottom=0.08)

		ax1 = plt.subplot(gs1[0:2,:])
		ax1.grid()
		ax1.set_ylabel('Roll',fontsize=8)
		ax1.xaxis.set_tick_params(labelsize=7)
		ax1.yaxis.set_tick_params(labelsize=7)

		ax2 = plt.subplot(gs1[2:4,:])
		ax2.grid()
		ax2.set_ylabel('Pitch',fontsize=8)
		ax2.xaxis.set_tick_params(labelsize=7)
		ax2.yaxis.set_tick_params(labelsize=7)

		ax3 = plt.subplot(gs1[4:6,:])
		ax3.grid()
		ax3.set_ylabel('Yaw',fontsize=8)
		ax3.xaxis.set_tick_params(labelsize=7)
		ax3.yaxis.set_tick_params(labelsize=7)

		ax4 = plt.subplot(gs1[6,:])
		ax4.grid()
		ax4.set_ylabel('Mark',fontsize=8)
		ax4.xaxis.set_tick_params(labelsize=7)
		ax4.yaxis.set_tick_params(labelsize=7)

		return fig
Exemple #14
0
def fig_ambient(fig_size=(2, 2),
                ncol=2,
                nrow=2,
                left=0.15,
                right=0.95,
                top=0.95,
                hspace=0,
                bottom=0.15,
                wspace=0):

    fig = plt.figure(figsize=fig_size)
    gs2 = GridSpec(nrow, ncol)
    gs2.update(left=left,
               right=right,
               top=top,
               hspace=hspace,
               bottom=bottom,
               wspace=wspace)

    nplots = ncol * nrow
    axes = []
    for k in range(nplots):
        ax = plt.subplot(gs2[k])
        #AXIS(ax)
        axes.append(ax)

    return axes
    def create_fig(self):
        nrow = 1
        ncol = 2
        ngrid = 2
        magical_factor = 15
        wspace = 0
        hspace = 0
        font_size = 15

        self.fig = plt.figure(figsize=(
            nrow * magical_factor,
            (ncol + 1) * ngrid,
        ))
        gs1 = GridSpec(
            nrow,
            (ncol + 1) * ngrid,
        )
        gs1.update(
            wspace=wspace,
            hspace=hspace,
        )

        self.axs = {}
        n = 0
        for i, j in product(range(nrow),
                            [i for i in range(ncol * ngrid)][::ngrid]):
            self.axs[n] = plt.subplot(gs1[i, j:j + ngrid])
            n += 1
Exemple #16
0
    def figure2():

        fig = plt.figure(figsize=(10, 6))
        gs = GridSpec(6, 1)
        gs.update(left=0.1, right=0.95)
        ax1 = plt.subplot(gs[:2])
        ax2 = plt.subplot(gs[2])
        ax3 = plt.subplot(gs[3:5])
        ax4 = plt.subplot(gs[5])
        ax = [ax1, ax2, ax3, ax4]

        start_time = time()

        I_sm1 = b2.TimedArray([0, 2, 0, 5, 0, 10, 0]*b2.pA, dt=100*b2.ms)
        par_sim['I_sm'] = I_sm1
        state_monitor = simulate_Thl_cell_fig2(par, par_sim)

        plot_data(state_monitor, ax[0])
        plot_current(state_monitor, ax[1])

        I_sm2 = b2.TimedArray([0, 0, -0.5, 0, 0, -1, 0, 0]*b2.pA, dt=100*b2.ms)
        par_sim['I_sm'] = I_sm2
        par['i_ext'] = 0.0
        state_monitor = simulate_Thl_cell_fig2(par, par_sim)
        print("Done in {}".format(time() - start_time))

        plot_data(state_monitor, ax[2])
        plot_current(state_monitor, ax[3], xlabel="Time [ms]")

        [ax[i].set_xticks([]) for i in range(3)]
        [ax[i].set_xlim([0, 1000]) for i in range(4)]
        plt.savefig(join("data", "figure2.png"))
        plt.show()
Exemple #17
0
def refocus(img,k_2D,  dz, alpha, delta=0, plotme=False):
    
    k_0 = 2 * np.pi / 780e-9
    fft_img = np.fft.fftshift(np.fft.fft2(img-img.mean()))
    fft_img_refocused = U(k_2D, dz, alpha, delta) * fft_img    
    img_refocused = np.fft.ifft2(fft_img*0+fft_img_refocused)
#    mod = (img_refocused * np.conjugate(img_refocused)).real
    mod = np.abs(img_refocused)  / (2 * k_0)
    
    if plotme:
        
        xc = 321
        yc = 218
        radius = 20  
        mod_crop = mod = mod[yc-2*radius:yc+2*radius, xc-2*radius:xc+2*radius]
    
        plt.figure(0, figsize=(10, 3))
        gs = GridSpec(1, 2)
        gs.update(left=0.1, right=0.95, bottom=0.1, top=0.96,
                  wspace=0.2, hspace=0.1)
    
        plt.subplot(gs[0])
        plt.imshow(np.abs(fft_img_refocused)**2, vmax=7e3)
        plt.colorbar()
    
        plt.subplot(gs[1])
        plt.imshow((mod_crop)+img.mean())
        plt.colorbar()
        plt.show()
    
    return mod
Exemple #18
0
def plot_2(plotdata, filename, title, use_offset=False):
    f = mpl.figure.Figure(figsize=(11, 8.5))
    canvas = FigureCanvasPdf(f)
    f.suptitle(title)
    gs = GridSpec(len(plotdata), 1)
    gs.update(left=0.05, right=0.94, wspace=0.05)
    i = 0
    offset = 0
    for newdata, refdata, invert, series_no in plotdata:
        ax1 = f.add_subplot(gs[i, :])
        ax2 = ax1.twinx()
        data = newdata.match.rate().data
        ax2.plot(data[0], data[1], color='#e0b040', linewidth=2.0,
                 linestyle='-', marker='+', markeredgewidth=2.0)
        ax2max = ax2.get_ylim()[1]
        ax2.set_ylim([0, ax2max * 2])
        ax1.set_ylabel(newdata.series1[series_no].get_name())
        data = newdata.series1[series_no].data
        if use_offset:
            offset = -newdata.series1[series_no].std()*2
            if invert:
                offset = -offset
        ax1.plot(refdata.data[0], refdata.data[1]+offset, linewidth=2.0,
                 color='#9090ff')
        ax1.plot(data[0], data[1], color='black', linewidth=0.75)
        ax1.set_zorder(ax2.get_zorder()+1)  # put ax in front of ax2
        ax1.patch.set_visible(False)  # hide the 'canvas'
        if invert:
            ax1.invert_yaxis()
        i = i + 1
    canvas.print_figure(filename)
Exemple #19
0
def make_plot(seriess, filename, title=None, invert=False):
    f = mpl.figure.Figure(figsize=(11, 8.5))
    canvas = FigureCanvasPdf(f)
    if title:
        f.suptitle(title)

    gs = GridSpec(len(seriess), 1)
    gs.update(left=0.05, right=0.94, wspace=0.05)
    for i in range(0, len(seriess)):
        s = seriess[i]
        if isinstance(s, (list, tuple)):
            ax1 = f.add_subplot(gs[i, :])
            ax2 = ax1.twinx()
            ax2.plot(s[1].data[0],
                     s[1].data[1],
                     color='#aaaaaa',
                     linewidth=5.0)
            ax1.set_ylabel(s[0].get_name())
            ax1.plot(s[0].data[0], s[0].data[1], color='black')
            ax1.set_zorder(ax2.get_zorder() + 1)  # put ax in front of ax2
            ax1.patch.set_visible(False)  # hide the 'canvas'
            if invert:
                ax1.invert_yaxis()
                ax2.invert_yaxis()
        else:
            ax = f.add_subplot(gs[i, :])
            ax.set_ylabel(s.get_name())
            ax.plot(s.data[0], s.data[1], color='black')
            if invert:
                ax.invert_yaxis()

    canvas.print_figure(filename)
  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()
Exemple #21
0
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
Exemple #22
0
    def view_random_images(self,
                           class_names='any',
                           n_each=1,
                           subset='train',
                           cmap='auto'):

        self.__check_test_subset(subset)

        subset_labels = self.__getattribute__(f'{subset}_labels')
        subset_images = self.__getattribute__(f'{subset}_images')

        if cmap == 'auto':
            subset_dim = len(subset_images[0, :].shape)
            if (subset_dim == 2) or (subset_dim == 3
                                     and subset_images.shape[-1] == 1):
                cmap = plt.cm.binary
            else:
                cmap = None

        if class_names is 'any':
            class_names = [np.random.choice(self.class_names)]
        elif class_names is 'all':
            class_names = self.class_names

        n_classes = len(class_names)

        fig = plt.figure(figsize=(n_classes * 2, n_each * 2))
        gs = GridSpec(n_each, n_classes)
        gs.update(wspace=0.15, hspace=0.05)

        # Get class labels
        class_labels = [self.nm2lab[nm] for nm in class_names]

        # Get label indices for each class
        label_df = pd.DataFrame(subset_labels)
        label_indices = label_df.groupby([0]).indices

        # Now sample from chosen class_labels
        sample_labels = {
            k: np.random.choice(label_indices[k], n_each)
            for k in class_labels
        }

        for i, (cls_lab, indices) in enumerate(sample_labels.items()):
            for j, idx in enumerate(indices):

                ax = plt.subplot(gs[j, i])
                ax.set_xticklabels([])
                ax.set_yticklabels([])
                cls_nm = self.lab2nm[cls_lab]
                img = subset_images[idx]
                ax.imshow(img, cmap=cmap)
                ax.set_axis_off()
                ax.set_aspect('auto')

                if j == 0:
                    ax.set_title(cls_nm, fontdict=dict(weight='bold'))

        return np.reshape(fig.axes, (n_each, len(class_labels)))
def plot_band(ax, nax, xticks_ax, xticklabels_ax, xmin_ax, xmax_ax, ymin, ymax,
              data_merged_ax):
    width_ratios = []
    used_colors = []
    for xmin, xmax in zip(xmin_ax, xmax_ax):
        width_ratios.append(xmax - xmin)

    gs = GridSpec(nrows=1, ncols=nax, width_ratios=width_ratios)
    gs.update(wspace=0.1)

    for iax in range(nax):

        for i in range(len(data_merged_ax[iax])):
            if len(data_merged_ax[iax][i]) > 0:
                ax.plot(data_merged_ax[iax][i][0:, 0],
                        data_merged_ax[iax][i][0:, 1],
                        linestyle=lsty[i],
                        color=color[i])
                used_colors.append(color[i])

                for j in range(2, len(data_merged_ax[iax][i][0][0:])):
                    ax.plot(data_merged_ax[iax][i][0:, 0],
                            data_merged_ax[iax][i][0:, j],
                            linestyle=lsty[i],
                            color=color[i])

        # # ax_0 = plt.subplot(gs[0,:])
        # # ax_0.set_axis_off()
        # cmp = mpl.colors.ListedColormap(used_colors)
        # norm = mpl.colors.BoundaryNorm(boundaries=bn, ncolors=cmp.N)
        # #fig.subplots_adjust(top=0.9)
        #
        # p0 = ax.get_position().get_points().flatten()
        # # l, b, w = [0.15, 0.92, 0.7]
        # # cax = fig.add_axes([0.15, 0.9, 0.2, 0.05])
        # # cax = fig.add_axes([p0[0], 1, p0[2]-p0[0], 0.05])
        # # cb_ax = mpl_toolkits.axes_grid1.inset_locator.inset_axes(ax, loc=3)
        # cb =fig.colorbar(mappable=mpl.cm.ScalarMappable(norm=norm, cmap=cmp), use_gridspec=False,
        #                  ax=ax, orientation='horizontal',shrink=1, fraction=0.1, pad=0.1)

        if iax == 0:
            if options.unitname.lower() == "mev":
                ax.set_ylabel("Frequency (meV)", labelpad=10)
            elif options.unitname.lower() == "thz":
                ax.set_ylabel("Frequency (THz)", labelpad=10, fontsize=12)
            else:
                ax.set_ylabel("Frequency (cm${}^{-1}$)", labelpad=10)

        else:
            ax.set_yticklabels([])
            ax.set_yticks([])

        plt.axis([xmin_ax[iax], xmax_ax[iax], ymin, ymax])
        ax.set_xticks(xticks_ax[iax])
        ax.set_xticklabels(xticklabels_ax[iax])
        ax.xaxis.grid(True, linestyle='-')
        ax.tick_params(axis='y', direction='in', labelsize=12)
        # ax.minorticks_on()
        ax.tick_params(axis='both', direction='in', right=True, top=True)
Exemple #24
0
def gen_metrics_grid():
    grids = {}
    g = GridSpec(2, 2, width_ratios=[1.8, 1], height_ratios=[1, 1])
    grids['inst'] = g[0, 0:2]
    grids['avg'] = g[1, 0]
    grids['scatter'] = g[1, 1]
    g.update(top=0.93, bottom=0.2, right=0.88, hspace=0.4, wspace=0.8)
    return grids
Exemple #25
0
def save_grid_images(images, file_name="grid_images.png"):
    gs = GridSpec(3, 3)
    gs.update(wspace=0.1, hspace=0.1)
    for idx, image in enumerate(images):
        plt.subplot(gs[idx])
        plt.imshow(image[0], cmap='gray')
        plt.axis('off')
    plt.savefig(file_name)
Exemple #26
0
def show_retrieval_indexing(images_retrieval, small_distances, k,
                            path_database, feature_extraction_method, distance,
                            folder_classes):
    acc = accuracy(small_distances, folder_classes, k)
    fig, ax = plt.subplots(len(images_retrieval),
                           k + 1,
                           sharex=True,
                           sharey=True)
    gs1 = GridSpec(len(images_retrieval), k + 1)
    gs1.update(wspace=0.025, hspace=0.5)  # set the spacing between axes.
    if len(images_retrieval) > 1:
        cont = 0
        for cont2, i in enumerate(images_retrieval):
            ax[cont2, 0].imshow(i, cmap='gray', interpolation='none')
            ax[cont2, 0].set_adjustable('box-forced')
            ax[cont2, 0].set_yticks([])
            ax[cont2, 0].set_xticks([])
            ax[cont2, 0].set_ylabel(acc[cont2], fontsize=6)
            cont += 1
            #for each retrieval image returns the k nearer images
            for j in range(k):
                ax[cont2, j + 1].imshow(imread(small_distances[cont2][j]),
                                        cmap='gray',
                                        interpolation='none')
                ax[cont2, j + 1].set_adjustable('box-forced')
                ax[cont2, j + 1].set_yticks([])
                ax[cont2, j + 1].set_xticks([])

                shortName = small_distances[cont2][j]
                shortName = shortName.split('/')[-1]
                shortName = shortName[0:6]
                ax[cont2, j + 1].set_title(shortName, fontsize=8)
                cont += 1
    else:
        ax[0].imshow(images_retrieval[0], cmap='gray', interpolation='none')
        ax[0].set_adjustable('box-forced')
        ax[0].set_yticks([])
        ax[0].set_xticks([])
        ax[0].set_ylabel('Input ', fontsize=8)
        #for each retrieval image returns the k nearer images
        for j in range(k):
            ax[j + 1].imshow(imread(small_distances[0][j]),
                             cmap='gray',
                             interpolation='none')
            ax[j + 1].set_adjustable('box-forced')
            ax[j + 1].set_yticks([])
            ax[j + 1].set_xticks([])

            shortName = fname_database[int(small_distances[0, j])]
            shortName = shortName.split('/')[-1]
            shortName = shortName[0:6]
            ax[j + 1].set_title(shortName, fontsize=8)

    fig.savefig(
        path_database + "results/result" + "_" + feature_extraction_method +
        "_" + distance + "_" + str(k) +
        "_sorting.png")  # save the figure to file   # save the figure to file
    plt.show()
Exemple #27
0
def lsplom(X, ax_ref=None, title='', names=None):
    assert type(X) == list

    if ax_ref is None:
        ax_ref = X
    if names is None:
        names = ['Ch.{}'.format(i) for i in range(len(X))]

    def fix_axes(fig, ax_ref):
        min = np.min([x.min() for x in ax_ref])
        max = np.max([x.max() for x in ax_ref])
        for i, ax in enumerate(fig.axes):
            # ax.text(0, 0, "ax%d" % (i+1), va="center", ha="center")
            ax.set_xlim([min, max])
            ax.set_ylim([min, max])
            # Hide the right and top spines
            ax.spines['right'].set_visible(False)
            ax.spines['top'].set_visible(False)
            ax.spines['left'].set_visible(False)
            ax.spines['bottom'].set_visible(False)
            # Only show ticks on the left and bottom spines
            ax.yaxis.set_ticks_position('left')
            ax.xaxis.set_ticks_position('bottom')
            for tl in ax.get_xticklabels() + ax.get_yticklabels():
                # tl.set_visible(False)
                pass

    N = len(X)
    f = plt.figure()
    plt.suptitle(title, fontsize=18)
    for n, x in enumerate(X):
        features = x.shape[1]
        gs = GridSpec(features, features)
        gs.update(left=n / N + 0.05, right=(n + 1) / N, wspace=0.05)
        for i, j in itertools.product(range(features), range(features)):
            plt.subplot(gs[i, j])
            if i > j:
                plt.plot(x[:, j], x[:, i], '.')
                if False:
                    plt.plot(x[0:2, j], x[0:2, i], 'r-', markersize=2)
                    plt.plot(x[1:3, j], x[1:3, i], 'g-', markersize=2)
                    plt.plot(x[2:4, j], x[2:4, i], 'k-', markersize=2)
                # zero axis
                plt.axhline(y=0, ls="--", c=".3")
                plt.axvline(x=0, ls="--", c=".3")
            elif i == j:
                if i == 0:
                    plt.title(names[n], fontsize=22)
                plt.text(0,
                         0,
                         'd.' + str(i),
                         horizontalalignment='center',
                         verticalalignment='center',
                         fontsize=18)
                plt.axis('off')
            else:
                plt.axis('off')
    fix_axes(f, ax_ref)
Exemple #28
0
    def display_tcks_with_mrview(self,
                                 tcks,
                                 backgrounds,
                                 padding=1,
                                 img_size=5,
                                 offset=None):
        """
        Displays dMRI tractography streamlines using MRtrix's mrview to
        display and screenshot to file the streamlines. Then reload,
        crop and combine the different slice orientations into
        a single panel.

        Parameters
        ----------
        save_path : str | None
            The path of the file to save the image at. If None the
            images are displayed instead
        size : Tuple(2)[int]
            The size of the combined figure to plot
        offset : Tuple(3)[int]
            An array of integers with with to offset the slices displayed
        """
        n_rows = len(tcks)
        # Create figure in which to aggregate the plots
        gs = GridSpec(n_rows, 3)
        gs.update(wspace=0.0, hspace=0.0)
        fig = plt.figure(figsize=(3 * img_size, n_rows * img_size))
        # Create temp dir to store screen captures
        tmpdir = tempfile.mkdtemp()
        for i, (tck, bg) in enumerate(zip(tcks, backgrounds)):
            # Call mrview to display the tracks, capture them to
            # file and then reload the image into a matplotlib
            # grid
            options = ['-tractography.load', tck.path, '-noannotations']
            if offset is not None:
                array = bg.get_array()
                centre = self.image_centre(array, offset)
                options.extend(['-voxel', '{},{},{}'.format(*centre)])
            # Set options to remove cursor, capture hte image and exit
            options.extend(['-lock', 'yes', '-capture.grab', '-exit'])
            imgs = []
            for i in range(3):
                sp.call('{} {} -plane {} {}'.format(self.mrview_path, bg.path,
                                                    2 - i, ' '.join(options)),
                        cwd=tmpdir,
                        shell=(self.mrview_path == 'mrview'))
                img = matplotlib.image.imread(
                    op.join(tmpdir, 'screenshot0000.png'))
                imgs.append(self.crop(img, border=padding))
            padded_size = max(chain(*(a.shape for a in imgs)))
            for i, img in enumerate(imgs):
                img = self.pad_to_size(img, (padded_size, padded_size))
                axis = fig.add_subplot(gs[i])
                axis.get_xaxis().set_visible(False)
                axis.get_yaxis().set_visible(False)
                plt.imshow(img)
        plt.tight_layout(0.0)
Exemple #29
0
 def generateTimeseriesPSCSnapViews(self,
                                    out_dir,
                                    nCols,
                                    nRows,
                                    title='',
                                    basename='psc_img',
                                    psc_min_max=PSC_MIN_MAX):
     """
     Create a list (size Nt = N timepoints) of figures. Each figure contains the PSC volume corresponding to the
      timepoint represented as Nk slices in a matrix-shape
     :return:
     """
     lf = []
     for t in range(self.Nt):
         out_graph_vol_fn = opj(
             out_dir, '_'.join([basename, str(t).zfill(4)]) + '.png')
         if not ope(out_graph_vol_fn):
             # Create a figure
             fig = plt.figure(figsize=(nCols, nRows))
             gs = GridSpec(nRows, nCols)
             gs.update(wspace=0.0,
                       hspace=0.0)  # set the spacing between axes.
             for i in range(nRows):
                 for j in range(nCols):
                     z = i * nCols + j
                     if z <= self.Nt:
                         im = self.f_psc_img[:, :, z, t].T
                         ax = plt.subplot(gs[i, j])
                         ims = ax.imshow(im,
                                         vmin=-psc_min_max,
                                         vmax=psc_min_max,
                                         cmap='seismic')
                         ax.set_xticks([])
                         ax.set_yticks([])
                         ax.axis('off')
                         # for tissueName, bin_map, tcol in zip(TISSUE_NAMES, [self.gm_bin,self.wm_bin,self.csf_bin], TISSUE_COLORS):
                         #     cmap1 = colors.LinearSegmentedColormap.from_list('my_cmap', [COL_TRANSP, tcol], 256)
                         #     mask = bin_map[:,:,z].T
                         #     ax.imshow(mask, cmap=cmap1, interpolation='none', alpha=.5)
             plt.suptitle(title + ' vol {0}/{1}'.format(t + 1, self.Nt))
             # Try to add colorbar at the bottom
             fig.subplots_adjust(right=0.9)
             cbar_ax = fig.add_axes([0.9, 0.25, 0.01,
                                     0.5])  #left bottom width height
             cbar = fig.colorbar(ims,
                                 ticks=[-psc_min_max, 0, psc_min_max],
                                 cax=cbar_ax)
             cbar.ax.set_yticklabels([
                 '-{0}%'.format(psc_min_max), '0',
                 '+{0}%'.format(psc_min_max)
             ])  # vertically oriented colorbar
             #cbar.set_label('Signal')
             # Save
             plt.savefig(out_graph_vol_fn)
             lf.append(out_graph_vol_fn)
             plt.close()
     return lf
 def firstPlot(self):
     """Set grid and axes position in the grid. Plot charts."""
     gs = GridSpec(2, 2)
     gs.update(wspace=0.25, hspace=0.5)
     self.canvas.axes1 = self.canvas.figure.add_subplot(gs[0, 0])
     self.canvas.axes2 = self.canvas.figure.add_subplot(gs[0, 1])
     self.canvas.axes3 = self.canvas.figure.add_subplot(gs[1, :])
     self.plotCharts()
     plt.tight_layout()
Exemple #31
0
def init_figure():
    h = plt.figure(figsize=(8, 10))
    gs = GridSpec(1, 3)
    gs.update(wspace=0.25)
    axr = plt.subplot(gs[0, 0:-1])
    axr.grid(color='gray', linestyle='--', linewidth=0.4, axis='x')
    axb = plt.subplot(gs[0, -1])
    axb.grid(color='gray', linestyle='--', linewidth=0.4, axis='x')
    return h, axr, axb
Exemple #32
0
 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
Exemple #33
0
def gen_simple_grid():
    """ Set a simple grid that only has instantaneous and filtered plots
        without metrics calculation
    """
    grids = {}
    g = GridSpec(2, 1, height_ratios=[1, 1])
    grids['inst'] = g[0, 0]
    grids['avg'] = g[1, 0]
    g.update(top=0.93, bottom=0.13, right=0.88, hspace=0.4, wspace=0.8)
    return grids
Exemple #34
0
def graph():

    plt.switch_backend('TkAgg')  #default on my system
    print(('Backend: {}'.format(plt.get_backend())))
    f = plt.figure(num=str(index) + '.' + prueba, figsize=(20, 15))
    mng = plt._pylab_helpers.Gcf.figs.get(f.number, None)
    mng = plt.get_current_fig_manager()
    mng.resize(*mng.window.maxsize())
    plt.title(str(index) + '.' + prueba)

    gs1 = GridSpec(7, 1)
    gs1.update(left=0.05, right=0.95, wspace=0.5, hspace=0.3, bottom=0.08)

    ax1 = plt.subplot(gs1[0, :])
    ax1.grid()
    ax1.set_ylabel('Roll', fontsize=8)
    L1 = ax1.plot(datos['time'], datos['roll'])

    ax2 = plt.subplot(gs1[1, :])
    ax2.grid()
    ax2.set_ylabel('Pitch', fontsize=8)
    L2 = ax2.plot(datos['time'], datos['pitch'])

    ax3 = plt.subplot(gs1[2, :])
    ax3.grid()
    ax3.set_ylabel('Yaw', fontsize=8)
    L3 = ax3.plot(datos['time'], datos['yaw'])

    ax4 = plt.subplot(gs1[3, :])
    ax4.grid()
    ax4.set_ylabel('X', fontsize=8)
    L4 = ax4.plot(datos['time'], datos['X'])

    ax5 = plt.subplot(gs1[4, :])
    ax5.grid()
    ax5.set_ylabel('Y', fontsize=8)
    L5 = ax5.plot(datos['time'], datos['Y'])

    ax6 = plt.subplot(gs1[5, :])
    ax6.grid()
    ax6.set_ylabel('Y', fontsize=8)
    L6 = ax6.plot(datos['time'], datos['Z'])

    ax7 = plt.subplot(gs1[6, :])
    ax7.grid()
    ax7.set_ylabel('LED_TIME', fontsize=8)
    L7 = ax7.plot(datos['time'], datos['ledblue'])
    L8 = ax7.plot(datos['time'], datos['ledred'])

    date = datetime.datetime.now()
    name = (str(index) + '_' + prueba + str(date.day) + '-' + str(date.month) +
            '-' + str(date.year) + '_' + str(date.hour) + ':' +
            str(date.minute) + ':' + str(date.second) + '.png')
    plt.savefig(name, bbox_inches='tight')
    plt.show()
Exemple #35
0
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")
Exemple #36
0
def _saveDataPlots(dataObjects):
    for dataObject in dataObjects:
        figure = plt.figure()
        gs = GridSpec(2, 1, height_ratios=[3, 1])
        gs.update(hspace=0.7)

        dataObject.generatePlot(
            [figure.add_subplot(gs[0]),
             figure.add_subplot(gs[1])])
        figure.savefig('temp/' + dataObject.texName + '.pdf')
        figure.clear()
Exemple #37
0
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')
Exemple #38
0
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
    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()
Exemple #40
0
	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)
Exemple #41
0
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)
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
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
Exemple #44
0
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
def myShow(X, Y, Z, xs = None, xs2 = None, xlabel = None, xlabel2=None, xdot=None, ydot=None, title = None):
    gs = GridSpec(1, 1)
    gs.update(top = 0.95, bottom = 0.02,left=0.02, right=0.98, hspace=0.2,wspace=0.05)
    ax = plt.subplot(gs[0, 0])
    m = 30
    V = np.array(range(10))**2 * np.sqrt(Z.max() - Z.min()) / np.float(m - 1) + Z.min()
    
    ax.contourf(X, Y, Z, V, alpha=.75, cmap=cm.RdBu)
    C = ax.contour(X, Y, Z, V, colors='black', linewidth=.3, alpha=0.5)
    # put the axes in the centre
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')
    ax.spines['bottom'].set_position(('data',0))
    ax.yaxis.set_ticks_position('left')
    ax.spines['left'].set_position(('data',0))
    # put white boxes around the labels
    for label in ax.get_xticklabels() + ax.get_yticklabels():
        label.set_fontsize(10)
        label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.35 ))
    if xdot != None and ydot != None :
        ax.plot([xdot,xdot],[ydot,ydot], marker='o', color='black')
    if xs != None:
        x = []
        y = []
        for xx,yy in xs:
            x.append(xx)
            y.append(yy)    
        ax.plot(x, y, label=xlabel)
    if xs2 != None:
        x = []
        y = []
        for xx,yy in xs2:
            x.append(xx)
            y.append(yy)    
        ax.plot(x, y, label=xlabel2)
    if xlabel != None:
        ax.legend(loc='upper left')
    if title !=None:
        ax.set_title(title, fontsize=18, position=(0.5, 1.01))
    fig = plt.gcf()
    fig.set_size_inches(10, 5)
def gridspec_demo():
    """If you need even more flexibility with subplots (for example, a 2x2
    figure with only 3 subplots, where one subplot spans two rows), use
    GridSpec.  We won't go into a lot of details here, but it will allow you to
    create plots like the one produced by this function.

    For more details and documentation, see:
    http://matplotlib.sourceforge.net/users/gridspec.html

    """

    # Import GridSpec
    from matplotlib.gridspec import GridSpec

    # Create a new figure
    fig = plt.figure()

    # First grid specification -- a 3x3 plot with only three subplots
    gs1 = GridSpec(3, 3)
    gs1.update(left=0.05, right=0.48, wspace=0.05)
    ax1 = plt.subplot(gs1[:-1, :])
    ax2 = plt.subplot(gs1[-1, :-1])
    ax3 = plt.subplot(gs1[-1, -1])

    # A different grid specification on the same figure.  This essentially
    # expands the figure to be 6x3 by explicitly setting the location of the
    # GridSpec (with gs2.update).
    gs2 = GridSpec(3, 3)
    gs2.update(left=0.55, right=0.98, hspace=0.05)
    ax4 = plt.subplot(gs2[:, :-1])
    ax5 = plt.subplot(gs2[:-1, -1])
    ax6 = plt.subplot(gs2[-1, -1])

    # Remove tick labels and print the name of the axes for each set of axes
    for i, ax in enumerate(fig.axes):
        ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
        for tl in ax.get_xticklabels() + ax.get_yticklabels():
            tl.set_visible(False)

    # Set overall plot title
    plt.suptitle("GridSpec w/ different subplotpars", fontsize=titlesize)
    def _plotStats(self, df, strategyName):
        """
            绘制账户盈亏统计图
        """
        def _dateFormatter(x, pos):
            if not (0 <= int(x) < df.shape[0]):
                return None

            return df.index[int(x)].strftime("%y-%m-%d")

        # create grid spec
        gs = GridSpec(4, 1)
        gs.update(hspace=0)

        # subplot for PnL
        axPnl = plt.subplot(gs[:-1, :])
        axPnl.grid(True)
        axPnl.set_title('{}: 盈亏(%)'.format(strategyName))

        # set x ticks
        x = [x for x in range(df.shape[0])]
        xspace = max((len(x)+9)//10, 1)
        axPnl.xaxis.set_major_locator(FixedLocator(x[:-xspace-1: xspace] + x[-1:]))
        axPnl.xaxis.set_major_formatter(FuncFormatter(_dateFormatter))

        # plot pnl
        for name in df.columns:
            if name not in ['持仓资金(%)', '持仓股票数']:
                axPnl.plot(x, df[name].values, label=name)

        axPnl.legend(loc='upper left', frameon=False)

        # subplot for position
        axPos = plt.subplot(gs[-1, :], sharex=axPnl)
        axPos.grid(True)
        axPos.bar(x, df['持仓资金(%)'].values, label='持仓资金(%)')
        axPos.plot(x, df['持仓资金(%)'].values.cumsum()/np.array(list(range(1, df.shape[0] + 1))), label='平均持仓资金(%)', color='g')
        axPos.plot(x, df['持仓股票数'].values, label='持仓股票数', color='r')

        axPos.legend(loc='upper left', frameon=False)
Exemple #48
0
def plot_both_directions(data, co, fig=None):
    '''
    Parameters
    ----------
    data : ndarray
      shape (52=ntask, nbin)
    co : ndarray
      shape (52,), dtype bool, array of which tasks are center-out
    fig : matplotlib Figure instance
      an existing figure to use, optional
    '''
    if not ((np.rank(data) == 2) & (data.shape[0] == 52)):
        raise ValueError('data has wrong shape; should be (52, nbin),'
                         'actually is %s' % (str(data.shape)))
    if (fig != None) & (not isinstance(fig, Figure)):
        raise ValueError('`fig` must be an instance of Figure')
    if (fig == None):
        fig = plt.figure()
    gs = GridSpec(1,2)
    gs.update(left=0.02, right=0.98, top=0.98, bottom=0.05, hspace=0.02)
    plot_series(data[co], order='co', fig=fig, subplot_spec=gs[0])
    plot_series(data[~co], order='oc', fig=fig, subplot_spec=gs[1])
Exemple #49
0
    def plot_ebands_with_doses(self, ebands_kpath, doses, ylims=None, **kwargs):
        """
        Plot band structure and doses

        Args:
            ebands_kpath:
            doses:
            ylims: Set the data limits for the x-axis in eV. Accept tuple e.g. ``(left, right)``
                or scalar e.g. ``left``. If left (right) is None, default values are used

        Return: |matplotlib-Figure|
        """
        # Build grid plot.
        import matplotlib.pyplot as plt
        from matplotlib.gridspec import GridSpec
        fig = plt.figure()
        ncols = 3
        width_ratios = [2, 0.2, 0.2]
        gspec = GridSpec(1, ncols, width_ratios=width_ratios)
        gspec.update(wspace=0.05)

        ax_ebands = plt.subplot(gspec[0])
        ax_doses = []
        for i in range(2):
            ax = plt.subplot(gspec[i + 1], sharey=ax_ebands)
            ax_doses.append(ax)
            ax.grid(True)
            set_axlims(ax, ylims, "y")

        # Plot electron bands.
        ebands_kpath.plot(ax=ax_ebands, ylims=ylims, show=False)

        # Plot DOSes.
        #doses.edos.plot
        #vdos.edos.plot
        #ax.set_ylabel("")

        return fig
Exemple #50
0
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)

    for data_no, data_dict in enumerate(renderer.plotly_fig['data']):
        d1, d2 = strip_dict_params(data_dict, BLANK_SUBPLOTS['data'][data_no],
                                   ignore=['uid'])
        equivalent, msg = compare_dict(d1, d2)

    equivalent, msg = compare_dict(renderer.plotly_fig['layout'],
                                   BLANK_SUBPLOTS['layout'])
    assert equivalent, msg
def initialize_figure(start_hour, stop_hour):
    # f = plt.figure(figsize=(70, 20))
    # f = plt.figure(figsize=(40, 15))
    # proc = 10 / 100.0
    # f = plt.figure(figsize=(40-40*proc, 15-15*proc))
    f = plt.figure(figsize=(26, 15))

    font_1 = font_0.copy()
    font_1.set_size('20')
    font_1.set_weight('bold')
    plt.suptitle(u"Dynamika zmian asymetrii rytmu serca w wykresach mini-Poincaré w 24-godzinnym nagraniu",
                 fontproperties=font_1, y=0.995, fontsize=25)

    empty_ratio = 0.2
    height_ratios = [empty_ratio,
                     3-2.5*empty_ratio,  # 1 24-tachogram
                     1.5*empty_ratio,
                     0.8,  # 2 arrows
                     #0.1, # label for poincare windows
                     0.1, # label for poincare windows
                     #3,  # 3 poincare plot windows
                     2.5,  # 3 poincare plot windows
                     0.001,  # empty plot
                     0.499,  # data row
                     ]

    num_rows = len(height_ratios)

    num_cols = len(png_files)
    width_ratios = [1] * num_cols

    row_number = 0

    gs1 = GridSpec(num_rows, num_cols, height_ratios=height_ratios, width_ratios=width_ratios)
    gs1.update(left=0.04, right=0.99, wspace=0.0, hspace=0.0, bottom=0.04, top=0.98)
    return f, gs1
Exemple #52
0
def plot_energy():
    '''
    x axis: buffer manager
    y axis: disk status
    '''

    active_l = []
    idle_l = []
    standby_l = []
    spinup_l = []
    spindown_l = []

    x_ticks = []

    for sr in sort_sim_results(_sim_results.values()):
        x_ticks.append(sr.get_x_tick_label())
        ene_val = sr.energy.get_energy_value_list()
        active_l.append(float(ene_val[0]))
        idle_l.append(float(ene_val[1]))
        standby_l.append(float(ene_val[2]))
        spinup_l.append(float(ene_val[3]))
        spindown_l.append(float(ene_val[4]))

    width = 0.50
    ind = np.arange(len(x_ticks))
    ind = ind + 0.5 - width / 2

    bottoms = np.array([0 for i in range(len(x_ticks))])

    # clear figure
    plt.clf()

    # setting layout
    gs = GridSpec(1,1)
    gs.update(left=0.15, right=0.80)
    ax = plt.subplot(gs[:])

    p_active = plt.bar(ind, active_l, width, color='r', label='active', axes=ax)
    bottoms = bottoms + active_l
    p_idle = plt.bar(ind, idle_l, width, color='g', bottom=bottoms, label='idle', axes=ax)
    bottoms = bottoms + idle_l
    p_standby = plt.bar(ind, standby_l, width, color='b', bottom=bottoms, label='standby', axes=ax)
    bottoms = bottoms + standby_l
    p_spindown = plt.bar(ind, spindown_l, width, color='c', bottom=bottoms, label='spindown', axes=ax)
    bottoms = bottoms + spindown_l
    p_spinup = plt.bar(ind, spinup_l, width, color='m', bottom=bottoms, label='spinup', axes=ax)

    # labels setting
    plt.ylabel('Energy Consumption [joule]', size=14)
    plt.yticks(size=16)
    plt.xticks(ind + width / 2, x_ticks)

    # title setting
    plt.title('Replevel=%s, CMA=%s, CMF=%s\n%s'
              % (_sim_results.values()[0].replicalevel, 
                 _sim_results.values()[0].memoryassignor,
                 _sim_results.values()[0].memoryfactory,
                 _sim_results.values()[0].get_workload_param_text()
                 ),
              size=16
    )

    # legend setting 
    plt.legend(
        (p_spinup[0], p_spindown[0], p_standby[0], p_idle[0], p_active[0]),
        ('spinup', 'spindown', 'standby', 'idle', 'active'),
        bbox_to_anchor=(1, 1),
        borderaxespad=0.0,
        loc='upper left',
    )

        
    # set x ticks to the scientific notation
    plt.gca().ticklabel_format(style="sci", scilimits=(0,0), axis="y", size=16)
    
    # plt.show()
    save_figure(plt, 'energy', _output_dir)
Exemple #53
0
def drawBumpExamples(dataSpace, spaceRect, iterList, gsCoords, types, **kw):
    '''Draw a grid-like plot of bump attractor (network activity) examples.

    .. todo::
        code duplication
    '''
    # kw processing
    trialNum   = kw.pop('trialNum', 0)
    exIdx      = kw.pop('exIdx', (0, 0))
    xlabel     = kw.pop('xlabel', True)
    ylabel     = kw.pop('ylabel', True)
    xlabelPos  = kw.pop('xlabelPos', -0.2)
    ylabelPos  = kw.pop('ylabelPos', -0.2)
    xlabel2    = kw.pop('xlabel2', True)
    ylabel2    = kw.pop('ylabel2', True)
    xlabel2Pos = kw.pop('xlabel2os', -0.6)
    ylabel2Pos = kw.pop('ylabel2os', -0.6)
    fontSize   = kw.pop('fontSize', 'medium')
    fig        = kw.pop('fig', plt.gcf())
    # + plotBump() kwargs
    kw['rasterized'] = kw.pop('rasterized', True)
    kw['vmin']       = kw.get('vmin', 0)


    left   = spaceRect[0]
    bottom = spaceRect[1]
    right  = spaceRect[2]
    top    = spaceRect[3]
    exRow, exCol = exIdx

    bumps, wi, we = aggr.aggregateType(dataSpace, iterList, types, trialNum+1,
            ignoreNaNs=False, normalizeTicks=False)

    scaleBar = None
    exRows = top - bottom + 1
    exCols = right - left + 1
    gs = GridSpec(exRows, exCols)
    gsLeft   = gsCoords[0]
    gsBottom = gsCoords[1]
    gsRight  = gsCoords[2]
    gsTop    = gsCoords[3]
    gs.update(left=gsLeft, bottom=gsBottom, right=gsRight, top=gsTop)

    ax = None
    for r in range(bottom, top+1):
        for c in range(left, right+1):
            print(r, c)
            bump = bumps[r][c][trialNum]
            if (not isinstance(bump, np.ndarray)):
                continue

            gsRow = top - r
            gsCol = c - left
            ax = fig.add_subplot(gs[gsRow, gsCol])
            plotBump(ax, bump, **kw)

            if (ylabel and gsCol == 0):
                label = "{0:.2f}".format(we[r][c])
                ax.text(ylabelPos, 0.5, label, rotation=90,
                        transform=ax.transAxes, va='center', ha='right',
                        fontsize=fontSize)
            if (xlabel and gsRow == exRows - 1):
                label = "{0:.2f}".format(wi[r][c])
                ax.text(0.5, xlabelPos, label, transform=ax.transAxes,
                        va='top', ha='center', fontsize=fontSize)
            # Second Y label
            if (ylabel2 and r-bottom == 0 and c-left == 0):
                trans = transforms.blended_transform_factory(ax.transAxes,
                        plt.gcf().transFigure)
                weTxt_y = gsBottom + (gsTop - gsBottom)/2.0
                ax.text(ylabel2Pos, weTxt_y, ylabelText, transform=trans,
                        va='center', ha='right', rotation=90,
                        fontsize=fontSize)


        # Second X label
        if (xlabel2 and r - bottom == 0):
            trans = transforms.blended_transform_factory(plt.gcf().transFigure,
                    ax.transAxes)
            wiTxt_x = gsLeft + (gsRight - gsLeft)/2.0
            ax.text(wiTxt_x, xlabel2Pos, xlabelText, transform=trans, va='top',
                    ha='center', fontsize=fontSize)

    return gs
Exemple #54
0
def specboxdblwide(Data, Labels):

	"""
	Plot several Raman spectra in individual boxes for comparison. 
	The bottom box has an attached box for an additional spectral window.
	"""

	from matplotlib.gridspec import GridSpec
	
# 	_, ColorScheme = colordef(Labels)
	ColorScheme = ['DarkOrange', 'CornflowerBlue', 'OliveDrab']


	xx = Data[:,0].reshape((Data.shape[0],1))
	yy = Data[:,1:]
	nPlots = len(Labels)
	SpecPerPlot = int(yy.shape[1]/nPlots)


# Data for final double-wide spectrum	
	DataEnd = np.loadtxt('AuNPCHIR.csv', delimiter=',', skiprows=1)
	Labels.append('CHIR-090')
	xEnd = DataEnd[:,0].reshape((DataEnd.shape[0],1))
	yEnd = DataEnd[:,1:]

	plt.rc('font', family = 'Arial', size='14')


# Setup grid for all plots and create plots except for last box and plot
	fig = plt.figure(figsize=(7,9))
	gs = GridSpec(nPlots+1,5)
	gs.update(left=0.10, right=0.95, top=0.99, bottom=0.08, hspace=0, wspace=0)
	for i in range(nPlots):
		ax = plt.subplot(gs[i,:-1])
		for j in range(SpecPerPlot):
			ax.plot(xx,yy[:,SpecPerPlot*i+j],c=ColorScheme[j])
		ax.set_yticks(np.arange(0.2, 1.2, 0.2))
		ax.set_yticklabels([1],visible=False)
		ax.set_xticklabels([1],visible=False)	
		ax.set_title(Labels[i],ha='left',x=0.05,y=0.8)
		ax.set_ylim(0,1.1)


# Last box has double-wide plot
	axEndLeft = plt.subplot(gs[-1,:-1])
	axEndRight = plt.subplot(gs[-1,-1])
	for j in range(SpecPerPlot):
		axEndLeft.plot(xEnd,yEnd[:,j],c=ColorScheme[j])
		axEndRight.plot(xEnd,yEnd[:,j]*4,c=ColorScheme[j])
	
	axEndLeft.set_xlim(200,2000)
	axEndLeft.set_yticklabels([1],visible=False)
	axEndLeft.set_title(Labels[-1],ha='left',x=0.05,y=0.8)
	axEndLeft.set_xlabel(r'Wavenumber ($\mathregular{cm}^{-1}$)')
	axEndLeft.set_ylim(0,1.1)

	axEndRight.set_xlim(2000,2400)
	axEndRight.set_xticks([2000,2200,2400])
	axEndRight.set_yticklabels([1],visible=False)
	axEndRight.set_title('(4x)',ha='right',x=0.85,y=0.8)
	axEndRight.set_ylim(0,1.1)
	
	fig.text(0.05,0.5,'Normalized Intensity (a.u.)',rotation=90,ha='center',va='center')

	plt.show()
Exemple #55
0
from matplotlib.gridspec import GridSpec


def make_ticklabels_invisible(fig):
    for i, ax in enumerate(fig.axes):
        ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
        ax.tick_params(labelbottom=False, labelleft=False)


# demo 3 : gridspec with subplotpars set.

fig = plt.figure()

fig.suptitle("GridSpec w/ different subplotpars")

gs1 = GridSpec(3, 3)
gs1.update(left=0.05, right=0.48, wspace=0.05)
ax1 = plt.subplot(gs1[:-1, :])
ax2 = plt.subplot(gs1[-1, :-1])
ax3 = plt.subplot(gs1[-1, -1])

gs2 = GridSpec(3, 3)
gs2.update(left=0.55, right=0.98, hspace=0.05)
ax4 = plt.subplot(gs2[:, :-1])
ax5 = plt.subplot(gs2[:-1, -1])
ax6 = plt.subplot(gs2[-1, -1])

make_ticklabels_invisible(fig)

plt.show()
Exemple #56
0
def main(fname, lines=False, model=False, telluric=False, sun=False,
         rv=False, rv1=False, rv2=False, ccf='none', ftype='1D',
         fitsext='0', order='77'):
    """Plot a fits file with extensive options

    :fname: Input spectra
    :lines: Absorption lines
    :model: Model spectrum
    :telluric: Telluric spectrum
    :sun: Solar spectrum
    :rv: RV of input spectrum
    :rv1: RV of Solar/model spectrum
    :rv2: RV of telluric spectrum
    :ccf: Calculate CCF (sun, model, telluric, both)
    :ftype: Type of fits file (1D, CRIRES, GIANO)
    :fitsext: Slecet fits extention to use (0,1,2,3,4)
    :returns: RV if CCF have been calculated
    """
    print('\n-----------------------------------')
    path = os.path.expanduser('~/.plotfits/')
    pathsun = os.path.join(path, 'solarspectrum_01.fits')
    pathtel = os.path.join(path, 'telluric_NIR.fits')
    pathwave = os.path.join(path, 'WAVE_PHOENIX-ACES-AGSS-COND-2011.fits')
    pathGIANO = os.path.join(path, 'wavelength_GIANO.dat')
    if os.path.isdir(path):
        if sun and (not os.path.isfile(pathsun)):
            print('Downloading solar spectrum...')
            _download_spec(pathsun)
        if telluric and (not os.path.isfile(pathtel)):
            print('Downloading telluric spectrum...')
            _download_spec(pathtel)
        if model and (not os.path.isfile(pathwave)):
            print('Downloading wavelength vector for model...')
            url = 'ftp://phoenix.astro.physik.uni-goettingen.de/HiResFITS//WAVE_PHOENIX-ACES-AGSS-COND-2011.fits'
            urllib.urlretrieve(url, pathwave)
    else:
        os.mkdir(path)
        print('%s Created' % path)
        print('Downloading solar spectrum...')
        _download_spec(pathsun)
        print('Downloading telluric spectrum...')
        _download_spec(pathtel)

    fitsext = int(fitsext)
    order = int(order)

    if ftype == '1D':
        I = fits.getdata(fname, fitsext)
        hdr = fits.getheader(fname, fitsext)
        w = get_wavelength(hdr)
    elif ftype == 'CRIRES':
        d = fits.getdata(fname, fitsext)
        hdr = fits.getheader(fname, fitsext)
        try:
            I = d['Extracted_OPT'] # Gasgano reduction
        except:
            I = d['Extracted_DRACS'] # Dracs reduction
        w = d['Wavelength']*10
    elif ftype == 'GIANO':
        d = fits.getdata(fname)
        I = d[order - 32]  # 32 is the first order
        wd = np.loadtxt(pathGIANO)
        w1, w2 = wd[wd[:, 0] == order][0][1:]
        w = np.linspace(w1, w2, len(I))

    I /= np.median(I)
    # Normalization (use first 50 points below 1.2 as constant continuum)
    maxes = I[(I < 1.2)].argsort()[-50:][::-1]
    I /= np.median(I[maxes])
    dw = 10  # Some extra coverage for RV shifts

    if rv:
        I, w = dopplerShift(wvl=w, flux=I, v=rv, fill_value=0.95)
    w0, w1 = w[0] - dw, w[-1] + dw

    if sun and not model:
        I_sun = fits.getdata(pathsun)
        hdr = fits.getheader(pathsun)
        w_sun = get_wavelength(hdr)
        i = (w_sun > w0) & (w_sun < w1)
        w_sun = w_sun[i]
        I_sun = I_sun[i]
        if len(w_sun) > 0:
            I_sun /= np.median(I_sun)
            if ccf in ['sun', 'both'] and rv1:
                print('Warning: RV set for Sun. Calculate RV with CCF')
            if rv1 and ccf not in ['sun', 'both']:
                I_sun, w_sun = dopplerShift(wvl=w_sun, flux=I_sun, v=rv1, fill_value=0.95)
        else:
            print('Warning: Solar spectrum not available in wavelength range.')
            sun = False
    elif sun and model:
        print('Warning: Both solar spectrum and a model spectrum are selected. Using model spectrum.')
        sun = False

    if model:
        I_mod = fits.getdata(model)
        hdr = fits.getheader(model)
        if 'WAVE' in hdr.keys():
            w_mod = fits.getdata(pathwave)
        else:
            w_mod = get_wavelength(hdr)
        nre = nrefrac(w_mod)  # Correction for vacuum to air (ground based)
        w_mod = w_mod / (1 + 1e-6 * nre)
        i = (w_mod > w0) & (w_mod < w1)
        w_mod = w_mod[i]
        I_mod = I_mod[i]
        if len(w_mod) > 0:
            # https://phoenix.ens-lyon.fr/Grids/FORMAT
            # I_mod = 10 ** (I_mod-8.0)
            I_mod /= np.median(I_mod)
            # Normalization (use first 50 points below 1.2 as continuum)
            maxes = I_mod[(I_mod < 1.2)].argsort()[-50:][::-1]
            I_mod /= np.median(I_mod[maxes])
            if ccf in ['model', 'both'] and rv1:
                print('Warning: RV set for model. Calculate RV with CCF')
            if rv1 and ccf not in ['model', 'both']:
                I_mod, w_mod = dopplerShift(wvl=w_mod, flux=I_mod, v=rv1, fill_value=0.95)
        else:
            print('Warning: Model spectrum not available in wavelength range.')
            model = False

    if telluric:
        I_tel = fits.getdata(pathtel)
        hdr = fits.getheader(pathtel)
        w_tel = get_wavelength(hdr)
        i = (w_tel > w0) & (w_tel < w1)
        w_tel = w_tel[i]
        I_tel = I_tel[i]
        if len(w_tel) > 0:
            I_tel /= np.median(I_tel)
            if ccf in ['telluric', 'both'] and rv2:
                print('Warning: RV set for telluric, Calculate RV with CCF')
            if rv2 and ccf not in ['telluric', 'both']:
                I_tel, w_tel = dopplerShift(wvl=w_tel, flux=I_tel, v=rv2, fill_value=0.95)
        else:
            print('Warning: Telluric spectrum not available in wavelength range.')
            telluric = False

    rvs = {}
    if ccf != 'none':
        if ccf in ['sun', 'both'] and sun:
            # remove tellurics from the Solar spectrum
            if telluric and sun:
                print('Correcting solar spectrum for tellurics...')
                I_sun = I_sun / I_tel
            print('Calculating CCF for the Sun...')
            rv1, r_sun, c_sun, x_sun, y_sun = ccf_astro((w, -I + 1), (w_sun, -I_sun + 1))
            if rv1 != 0:
                print('Shifting solar spectrum...')
                I_sun, w_sun = dopplerShift(w_sun, I_sun, v=rv1, fill_value=0.95)
                rvs['sun'] = rv1
                print('DONE')

        if ccf in ['model', 'both'] and model:
            print('Calculating CCF for the model...')
            rv1, r_mod, c_mod, x_mod, y_mod = ccf_astro((w, -I + 1), (w_mod, -I_mod + 1))
            if rv1 != 0:
                print('Shifting model spectrum...')
                I_mod, w_mod = dopplerShift(w_mod, I_mod, v=rv1, fill_value=0.95)
                rvs['model'] = rv1
                print('DONE')

        if ccf in ['telluric', 'both'] and telluric:
            print('Calculating CCF for the model...')
            rv2, r_tel, c_tel, x_tel, y_tel = ccf_astro((w, -I + 1), (w_tel, -I_tel + 1))
            if rv2 != 0:
                print('Shifting telluric spectrum...')
                I_tel, w_tel = dopplerShift(w_tel, I_tel, v=rv2, fill_value=0.95)
                rvs['telluric'] = rv2
                print('DONE')

    if len(rvs) == 0:
        ccf = 'none'

    if ccf != 'none':
        from matplotlib.gridspec import GridSpec
        fig = plt.figure(figsize=(16, 5))
        gs = GridSpec(1, 5)
        if len(rvs) == 1:
            gs.update(wspace=0.25, hspace=0.35, left=0.05, right=0.99)
            ax1 = plt.subplot(gs[:, 0:-1])
            ax2 = plt.subplot(gs[:, -1])
            ax2.set_yticklabels([])
        elif len(rvs) == 2:
            gs.update(wspace=0.25, hspace=0.35, left=0.01, right=0.99)
            ax1 = plt.subplot(gs[:, 1:4])
            ax2 = plt.subplot(gs[:, 0])
            ax3 = plt.subplot(gs[:, -1])
            ax2.set_yticklabels([])
            ax3.set_yticklabels([])
    else:
        fig = plt.figure(figsize=(16, 5))
        ax1 = fig.add_subplot(111)

    # Start in pan mode with these two lines
    manager = plt.get_current_fig_manager()
    manager.toolbar.pan()

    # Use nice numbers on x axis (y axis is normalized)...
    x_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
    ax1.xaxis.set_major_formatter(x_formatter)

    if sun and not model:
        ax1.plot(w_sun, I_sun, '-g', lw=2, alpha=0.6, label='Sun')
    if telluric:
        ax1.plot(w_tel, I_tel, '-r', lw=2, alpha=0.5, label='Telluric')
    if model:
        ax1.plot(w_mod, I_mod, '-g', lw=2, alpha=0.5, label='Model')
    ax1.plot(w, I, '-k', lw=2, label='Star')

    # Add crosshair
    xlim = ax1.get_xlim()
    cursor = Cursor(ax1)
    plt.connect('motion_notify_event', cursor.mouse_move)
    ax1.set_xlim(xlim)

    if lines:
        y0, y1 = ax1.get_ylim()
        if rv1:
            shift = (1.0 + rv1 / 299792.458)
            for line in lines:
                ax1.vlines(line*shift, y0, y1, linewidth=2, color='m', alpha=0.5)
                ax1.text(line*shift-0.7, 1.2, str(line), rotation=90)
        else:
            for line in lines:
                ax1.vlines(line, y0, y1, linewidth=2, color='m', alpha=0.5)
                ax1.text(line-0.7, 1.2, str(line), rotation=90)

    ax1.set_xlabel('Wavelength')
    ax1.set_ylabel('"Normalized" flux')

    if len(rvs) == 1:
        if 'sun' in rvs.keys():
            ax2.plot(r_sun, c_sun, '-k', lw=2)
            ax2.plot(x_sun, y_sun, '--r', lw=2)
            ax2.set_title('CCF (sun)')
        if 'model' in rvs.keys():
            ax2.plot(r_mod, c_mod, '-k', lw=2)
            ax2.plot(x_mod, y_mod, '--r', lw=2)
            ax2.set_title('CCF (mod)')
        if 'telluric' in rvs.keys():
            ax2.plot(r_tel, c_tel, '-k', lw=2)
            ax2.plot(x_tel, y_tel, '--r', lw=2)
            ax2.set_title('CCF (tel)')
        ax2.set_xlabel('RV [km/s]')

    elif len(rvs) == 2:
        if 'sun' in rvs.keys():
            ax2.plot(r_sun, c_sun, '-k', lw=2)
            ax2.plot(x_sun, y_sun, '--r', lw=2)
            ax2.set_title('CCF (sun)')
        if 'model' in rvs.keys():
            ax2.plot(r_mod, c_mod, '-k', lw=2)
            ax2.plot(x_mod, y_mod, '--r', lw=2)
            ax2.set_title('CCF (mod)')
        ax3.plot(r_tel, c_tel, '-k', lw=2)
        ax3.plot(x_tel, y_tel, '--r', lw=2)
        ax3.set_title('CCF (tel)')

        ax2.set_xlabel('RV [km/s]')
        ax3.set_xlabel('RV [km/s]')

    if rv:
        ax1.set_title('%s\nRV correction: %s km/s' % (fname, rv))
    elif rv1 and rv2:
        ax1.set_title('%s\nSun/model: %s km/s, telluric: %s km/s' % (fname, rv1, rv2))
    elif rv1 and not rv2:
        ax1.set_title('%s\nSun/model: %s km/s' % (fname, rv1))
    elif not rv1 and rv2:
        ax1.set_title('%s\nTelluric: %s km/s' % (fname, rv2))
    elif ccf == 'model':
        ax1.set_title('%s\nModel(CCF): %s km/s' % (fname, rv1))
    elif ccf == 'sun':
        ax1.set_title('%s\nSun(CCF): %s km/s' % (fname, rv1))
    elif ccf == 'telluric':
        ax1.set_title('%s\nTelluric(CCF): %s km/s' % (fname, rv2))
    elif ccf == 'both':
        ax1.set_title('%s\nSun/model(CCF): %s km/s, telluric(CCF): %s km/s' % (fname, rv1, rv2))
    else:
        ax1.set_title(fname)
    if sun or telluric or model:
        ax1.legend(loc=3, frameon=False)
    plt.show()

    return rvs
Exemple #57
0
class Figure:

    def __init__(self,nxpix=1280):

        """Generate a 3D stereoscopic view of ~15k WISE sources. Color
        clusters of objects differently.

        Parameters:
        -----------
        nxpix : int
            Number of pixels of the output (PNG) file. An aspect ratio
            of 16:9 is assumed.
        """

        self.dpi = 100
        self.aspect = 16./9.

        self.ux = nxpix/float(self.dpi)
        self.uy = self.ux/self.aspect

        # Load data (WISE colors)
        print "Loading data..."
        with N.load('data.npz') as datafile:
            self.x, self.y, self.z = datafile['x'], datafile['y'], datafile['z']

        print "Number of objects: %d" % self.x.size
        print "Done."


    def make_stereoscopic_3d_scatter(self,azimuth=-18,saveformat='png'):

        """Generate two panels, 5 degrees apart in azimuth. Cross eyes for
        stereoscopic view.

        Parameters:
        -----------
        azimuth : {float,int}
            The azimuth angle (in degrees) at which the camera views
            the scene.

        saveformat : str
            Generate an output file, with the supplied azimuth in the
            file name. Must be either 'png' (recommended, default) or
            'pdf' (will be rather slow to save).

        Returns:
        --------
        Nothing, but saves an output file.

        """

        assert (saveformat in ('png','pdf')), "saveformat must be 'png' (recommended) or 'pdf' (will be very slow to save)."

        filename = '3D_color_stereoscopic_az%07.2f.%s' % (azimuth,saveformat)
        print "Generating plot %s" % filename

        self.setup_figure(figsize=(self.ux,self.uy))   # width, height

        # left panel (=right eye)
        ax1 = p.subplot(self.gs3D[0],projection='3d',aspect='equal',axisbg='w')
        plot_scatter_3D(self.fig,ax1,1,self.x,self.y,self.z,self.uy,azimuth=azimuth)

        # right panel (=left eye)
        ax2 = p.subplot(self.gs3D[1],projection='3d',aspect='equal',axisbg='w')
        plot_scatter_3D(self.fig,ax2,2,self.x,self.y,self.z,self.uy,azimuth=azimuth-5)

        if saveformat == 'png':
            p.savefig(filename,dpi=100)
        else:
            p.savefig(filename)

        p.close()


    def make_movie_frames(self,azstart=1,azstop=10,azstep=1):

        """Helper function to generate frames (for a video) with varying
        azimuth angle.

        Parameters:
        -----------
        azstart, azstop, azstep : float-ables
            The azimuth angles of first frame, last frame
            (approximate), and of the step size. All in degrees. All
            can be negative (determines direction of scene rotation)

        """

        try:
            azstart = float(azstart)
            azstop = float(azstop)
            azstep = float(azstep)
        except ValueError:
            raise Exception, "azstart, azstop, azstep must be convertible to a floating point number."

        if azstop < azstart:
            azstep = -N.abs(azstep)
            
        allaz = N.arange(azstart,azstop,azstep)
            
        for j,az in enumerate(allaz):
            print "Generating frame file %d of %d" % (j+1,len(allaz))
            self.make_stereoscopic_3d_scatter(azimuth=az)


    def setup_figure(self,figsize):

        """Set up the figure and rc params."""

        self.fontsize = 2*self.uy

        p.rcParams['axes.labelsize'] = self.fontsize
        p.rcParams['font.size'] = self.fontsize
        p.rcParams['legend.fontsize'] = self.fontsize-2
        p.rcParams['xtick.labelsize'] = self.fontsize
        p.rcParams['ytick.labelsize'] = self.fontsize

        self.fig = p.figure(figsize=figsize)  # width, height  300dpi
        self.fig.suptitle('Clustering of astronomical objects in WISE 3D color space\n(cross your eyes for stereoscopic view)',color='k',fontsize=self.fontsize+2)

        # this will hold the 3D scatter plot
        self.gs3D = GridSpec(1,2)
        self.gs3D.update(left=0.02,right=0.98,bottom=0.,top=1.,wspace=0.05,hspace=0.)
Exemple #58
0
for line in srf08Distancetxt:
	srfDistance_.append(line)		
srf08Distancetxt.close()

plt.figure(1)
plt.subplots_adjust(hspace = .4)

tl = 0
th = 30
if int (sys.argv[1]) < 2 :
	plt.suptitle("Sensors response for " + sys.argv[1] + " meter, " + sys.argv[2], fontsize = 15)
else:
	plt.suptitle("Sensors response for " + sys.argv[1] + " meters, " + sys.argv[2], fontsize = 15)
#srf08
gs1 = GridSpec(3, 3)
gs1.update(left=0.03, right=0.98, wspace=0)

pir = plt.subplot(gs1[1,:])
pir.plot(pirTime_, pirData_, 'r')
plt.axis([tl,th,0,1.1])
plt.ylabel('Motion status')
plt.title('PIR sensor')

srf08 = plt.subplot(gs1[:1, :])
srf08.plot(srf08Time_, srf08Data_, 'g')
plt.axis([tl,th,0,1.1])
plt.ylabel('Motion status')
plt.title('Ultrasonic SRF08 sensor')

xband = plt.subplot(gs1[-1, :])
xband.plot(xBandTime_, xBandData_, 'b')
#Setting the table with minimum scatter
rawdata, err_rawdata = data_min_scatter[str(0)].values,data_min_scatter[str(1)].values
# ********************************************************************************************************************
# ********************************************************************************************************************

print 'Make a beautifull plot from flux results: \n'
for i in range(len(data_min_scatter.columns)-2):
    if (i % 2 == 0) and (i != int(data_min_scatter.columns[-1])-2):
        refstar = data_min_scatter[str(i+2)].values
        err_refstar = data_min_scatter[str(i+3)].values
        rawflux = rawdata/refstar
        eflux = rawflux*np.sqrt((err_rawdata/rawdata)**2 + (err_refstar/refstar)**2)
        f = plt.figure()
        plt.suptitle('Minimum scatter of the flux \n @'+files_csv[id_min]+'\ncolumns = '+str(i+3)+' Reference Star/ '+str(i+4)+' Err_flux',fontsize=12)
        gs1 = GridSpec(2, 2, width_ratios=[1,2],height_ratios=[4,1])
        gs1.update(wspace=0.5)
        ax1 = plt.subplot(gs1[:-1, :])
        ax2 = plt.subplot(gs1[-1, :])
        ax1.grid()
        ax1.errorbar(hjd,rawflux,yerr=eflux,ecolor='g')
        ax1.set_xticklabels([])
        ax1.set_ylabel('Relative Flux')
        ax2.grid()
        ax2.plot(hjd,airmass,color='green')
        plt.yticks(np.array([airmass.min(), (airmass.min()+airmass.max())/2., airmass.max()]))
        ax2.set_xlabel('JD')
        ax2.set_ylabel('airmass')
        plt.savefig(save_path+'/rawflux_StarColumn_'+str(i+3)+'.png')

os.chdir(original_path)
print 'Total duration = ',abs(exotred.time.time()-start_time)/60.,' minutes'