def plot_waveforms_opto(spike_data, prm):
    if 'random_snippets_opto' in spike_data:
        print(
            'I will plot the waveform shapes for each cluster for opto_tagging data.'
        )
        save_path = prm.get_output_path() + '/Figures/opto_tagging'
        if os.path.exists(save_path) is False:
            os.makedirs(save_path)
        for cluster in range(len(spike_data)):
            cluster = spike_data.cluster_id.values[cluster] - 1
            max_channel = spike_data.primary_channel[cluster]
            highest_value = np.max(
                spike_data.random_snippets_opto[cluster][max_channel - 1, :, :]
                * -1)
            lowest_value = np.min(
                spike_data.random_snippets_opto[cluster][max_channel - 1, :, :]
                * -1)
            fig = plt.figure(figsize=(5, 5))
            grid = plt.GridSpec(2, 2, wspace=0.5, hspace=0.5)
            for channel in range(4):
                plot_spikes_for_channel(grid, highest_value, lowest_value,
                                        spike_data, cluster, channel,
                                        'random_snippets_opto')

            plt.savefig(save_path + '/' + spike_data.session_id[cluster] +
                        '_' + str(cluster + 1) + '_waveforms_opto.png',
                        dpi=300,
                        bbox_inches='tight',
                        pad_inches=0)
            # plt.savefig(save_path + '/' + spike_data.session_id[cluster] + '_' + str(cluster + 1) + '_waveforms_opto.pdf', bbox_inches='tight', pad_inches=0)
            plt.close()
示例#2
0
def plot_phased_tg(t2, f3, tg, stark=False):
    from nudie.utils.plotting import shiftedColorMap

    if stark:
        return

    res = np.real(tg).T

    nlevels = 50
    vmax, vmin = np.max(res), np.min(res)
    ticker = mpl.mpl.ticker.MaxNLocator(nlevels)
    levels = ticker.tick_values(vmin, vmax)
    #levels = levels[np.abs(levels) > levels_threshold]
    xsection = res[800, :]

    midpoint = 1 - vmax / (vmax + abs(vmin))
    cmap = shiftedColorMap(mpl.cm.RdBu_r, midpoint=midpoint)

    fig = mpl.figure()
    gs = mpl.GridSpec(2, 2, height_ratios=[2, 1], width_ratios=[5, 0.1])
    ax1 = fig.add_subplot(gs[0, 0])
    ax2 = fig.add_subplot(gs[1, 0])
    ax3 = fig.add_subplot(gs[:, 1])

    ax1.contour(-t2, f3, res, 10, colors='k')
    cf = ax1.contourf(-t2, f3, res, levels=levels, cmap=cmap)

    ax1.set_ylabel('detection frequency')
    ax1.set_xlabel('t2 time')
    mpl.colorbar(cf, cax=ax3, use_gridspec=True)

    ax2.plot(-t2, xsection)
    ax2.grid()
    gs.tight_layout(fig)
    mpl.show()
def make_combined_autocorr_plot(time_10, corr_10, time_250, corr_250,
                                spike_data, save_path, cluster):
    grid = plt.GridSpec(2, 1, hspace=0.5)
    autocorr_plot = plt.subplot(grid[0, 0])
    plt.suptitle("Autocorrelograms", fontsize=24)
    plt.xlabel('Time lag (ms)', fontsize=14)
    plt.ylabel('Probability', fontsize=14)
    plt.xlim(-10, 10)
    plt.xticks(fontsize=14)
    plt.yticks(fontsize=14)
    plt.xticks([-10, 0, 10], [-10, 0, 10])
    plt.bar(time_10, corr_10, align='center', width=1, color='black')

    autocorr_plot2 = plt.subplot(grid[1, 0])
    plt.xlim(-250, 250)
    plt.xticks(fontsize=14)
    plt.yticks(fontsize=14)
    plt.xlabel('Time lag (ms)', fontsize=14)
    plt.ylabel('Probability', fontsize=14)
    plt.xticks([-250, 0, 250], [-250, 0, 250])
    plt.bar(time_250, corr_250, align='center', width=1, color='black')
    plt.savefig(save_path + '/' + spike_data.session_id[cluster] + '_' +
                str(cluster + 1) + '_autocorrelograms.png',
                dpi=300,
                bbox_inches='tight',
                pad_inches=0)
    plt.close()
示例#4
0
    def _prepareChart(self) -> None:
        # Do not use LaTeX if NO_LATEX variable is set.
        no_latex = bool(os.getenv('NO_LATEX', False))
        params = dict(font='serif', style='white')
        if not no_latex:
            params['rc'] = {'text.usetex': True}
        sns.set(**params)

        # Set up the subplot grid
        f = plt.figure(figsize=(6, 4))
        gs = plt.GridSpec(10, 10, hspace=0)

        ax_heatmap = f.add_subplot(gs[4:, :])
        ax_plot = f.add_subplot(gs[:4, :], sharex=ax_heatmap)

        plt.setp(ax_heatmap.yaxis.get_majorticklines(), visible=False)
        plt.setp(ax_heatmap.get_yticklabels(), visible=False)

        plt.setp(ax_plot.get_xticklabels(), visible=False)
        plt.setp(ax_plot.xaxis.get_majorticklines(), visible=False)
        plt.setp(ax_plot.xaxis.get_minorticklines(), visible=False)

        # Make the grid look nice
        sns.utils.despine(f)
        sns.utils.despine(ax=ax_plot, left=True)
        f.tight_layout()

        plt.sca(ax_heatmap)
        sns.heatmap(self.data,
                    linewidth=0.01,
                    xticklabels=10,
                    cbar_kws=dict(orientation='horizontal',
                                  shrink=.75,
                                  aspect=25,
                                  pad=.2))
        ax_heatmap.set(ylabel='Lane')

        plt.sca(ax_plot)
        colors = sns.color_palette(['#000'])
        sns.set_palette(colors)
        if not no_latex:
            ylabel = 'Density ($\\frac{vehicles}{step}$)'
        else:
            ylabel = 'Density (vehicles/step)'
        ax_plot.set(xlabel=None, ylabel=ylabel)
        sns.lineplot(data=self.data.sum(axis=0) / self.data.shape[0])
def plot_waveforms(spike_data, prm):
    print('I will plot the waveform shapes for each cluster.')
    save_path = prm.get_output_path() + '/Figures/firing_properties'
    if os.path.exists(save_path) is False:
        os.makedirs(save_path)
    for cluster in range(len(spike_data)):
        cluster = spike_data.cluster_id.values[cluster] - 1
        fig = plt.figure(figsize=(5, 5))
        plt.suptitle("Spike waveforms", fontsize=24)
        grid = plt.GridSpec(2, 2, wspace=1, hspace=0.5)
        for channel in range(4):
            plot_spikes_for_channel_centered(grid, spike_data, cluster,
                                             channel, 'random_snippets')

        plt.savefig(save_path + '/' + spike_data.session_id[cluster] + '_' +
                    str(cluster + 1) + '_waveforms.png',
                    dpi=300,
                    bbox_inches='tight',
                    pad_inches=0)
        # plt.savefig(save_path + '/' + spike_data.session_id[cluster] + '_' + str(cluster + 1) + '_waveforms.pdf', bbox_inches='tight', pad_inches=0)
        plt.close()
示例#6
0
sys.path.append("/usr/local/bin/")

import matplotlib
matplotlib.rcParams['axes.linewidth'] = 0.5
from astropy.io import fits

galaxy = "PTF11qnr"
data = pyfits.getdata("../MUSE/AMUSING_dataproducts/%s.SSP.cube.fits.gz" %
                      galaxy)
tessela = data[1]
V = np.log10(data[0])

tessela[tessela == 0] = np.nan

fig = plt.figure(figsize=(4, 2))
grid = plt.GridSpec(1, 2, top=0.999, right=0.995, left=0.1, bottom=0.2)
ax = fig.add_subplot(grid[0, 0])
ax1 = fig.add_subplot(grid[0, 1])

ax.imshow(V, origin="l", vmin=-3.5, vmax=-0.8, cmap="binary", aspect="auto")
ax1.imshow(tessela, origin="l", cmap="gist_earth", aspect="auto")

ax.set_xlabel("pixels", fontsize=8)  #,labelpad = 0)
ax.set_ylabel("pixels", fontsize=8)  #,labelpad = 0)
plt.setp(ax.get_yticklabels(), rotation='vertical', fontsize=8)
plt.setp(ax.get_xticklabels(), fontsize=8)

ax1.set_xlabel("pixels", fontsize=8)  #,labelpad = 0)
plt.setp(ax1.get_yticklabels(), rotation='vertical', fontsize=8)
plt.setp(ax1.get_xticklabels(), fontsize=8)
示例#7
0
              axis=1)[:A.shape[0] / 4, :]
bina = 1
binb = 1
a_num = A.shape[0]
b_num = A.shape[1]
a_vv = np.copy(A.reshape(a_num // bina, bina, b_num // binb, binb))
A = np.mean(np.mean(a_vv, axis=3), axis=1)
cj = np.append(cj[:, 7 * cj.shape[1] / 8:cj.shape[1]],
               cj[:, :cj.shape[1] / 8],
               axis=1)[:cj.shape[0] / 4, :]

#cg = np.log10(np.power(np.abs(cj[:cj.shape[0]/2,:]),2))
#vmin = A.mean()-2.*A.std()
#vmax = A.mean()+A.std()
#print cg.shape,A.shape
gs = plt.GridSpec(2, 4, wspace=0.4, hspace=0.4)
fig = plt.figure(figsize=(6, 6))
fig.add_subplot(gs[:2, :2])
plt.figure(1)
#plt.subplot(121)
x = np.linspace(-25.4, +25.4, A.shape[1], endpoint=True)
y = np.linspace(0, 128, A.shape[0], endpoint=True)
x_ds, y_ds = np.meshgrid(x, y)
A = np.where(A > 0, A, 0.0001)
A = np.log10(np.power(A, 2))
print y_ds.shape, x_ds.shape, A.shape
plt.pcolormesh(x_ds, y_ds, A, cmap=cm.Greys, vmin=-1, vmax=3)
#ax=plt.imshow(np.log10(np.power(A,2)), aspect='auto', cmap=cm.Greys, interpolation='nearest', vmin=-1, origin='lower')
plt.colorbar()
plt.ylim(0, 128)
plt.xlim(-25.4, 25.4)
示例#8
0
        p_guess_quad_zenith = [1.5, -1]
        poptquad_zenith, pcovquad_zenith = opt.curve_fit(
            quad_curvefit_zenith,
            dec,
            ratio,
            p0=p_guess_quad_zenith,
            sigma=ratio_err,
            maxfev=10000)
        redchisq_decfits[3] = redchisq(
            ratio, quad_curvefit_zenith(dec, *poptquad_zenith), ratio_err,
            2)[0]
        a_fit[3], c_fit[3] = poptquad_zenith[0], poptquad_zenith[1]

        plt.rcParams[
            'figure.figsize'] = 20, 5  # Setting figure size. Have to close window for it to have effect.
        gs = plt.GridSpec(1, 6)
        ax = plt.subplot(gs[0])
        ax1 = plt.subplot(gs[1])
        ax2 = plt.subplot(gs[2])
        ax3 = plt.subplot(gs[3])
        ax4 = plt.subplot(gs[4])
        ax5 = plt.subplot(gs[5])
        # ax.scatter(dec, ratio, marker='+',color = 'k',c=SNR, cmap=plt.cm.Greys)#, c=SNR, cmap=plt.cm.Greys)
        # ax1.scatter(dec, ratio, marker='+',color ='k',c=SNR, cmap=plt.cm.Greys)#, c=SNR, cmap=plt.cm.Greys)
        # ax2.scatter(dec, ratio, marker='+',color ='k',c=SNR, cmap=plt.cm.Greys)#, c=SNR, cmap=plt.cm.Greys)
        # ax3.scatter(dec, ratio, marker='+',color ='k',c=SNR, cmap=plt.cm.Greys)
        # ax4.scatter(dec, ratio, marker='+',color ='k',c=SNR, cmap=plt.cm.Greys)
        # ax5.scatter(dec, ratio, marker='+',color ='k',c=SNR, cmap=plt.cm.Greys)
        ax.scatter(dec, ratio, marker='o', color='k', c=SNR,
                   cmap=plt.cm.Greys)  #, c=SNR, cmap=plt.cm.Greys)
        ax1.scatter(dec,
示例#9
0
def multiplot_violin_paper(df, fname, settings):
    """Plot data properties as violin plots.
    
    Far from optimized code: seaborn does not make this easy so added
    a lot of formatting using raw matplotlib commands

    Args:
        df (DataFrame): prediction dataframe
        fname (filename):
        settings (ExperimentSettings): custom class to hold hyperparameters

    Returns:
        figure (png)
    """

    # Set up the axes with gridspec
    plt.clf()
    fig = plt.figure()
    grid = plt.GridSpec(2, 4, hspace=0.2, wspace=0.2)
    ax_00 = fig.add_subplot(grid[0, 0])
    ax_01 = fig.add_subplot(grid[0, 1], sharey=ax_00)
    ax_02 = fig.add_subplot(grid[0, 2], sharey=ax_00)
    ax_03 = fig.add_subplot(grid[0, 3], sharey=ax_00)
    ax_1 = fig.add_subplot(grid[1, :])

    axes = [ax_00, ax_01, ax_02, ax_03]

    # Ia vs non Ia
    sns.set_palette(sns.color_palette(BI_COLORS))
    g = sns.violinplot(
        x="target",
        y="SIM_PEAKMAG_g",
        hue="salt",
        data=df,
        split=True,
        ax=axes[0],
        inner="quartile",
    )
    g.set_xlabel("")
    g.legend_.remove()
    g.yaxis.set_tick_params(labelsize=14)
    g.set_title("g", fontsize=14)
    g.set_ylabel("magnitude", fontsize=14)
    g.set_ylim(20, 28)
    g.spines["right"].set_visible(False)
    g.spines["top"].set_visible(False)
    g.set_xticklabels(["Ia", "nonIa"], fontsize=14)

    g = sns.violinplot(
        x="target",
        y="SIM_PEAKMAG_i",
        hue="salt",
        data=df,
        split=True,
        ax=axes[1],
        inner="quartile",
    )
    g.set_xlabel("")
    g.set_ylabel("")
    g.legend_.remove()
    g.yaxis.set_ticks_position("none")
    g.set_title("i", fontsize=14)
    g.set_ylim(20, 28)
    g.spines["right"].set_visible(False)
    g.spines["top"].set_visible(False)
    g.spines["left"].set_visible(False)
    g.set_xticklabels(["Ia", "nonIa"], fontsize=14)
    plt.setp(axes[1].get_yticklabels(), visible=False)

    g = sns.violinplot(
        x="target",
        y="SIM_PEAKMAG_r",
        hue="salt",
        data=df,
        split=True,
        ax=axes[2],
        inner="quartile",
    )
    g.legend_.remove()
    g.yaxis.set_ticks_position("none")
    g.set_xlabel("")
    g.set_ylabel("")
    g.set_title("r", fontsize=18)
    g.xaxis.set_tick_params(labelsize=14)
    g.set_ylim(20, 28)
    g.spines["right"].set_visible(False)
    g.spines["top"].set_visible(False)
    g.spines["left"].set_visible(False)
    g.set_xticklabels(["Ia", "nonIa"], fontsize=14)
    plt.setp(axes[2].get_yticklabels(), visible=False)

    g = sns.violinplot(
        x="target",
        y="SIM_PEAKMAG_z",
        hue="salt",
        data=df,
        split=True,
        ax=axes[3],
        inner="quartile",
    )
    g.legend_.remove()
    g.yaxis.set_ticks_position("none")
    g.set_title("z", fontsize=14)
    g.set_xlabel("")
    g.set_ylabel("")
    g.set_ylim(20, 28)
    g.spines["right"].set_visible(False)
    g.spines["top"].set_visible(False)
    g.spines["left"].set_visible(False)
    g.set_xticklabels(["Ia", "nonIa"], fontsize=14)
    plt.setp(axes[3].get_yticklabels(), visible=False)

    # redshift
    g = sns.violinplot(
        x="SNTYPE",
        y="SIM_REDSHIFT_CMB",
        hue="salt",
        data=df,
        split=True,
        ax=ax_1,
        inner="quartile",
    )
    g.set_ylabel("simulated redshift", fontsize=14)
    g.set_xlabel("")
    g.set_ylim(0, 1.0)
    g.set_xticklabels([a for a in settings.sntypes.values()], fontsize=14)
    g.xaxis.set_tick_params(labelsize=14)
    g.yaxis.set_tick_params(labelsize=14)
    g.legend_.remove()
    g.spines["right"].set_visible(False)
    g.spines["top"].set_visible(False)
    g.spines["bottom"].set_visible(False)

    plt.savefig(f"{settings.figures_dir}/multiviolin_{fname}.png")
    plt.close()
    del fig
示例#10
0
dec18_ind = np.where(dec >= 18.)
ratio_dec18 = ratio[dec18_ind]
ratio_err_dec18 = ratio_err[dec18_ind]
dec18_less_ind = np.where(dec < 18.)
ratio_less_dec18 = ratio[dec18_less_ind]
ratio_err_less_dec18 = ratio_err[dec18_less_ind]

SNR = ratio_err

# poptzero_ratio_dec18, pcovzero_ratio_dec18 = opt.curve_fit(zero_curvefit, dec[dec18_ind], ratio_dec18, p0 = p_guess_zero, sigma = ratio_err_dec18, maxfev = 10000)
# poptzero_ratio_less_dec18, pcovzero_ratio_less_dec18 = opt.curve_fit(zero_curvefit, dec[dec18_less_ind], ratio_less_dec18, p0 = p_guess_zero, sigma = ratio_err_less_dec18, maxfev = 10000)

plt.rcParams[
    'figure.figsize'] = 12, 5  # Setting figure size. Have to close window for it to have effect.
gs = plt.GridSpec(1, 2, wspace=0, width_ratios=[3, 1])
ax = plt.subplot(gs[0])
ax1 = plt.subplot(gs[1])
ax.scatter(dec,
           ratio,
           marker='o',
           c=SNR,
           cmap=plt.cm.Greys_r,
           norm=matplotlib.colors.LogNorm())  #, c=SNR, cmap=plt.cm.Greys)
dec_long = np.arange(
    min(dec) + 0.07 * min(dec),
    max(dec) + 0.10 * max(dec), 0.1)
dec_long = np.array(dec_long)
if options.do_ratio_errors:
    ax.plot(dec_long,
            np.ones(len(dec_long)) * zero_curvefit(dec_long, a_mcmc_plot),
示例#11
0
def heatmap(x, y, tfs=12, bkg_color='#F1F1F1', separate_first=0, **kwargs):
    """ Calculate a heatmap

    Based on: https://towardsdatascience.com/better-heatmaps-and-correlation-matrix-plots-in-python-41445d0f2bec
    """
    if 'color' in kwargs:
        color = kwargs['color']
    else:
        color = [1] * len(x)

    if 'palette' in kwargs:
        palette = kwargs['palette']
        n_colors = len(palette)
    else:
        n_colors = 256  # Use 256 colors for the diverging color palette
        palette = sns.diverging_palette(
            359, 122, s=90, n=500)  #sns.color_palette("BrBG", n_colors)

    if 'color_range' in kwargs:
        color_min, color_max = kwargs['color_range']
    else:
        color_min, color_max = min(color), max(
            color
        )  # Range of values that will be mapped to the palette, i.e. min and max possible correlation

    def value_to_color(val):
        if color_min == color_max:
            return palette[-1]
        else:
            val_position = float((val - color_min)) / (
                color_max - color_min
            )  # position of value in the input range, relative to the length of the input range
            val_position = min(max(val_position, 0),
                               1)  # bound the position betwen 0 and 1
            ind = int(val_position *
                      (n_colors - 1))  # target index in the color palette
            return palette[ind]

    if 'size' in kwargs:
        size = kwargs['size']
    else:
        size = [1] * len(x)

    if 'size_range' in kwargs:
        size_min, size_max = kwargs['size_range'][0], kwargs['size_range'][1]
    else:
        size_min, size_max = min(size), max(size)

    size_scale = kwargs.get('size_scale', 500)

    def value_to_size(val):
        if size_min == size_max:
            return 1 * size_scale
        else:
            val_position = (val - size_min) * 0.99 / (
                size_max - size_min
            ) + 0.01  # position of value in the input range, relative to the length of the input range
            val_position = min(max(val_position, 0),
                               1)  # bound the position betwen 0 and 1
            return val_position * size_scale

    if 'x_order' in kwargs:
        x_names = [t for t in kwargs['x_order']]
    else:
        x_names = [t for t in sorted(set([v for v in x]))]
    x_to_num = {p[1]: p[0] for p in enumerate(x_names)}

    if 'y_order' in kwargs:
        y_names = [t for t in kwargs['y_order']]
    else:
        y_names = [t for t in sorted(set([v for v in y]))]
    y_to_num = {p[1]: p[0] for p in enumerate(y_names)}

    plot_grid = plt.GridSpec(1, 30, hspace=0.2,
                             wspace=0.1)  # Setup a 1x10 grid
    ax = plt.subplot(plot_grid[:, :-1]
                     )  # Use the left 14/15ths of the grid for the main plot

    marker = kwargs.get('marker', 's')

    kwargs_pass_on = {
        k: v
        for k, v in kwargs.items() if k not in [
            'color', 'palette', 'color_range', 'size', 'size_range',
            'size_scale', 'marker', 'x_order', 'y_order'
        ]
    }
    ax.scatter(x=[x_to_num[v] for v in x],
               y=[y_to_num[v] for v in y],
               marker=marker,
               s=[value_to_size(v) for v in size],
               c=[value_to_color(v) for v in color],
               **kwargs_pass_on)
    ax.set_xticks([v for k, v in x_to_num.items()])
    ax.set_xticklabels([k for k in x_to_num],
                       rotation=45,
                       horizontalalignment='right',
                       fontsize=tfs)
    ax.set_yticks([v for k, v in y_to_num.items()])
    ax.set_yticklabels([k for k in y_to_num], fontsize=tfs)

    ax.grid(False, 'major')
    ax.grid(True, 'minor')
    ax.set_xticks([t + 0.5 for t in ax.get_xticks()], minor=True)
    ax.set_yticks([t + 0.5 for t in ax.get_yticks()], minor=True)

    ax.set_xlim([-0.5, max([v for v in x_to_num.values()]) + 0.5])
    ax.set_ylim([-0.5, max([v for v in y_to_num.values()]) + 0.5])
    ax.set_facecolor(bkg_color)

    if separate_first:
        l = np.sqrt(len(x))
        plt.axvline(separate_first - .5, color='gray')
        plt.axhline(l - .5 - separate_first, color='gray')

    # Add color legend on the right side of the plot
    if color_min < color_max:
        ax = plt.subplot(plot_grid[:,
                                   -1])  # Use the rightmost column of the plot
        #ax.axis('off')
        plt.box(on=None)
        col_x = [0] * len(palette)  # Fixed x coordinate for the bars
        bar_y = np.linspace(
            color_min, color_max,
            n_colors)  # y coordinates for each of the n_colors bars
        bar_height = bar_y[1] - bar_y[0]
        print(bar_height)
        ax.barh(
            y=bar_y,
            width=[15] * len(palette),  # Make bars 5 units wide
            left=col_x,  # Make bars start at 0
            height=bar_height,
            color=palette,
            linewidth=0)
        ax.set_ylim(-2, 2)
        ax.set_xlim(
            0, 5
        )  # Bars are going from 0 to 5, so lets crop the plot somewhere in the middle
        ax.grid(False)  # Hide grid
        ax.set_facecolor('white')  # Make background white
        ax.set_xticks([])  # Remove horizontal ticks
        ax.set_yticks(
            np.linspace(min(bar_y), max(bar_y),
                        3))  # Show vertical ticks for min, middle and max
        ax.yaxis.tick_right()  # Show vertical ticks on the right
    plt.sca(plt.subplot(plot_grid[:, :-1]))
示例#12
0
def make_combined_field_analysis_figures(prm, spatial_firing):
    print('I will make the combined images for field analysis results now.')
    save_path = prm.get_output_path() + '/Figures/field_analysis'
    if os.path.exists(save_path) is False:
        os.makedirs(save_path)
    plt.close('all')
    figures_path = prm.get_output_path() + '/Figures/'
    for cluster in range(len(spatial_firing)):
        cluster = spatial_firing.cluster_id.values[cluster] - 1
        spike_scatter_path = figures_path + 'firing_scatters/' + spatial_firing.session_id[cluster] + '_' + str(cluster + 1) + '_spikes_on_trajectory.png'
        rate_map_path = figures_path + 'rate_maps/' + spatial_firing.session_id[cluster] + '_rate_map_' + str(cluster + 1) + '.png'
        head_direction_polar_path = figures_path + 'head_direction_plots_polar/' + spatial_firing.session_id[cluster] + '_hd_polar_' + str(cluster + 1) + '.png'
        head_direction_map_path = figures_path + 'head_direction_plots_2d/' + spatial_firing.session_id[cluster] + '_hd_map_' + str(cluster + 1) + '.png'
        firing_fields_rate_map_path = figures_path + 'firing_field_plots/' + spatial_firing.session_id[cluster] + '_firing_fields_rate_map' + str(cluster + 1) + '.png'
        firing_fields_coloured_spikes_path = figures_path + 'firing_fields_coloured_spikes/' + spatial_firing.session_id[cluster] + '_firing_fields_coloured_spikes' + str(cluster + 1) + '.png'
        firing_field_path = figures_path + 'firing_field_plots/' + spatial_firing.session_id[cluster] + '_cluster_' + str(cluster + 1) + '_firing_field_'
        firing_field_path_first = prm.get_output_path() + '/first_half/Figures/firing_field_plots/' + spatial_firing.session_id[cluster] + '_cluster_' + str(cluster + 1) + '_firing_field_'
        firing_field_path_second = prm.get_output_path() + '/second_half/Figures/firing_field_plots/' + spatial_firing.session_id[cluster] + '_cluster_' + str(cluster + 1) + '_firing_field_'

        number_of_firing_fields = 0
        if 'firing_fields' in spatial_firing:
            number_of_firing_fields = len(spatial_firing.firing_fields[cluster])
            if number_of_firing_fields == 0:
                continue
        number_of_rows = 4
        number_of_columns = 5
        if number_of_firing_fields > 5:
            number_of_columns = number_of_firing_fields
        grid = plt.GridSpec(number_of_rows, number_of_columns, wspace=0.2, hspace=0.2)
        rounded_r = [ '%.4f' % elem for elem in spatial_firing.field_corr_r[cluster]]
        rounded_p = [ '%.4f' % elem for elem in spatial_firing.field_corr_p[cluster]]
        plt.suptitle("r: " + str(rounded_r) + '\np: ' + str(rounded_p))
        if os.path.exists(spike_scatter_path):
            spike_scatter = mpimg.imread(spike_scatter_path)
            spike_scatter_plot = plt.subplot(grid[0, 0])
            spike_scatter_plot.axis('off')
            spike_scatter_plot.imshow(spike_scatter)
        if os.path.exists(head_direction_polar_path):
            polar_hd = mpimg.imread(head_direction_polar_path)
            polar_hd_plot = plt.subplot(grid[0, 1])
            polar_hd_plot.axis('off')
            polar_hd_plot.imshow(polar_hd)
        if os.path.exists(head_direction_map_path):
            hd_map = mpimg.imread(head_direction_map_path)
            hd_map_plot = plt.subplot(grid[0, 2])
            hd_map_plot.axis('off')
            hd_map_plot.imshow(hd_map)
        if os.path.exists(firing_fields_rate_map_path):
            firing_fields = mpimg.imread(firing_fields_rate_map_path)
            firing_fields_plot = plt.subplot(grid[0, 3])
            firing_fields_plot.axis('off')
            firing_fields_plot.imshow(firing_fields)
        if os.path.exists(firing_fields_coloured_spikes_path):
            firing_fields = mpimg.imread(firing_fields_coloured_spikes_path)
            firing_fields_plot = plt.subplot(grid[0, 4])
            firing_fields_plot.axis('off')
            firing_fields_plot.imshow(firing_fields)

        for field in range(number_of_firing_fields):
            path = firing_field_path + str(field + 1) + '.png'
            firing_field_polar = mpimg.imread(path)
            row = 1
            col = field
            firing_fields_polar_plot = plt.subplot(grid[row, col])
            firing_fields_polar_plot.axis('off')
            firing_fields_polar_plot.imshow(firing_field_polar)

        for field in range(number_of_firing_fields):
            path = firing_field_path_first + str(field + 1) + '.png'
            firing_field_polar = mpimg.imread(path)
            row = 2
            col = field
            firing_fields_polar_plot = plt.subplot(grid[row, col])
            firing_fields_polar_plot.axis('off')
            firing_fields_polar_plot.imshow(firing_field_polar)

        for field in range(number_of_firing_fields):
            path = firing_field_path_second + str(field + 1) + '.png'
            firing_field_polar = mpimg.imread(path)
            row = 3
            col = field
            firing_fields_polar_plot = plt.subplot(grid[row, col])
            firing_fields_polar_plot.axis('off')
            firing_fields_polar_plot.imshow(firing_field_polar)

        plt.savefig(save_path + '/' + spatial_firing.session_id[cluster] + '_' + str(cluster + 1) + '.png', dpi=1000)
        # plt.savefig(save_path + '/' + spatial_firing.session_id[cluster] + '_' + str(cluster + 1) + '.pdf', dpi=1000)
        plt.close()
示例#13
0
def make_combined_figure(prm, spatial_firing):
    print('I will make the combined images now.')
    save_path = prm.get_output_path() + '/Figures/combined'
    if os.path.exists(save_path) is False:
        os.makedirs(save_path)
    plt.close('all')
    figures_path = prm.get_output_path() + '/Figures/'
    for cluster in range(len(spatial_firing)):
        cluster = spatial_firing.cluster_id.values[cluster] - 1
        coverage_path = figures_path + 'session/heatmap.png'
        spike_scatter_path = figures_path + 'firing_scatters/' + spatial_firing.session_id[cluster] + '_' + str(cluster + 1) + '_spikes_on_trajectory.png'
        rate_map_path = figures_path + 'rate_maps/' + spatial_firing.session_id[cluster] + '_rate_map_' + str(cluster + 1) + '.png'
        head_direction_polar_path = figures_path + 'head_direction_plots_polar/' + spatial_firing.session_id[cluster] + '_hd_polar_' + str(cluster + 1) + '.png'
        head_direction_map_path = figures_path + 'head_direction_plots_2d/' + spatial_firing.session_id[cluster] + '_hd_map_' + str(cluster + 1) + '.png'
        firing_fields_rate_map_path = figures_path + 'firing_field_plots/' + spatial_firing.session_id[cluster] + '_firing_fields_rate_map' + str(cluster + 1) + '.png'
        spike_histogram_path = figures_path + 'firing_properties/' + spatial_firing.session_id[cluster] + '_' + str(cluster + 1) + '_spike_histogram.png'
        speed_histogram_path = figures_path + 'firing_properties/' + spatial_firing.session_id[cluster] + '_' + str(cluster + 1) + '_speed_histogram.png'
        firing_field_path = figures_path + 'firing_field_plots/' + spatial_firing.session_id[cluster] + '_cluster_' + str(cluster + 1) + '_firing_field_'
        autocorrelograms = figures_path + 'firing_properties/' + spatial_firing.session_id[cluster] + '_' + str(cluster + 1) + '_autocorrelograms.png'
        waveforms_path = figures_path + 'firing_properties/' + spatial_firing.session_id[cluster] + '_' + str(cluster + 1) + '_waveforms.png'
        rate_map_autocorrelogram_path = figures_path + 'rate_map_autocorrelogram/' + spatial_firing.session_id[cluster] + '_rate_map_autocorrelogram_' + str(cluster + 1) + '.png'
        speed_vs_firing_rate_path = figures_path + 'firing_properties/' + spatial_firing.session_id[cluster] + '_' + str(cluster + 1) + '_speed_vs_firing_rate.png'

        number_of_firing_fields = 0
        if 'firing_fields' in spatial_firing:
            number_of_firing_fields = len(spatial_firing.firing_fields[cluster])
        number_of_rows = math.ceil((number_of_firing_fields + 1)/6) + 2

        grid = plt.GridSpec(number_of_rows, 5, wspace=0.025, hspace=0.05)
        if os.path.exists(waveforms_path):
            waveforms = mpimg.imread(waveforms_path)
            waveforms_plot = plt.subplot(grid[0, 0])
            waveforms_plot.axis('off')
            waveforms_plot.imshow(waveforms)
        if os.path.exists(spike_histogram_path):
            spike_hist = mpimg.imread(spike_histogram_path)
            spike_hist_plot = plt.subplot(grid[0, 2])
            spike_hist_plot.axis('off')
            spike_hist_plot.imshow(spike_hist)
        if os.path.exists(autocorrelograms):
            autocorrelogram_10 = mpimg.imread(autocorrelograms)
            autocorrelogram_10_plot = plt.subplot(grid[0, 1])
            autocorrelogram_10_plot.axis('off')
            autocorrelogram_10_plot.imshow(autocorrelogram_10)
        if os.path.exists(speed_vs_firing_rate_path):
            speed_vs_rate = mpimg.imread(speed_vs_firing_rate_path)
            speed_vs_rate_plot = plt.subplot(grid[0, 3])
            speed_vs_rate_plot.axis('off')
            speed_vs_rate_plot.imshow(speed_vs_rate)
        if os.path.exists(coverage_path):
            coverage = mpimg.imread(coverage_path)
            coverage_plot = plt.subplot(grid[0, 4])
            coverage_plot.axis('off')
            coverage_plot.imshow(coverage)
        if os.path.exists(spike_scatter_path):
            spike_scatter = mpimg.imread(spike_scatter_path)
            spike_scatter_plot = plt.subplot(grid[1, 0])
            spike_scatter_plot.axis('off')
            spike_scatter_plot.imshow(spike_scatter)
        if os.path.exists(rate_map_path):
            rate_map = mpimg.imread(rate_map_path)
            rate_map_plot = plt.subplot(grid[1, 1])
            rate_map_plot.axis('off')
            rate_map_plot.imshow(rate_map)
        if os.path.exists(rate_map_autocorrelogram_path):
            rate_map_autocorr = mpimg.imread(rate_map_autocorrelogram_path)
            rate_map_autocorr_plot = plt.subplot(grid[1, 2])
            rate_map_autocorr_plot.axis('off')
            rate_map_autocorr_plot.imshow(rate_map_autocorr)
        if os.path.exists(head_direction_polar_path):
            polar_hd = mpimg.imread(head_direction_polar_path)
            polar_hd_plot = plt.subplot(grid[1, 3])
            polar_hd_plot.axis('off')
            polar_hd_plot.imshow(polar_hd)
        if os.path.exists(head_direction_map_path):
            hd_map = mpimg.imread(head_direction_map_path)
            hd_map_plot = plt.subplot(grid[1, 4])
            hd_map_plot.axis('off')
            hd_map_plot.imshow(hd_map)
        if os.path.exists(firing_fields_rate_map_path):
            firing_fields = mpimg.imread(firing_fields_rate_map_path)
            firing_fields_plot = plt.subplot(grid[2, 0])
            firing_fields_plot.axis('off')
            firing_fields_plot.imshow(firing_fields)
        for field in range(number_of_firing_fields):
            path = firing_field_path + str(field + 1) + '.png'
            firing_field_polar = mpimg.imread(path)
            row = math.floor((field+1)/5) + 2
            col = (field+1) % 5
            firing_fields_polar_plot = plt.subplot(grid[row, col])
            firing_fields_polar_plot.axis('off')
            firing_fields_polar_plot.imshow(firing_field_polar)

        plt.savefig(save_path + '/' + spatial_firing.session_id[cluster] + '_' + str(cluster + 1) + '.png', dpi=1000)
        # plt.savefig(save_path + '/' + spatial_firing.session_id[cluster] + '_' + str(cluster + 1) + '.pdf')
        plt.close()
def dynamic_heatmap(df, columns, fontsize=20, annot=False, palette=None, figsize=(15, 10), squaresize=500):
    """Plots a heatmap that changes size values depending on correlation Adapted from:
    https://towardsdatascience.com/better-heatmaps-and-correlation-matrix-plots-in-python-41445d0f2bec"""

    plt.figure(figsize=figsize)
    corr = df[columns].corr()
    sns.set(style="dark")
    grid_bg_color = sns.axes_style()['axes.facecolor']

    # Generate a mask for the upper triangle
    mask = np.zeros_like(corr, dtype=np.bool)
    mask[np.triu_indices_from(mask)] = True

    corr = pd.melt(corr.reset_index(),
                   id_vars='index')  # Unpivot the dataframe, so we can get pair of arrays for x and y
    corr.columns = ['x', 'y', 'value']

    x = corr['x']
    y = corr['y']
    size = corr['value'].abs()

    # Set up the matplotlib figure
    f, ax = plt.subplots(figsize=figsize)
    ax.set_xticklabels(
        ax.get_xticklabels(),
        rotation=45,
        horizontalalignment='right');

    # Mapping from column names to integer coordinates
    x_labels = [v for v in sorted(x.unique())]
    y_labels = [v for v in sorted(y.unique())]
    x_to_num = {p[1]: p[0] for p in enumerate(x_labels)}
    y_to_num = {p[1]: p[0] for p in enumerate(y_labels)}

    size_scale = squaresize

    if palette:
        n_colors = len(palette)
    else:
        n_colors = 256  # Use 256 colors for the diverging color palette
        palette = sns.diverging_palette(20, 220, n=n_colors) # Create the palette
    color_min, color_max = [-1,
                            1]  # Range of values that will be mapped to the palette, i.e. min and max possible correlation
    color = corr["value"]

    def value_to_color(val):
        val_position = float((val - color_min)) / (
                    color_max - color_min)  # position of value in the input range, relative to the length of the input range
        ind = int(val_position * (n_colors - 1))  # target index in the color palette
        return palette[ind]

    plot_grid = plt.GridSpec(1, 15, hspace=0.2, wspace=0.1)  # Setup a 1x15 grid
    ax = plt.subplot(plot_grid[:, :-1])  # Use the leftmost 14 columns of the grid for the main plot

    ax.scatter(
        x=x.map(x_to_num),  # Use mapping for x
        y=y.map(y_to_num),  # Use mapping for y
        s=size * size_scale,  # Vector of square sizes, proportional to size parameter
        c=color.apply(value_to_color),  # Vector of square colors, mapped to color palette
        marker='s'  # Use square as scatterplot marker
    )

    # Show column labels on the axes
    ax.set_xticks([x_to_num[v] for v in x_labels])
    ax.set_xticklabels(x_labels, rotation=45, horizontalalignment='right')
    ax.set_yticks([y_to_num[v] for v in y_labels])
    ax.set_yticklabels(y_labels)
    #     ax.set_fontsize(font_scale)
    for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
                 ax.get_xticklabels() + ax.get_yticklabels()):
        item.set_fontsize(fontsize)

    numbers = corr['value'].round(decimals=2)

    if annot:
        for i, txt in enumerate(numbers):
            annot_font_size = int(fontsize * size[i] * annot)
            ax.annotate(txt, (x.map(x_to_num)[i], y.map(x_to_num)[i]),
                        horizontalalignment="center", verticalalignment="center",
                        color=grid_bg_color, fontweight="black", fontsize=annot_font_size)

    ax.grid(False, 'major')
    ax.grid(True, 'minor')
    ax.set_xticks([t + 0.5 for t in ax.get_xticks()], minor=True)
    ax.set_yticks([t + 0.5 for t in ax.get_yticks()], minor=True)
    ax.set_xlim([-0.5, max([v for v in x_to_num.values()]) + 0.5])
    ax.set_ylim([-0.5, max([v for v in y_to_num.values()]) + 0.5])

    # Add color legend on the right side of the plot
    ax = plt.subplot(plot_grid[:, -1])  # Use the rightmost column of the plot

    col_x = [0] * len(palette)  # Fixed x coordinate for the bars
    bar_y = np.linspace(color_min, color_max, n_colors)  # y coordinates for each of the n_colors bars

    bar_height = bar_y[1] - bar_y[0]
    ax.barh(
        y=bar_y,
        width=[5] * len(palette),  # Make bars 5 units wide
        left=col_x,  # Make bars start at 0
        height=bar_height,
        color=palette,
        linewidth=0
    )
    ax.set_xlim(1, 2)  # Bars are going from 0 to 5, so lets crop the plot somewhere in the middle
    ax.grid(False)  # Hide grid
    ax.set_xticks([])  # Remove horizontal ticks
    ax.set_yticks(np.linspace(min(bar_y), max(bar_y), 3))  # Show vertical ticks for min, middle and max
    ax.yaxis.tick_right()  # Show vertical ticks on the right
    plt.show()
示例#15
0
    scenes_spec = []
    for _ in range(N):
        scene_obs = {}
        for obj in objects:
            scene_obs[obj] = obj
        scenes_spec += [scene_obs]

    world.create_scenes(scenes_spec)

    def gridnum(i, ncols):
        return i // ncols, i % ncols

    plt.ion()
    fig = plt.figure(figsize=(10, 5))
    spec = plt.GridSpec(ncols=N // 2, nrows=2, figure=fig)
    ax = [fig.add_subplot(spec[gridnum(i, ncols=N // 2)]) for i in range(N)]
    plt.tight_layout()

    for b in range(50):

        transforms = []
        for _ in range(N):
            model_matrices = []
            for _ in objects:
                xy = torch.rand(2) * 128 - 64
                model_matrices += [Translate(x=xy[0], y=xy[1], z=0)]
            transforms += [model_matrices]

        distance = 30
        elevation = 0.0
示例#16
0
    xtickslabels = np.arange(-m / 2, m / 2 + 1, 2)
    yticks = np.arange(-n / 2 + 0.5, n / 2 + 1, 2)
    ytickslabels = np.arange(-n / 2, n / 2 + 1, 2)
else:
    n = e.shape[0]
    m = e.shape[1]
    xticks = np.arange(-m / 2 + 0.5, m / 2 + 1, 2)
    xtickslabels = np.arange(-m / 2 + 1, m / 2 + 1, 2)
    yticks = np.arange(-n / 2 + 0.5, n / 2 + 1, 2)
    ytickslabels = np.arange(-n / 2 + 1, n / 2 + 1, 2)
extent = [-n / 2, n / 2, -m / 2, m / 2]

np.save('e_field_fourier_nonoise_tfd.npy', e)

# defining the grid of the plot
gs = plt.GridSpec(4, 6, wspace=0.4, hspace=0.4)
fig = plt.figure(figsize=(18, 12))

fig.add_subplot(gs[:2, :2])
plt.imshow(e.real,
           aspect='equal',
           extent=extent,
           interpolation='nearest',
           origin='lower',
           cmap='viridis')
plt.title(r'Simulated $\tilde{E}(\tau,f_D)$')
ax = plt.gca()
ax.set_xticks(xticks)
ax.set_xticklabels(xtickslabels)
ax.set_yticks(yticks)
ax.set_yticklabels(ytickslabels)
示例#17
0
sns.set_style("darkgrid")
sns.set_context("paper")
fs = 14  # fontsize
si = 141
lw = 2  # linewidth

sp1 = 6
sp2 = 25

color1 = 'k'
color2 = 'red'
color3 = 'k'
#%% start figure
fig = plt.figure(figsize=(19, 9))
grid = plt.GridSpec(2, 24, wspace=0., hspace=0.2)
#% subplot (a)
ax = plt.subplot(
    grid[0, :12],
    projection=projection)  #plt.subplot(2,2,1, projection=projection)
plt.title('(a) $R_{0.1}$, eddying', fontsize=fs)

g = ax.gridlines(crs=ccrs.PlateCarree(),
                 draw_labels=True,
                 linewidth=1,
                 color='gray',
                 alpha=0.5,
                 linestyle='--')
g.xlocator = mticker.FixedLocator([-180, -90, -0, 90, 180])
g.xlabels_top = False
g.ylabels_right = False
示例#18
0
    idxlon = np.logical_and(Lons >= maxminlon, Lons <= minmaxlon)
    assert (idxlon == True).all()
    avgd = np.flip(avgd[idxlat], 0)
    #    land = np.full(avgd.shape, np.nan); land[avgd==0] = 1;
    avgd[avgd == 0] = np.nan
    avd50gm[j] = mean_latitudeweigthed(avgd, Lats) / 100.

avgd50, surf50, Lons, Lats = calc_fields(
    name=
    '/Volumes/HardDisk/POP/output/highres/timeseries/timeseries_per_location_ddeg1_sp25_dd10_tempresmonmean.nc'
)
avgd50mean = mean_latitudeweigthed(avgd50, Lats) / 100.

#%% start figure
fig = plt.figure(figsize=(19, 15))
grid = plt.GridSpec(3, 24, wspace=0., hspace=0.4)
#% Subplot (a) highres
ax0 = plt.subplot(
    grid[0, :12],
    projection=projection)  #plt.subplot(2,2,1, projection=projection)
plt.title('(a)$R_{0.1}$', fontsize=fs)
g = ax0.gridlines(crs=ccrs.PlateCarree(),
                  draw_labels=True,
                  linewidth=1,
                  color='gray',
                  alpha=0.5,
                  linestyle='--')
g.xlabels_top = False
g.ylabels_right = False
g.xlabels_bottom = False
g.xlabel_style = {'fontsize': fs}
示例#19
0
def jointplot(X,
              Y,
              xlabel=None,
              ylabel=None,
              binsim=40,
              binsh=20,
              contour=True):
    """
Plots the joint distribution of posteriors for X1 and X2, including the 1D
histograms showing the median and standard deviations.

The work that went in creating this nice method is shown, step by step, in 
the ipython notebook "error contours.ipynb". Sources of inspiration:

- http://python4mpia.github.io/intro/quick-tour.html
- http://stackoverflow.com/questions/12301071/multidimensional-confidence-intervals

Usage:

>>> jointplot(M.rtr.trace(),M.mdot.trace(),xlabel='$\log \ r_{\\rm tr}$', ylabel='$\log \ \dot{m}$')

gives the following plot.

.. figure:: ../figures/jointplot.png
   :scale: 100 %
   :alt: Two-dimensional kernel density distribution.

   Two-dimensional kernel density distribution, along with one-dimensional histograms of each distribution.
	"""
    import scipy.stats

    # Generates 2D histogram for image
    histt, xt, yt = numpy.histogram2d(X,
                                      Y,
                                      bins=[binsim, binsim],
                                      normed=False)
    histt = numpy.transpose(
        histt)  # Beware: numpy switches axes, so switch back.

    # assigns correct proportions to subplots
    fig = pylab.figure()
    gs = pylab.GridSpec(2,
                        2,
                        width_ratios=[3, 1],
                        height_ratios=[1, 3],
                        wspace=0.001,
                        hspace=0.001)
    con = pylab.subplot(gs[2])
    histx = pylab.subplot(gs[0], sharex=con)
    histy = pylab.subplot(gs[3], sharey=con)

    # Image
    con.imshow(histt,
               extent=[xt[0], xt[-1], yt[0], yt[-1]],
               origin='lower',
               cmap=pylab.cm.gray_r,
               aspect='auto')

    # Overplot with error contours 1,2 sigma
    if contour == True:
        pdf = scipy.stats.gaussian_kde([X, Y])
        x, y = pylab.meshgrid(xt, yt)
        z = numpy.array(pdf.evaluate([x.flatten(),
                                      y.flatten()])).reshape(x.shape)
        # the [61,15] values were obtained by trial and error until the joint confidence
        # contours matched the confidence intervals from the individual X,Y
        s = scipy.stats.scoreatpercentile(pdf(pdf.resample(1000)), [61, 15])
        cs = con.contour(x,
                         y,
                         z,
                         levels=s,
                         extent=[x[0], x[-1], y[0], y[-1]],
                         linestyles=['-', '-', '-'],
                         colors=['black', 'blue'])
        # use dictionary in order to assign your own labels to the contours.
        #fmtdict = {s[0]:r'$1\sigma$',s[1]:r'$2\sigma$'}
        #con.clabel(cs, fmt=fmtdict, inline=True, fontsize=20)
        if xlabel != None: con.set_xlabel(xlabel)
        if ylabel != None: con.set_ylabel(ylabel)

    # X-axis histogram
    histx.hist(X, binsh, histtype='stepfilled', facecolor='lightblue')
    pylab.setp(histx.get_xticklabels(), visible=False)  # no X label
    pylab.setp(histx.get_yticklabels(), visible=False)  # no Y label
    # Vertical lines with median and 1sigma confidence
    yax = histx.set_ylim()
    histx.plot([numpy.median(X), numpy.median(X)], [yax[0], yax[1]],
               'k-',
               linewidth=2)  # median
    xsd = scipy.stats.scoreatpercentile(X, [15.87, 84.13])
    histx.plot([xsd[0], xsd[0]], [yax[0], yax[1]], 'k--')  # -1sd
    histx.plot([xsd[-1], xsd[-1]], [yax[0], yax[1]], 'k--')  # +1sd

    # Y-axis histogram
    histy.hist(Y,
               binsh,
               histtype='stepfilled',
               orientation='horizontal',
               facecolor='lightyellow')
    pylab.setp(histy.get_yticklabels(), visible=False)  # no Y label
    pylab.setp(histy.get_xticklabels(), visible=False)  # no X label
    # Vertical lines with median and 1sigma confidence
    xax = histy.set_xlim()
    histy.plot([xax[0], xax[1]],
               [numpy.median(Y), numpy.median(Y)],
               'k-',
               linewidth=2)  # median
    ysd = scipy.stats.scoreatpercentile(Y, [15.87, 84.13])
    histy.plot([xax[0], xax[1]], [ysd[0], ysd[0]], 'k--')  # -1sd
    histy.plot([xax[0], xax[1]], [ysd[-1], ysd[-1]], 'k--')  # +1sd
示例#20
0
def gsea_plot(rank_metric, enrich_term, hit_ind, nes, pval, fdr, RES,
              phenoPos=None, phenoNeg=None, figsize =(6.5,6), **kwarg):
    """This is the main function for reproducing the gsea plot.

    :param rank_metric: rankings, rank_metric['rank'].values.
    :param enrich_term: gene_set name
    :param hit_ind: hit indexs of rank_metric['gene_name'] presented in gene set S.
    :param nes: Normalized enrichment scores.
    :param pval: nominal p-value.
    :param fdr: false discoveray rate.
    :param RES: ranking enrichment scores of all genes in rank_metric['gene_name'].
    :param phenoPos: phenotype lable, positive correlated.
    :param phenoNeg: phenotype lable, negative correlated.
    :param figsize: matplotlib figsize.
    :return: fig object of gsea plot.
    """
    #plt.style.use('classic')
    # center color map at midpoint = 0
    norm = _MidpointNormalize(midpoint=0)

    #dataFrame of ranked matrix scores
    x = rank_metric.index.values
    #figsize = (6,6)
    phenoP_label = phenoPos + ' (Positively Correlated)'
    phenoN_label = phenoNeg + ' (Negatively Correlated)'
    zero_score_ind = np.abs(rank_metric['rank']).argmin()
    z_score_label = 'Zero score at ' + str(zero_score_ind)
    nes_label = 'NES: '+ "{:.3f}".format(float(nes))
    pval_label = 'Pval: '+ "{:.3f}".format(float(pval))
    fdr_label = 'FDR: '+ "{:.3f}".format(float(fdr))
    #im_matrix = rank_metric.ix[:,1:].T
    im_matrix = rank_metric.iloc[:,1:].T

    #in most case, we will have mangy plots, so do not display plots
    #It's also convinient to run this script on command line.
    plt.ioff()
    #GSEA Plots
    gs = plt.GridSpec(16,1)
    fig = plt.figure(figsize=figsize)
    #Ranked Metric Scores Plot
    ax1 =  fig.add_subplot(gs[11:])
    ax1.fill_between(x, y1= rank_metric['rank'], y2=0, color='#C9D3DB')
    ax1.set_ylabel("Ranked list metric",fontsize=14)
    ax1.text(.05, .9, phenoP_label, color='red', horizontalalignment='left', verticalalignment='top',
         transform=ax1.transAxes)
    ax1.text(.95, .05, phenoN_label, color='Blue', horizontalalignment='right', verticalalignment='bottom',
         transform=ax1.transAxes)

    # the x coords of this transformation are data, and the y coord are axes
    trans1 = transforms.blended_transform_factory(ax1.transData, ax1.transAxes)
    ax1.vlines(zero_score_ind, 0, 1, linewidth=.5, transform=trans1, linestyles='--', color='grey')
    ax1.text(zero_score_ind, 0.5, z_score_label, horizontalalignment='center', verticalalignment='center',
             transform=trans1)
    ax1.set_xlabel("Rank in Ordered Dataset", fontsize=14)
    ax1.spines['top'].set_visible(False)
    ax1.tick_params(axis='both', which='both', top='off', right='off', left='off')
    ax1.locator_params(axis='y', nbins=5)
    ax1.yaxis.set_major_formatter(plt.FuncFormatter(lambda tick_loc,tick_num :  '{:.1f}'.format(tick_loc) ))

    # use round method to control float number
    #ax1.yaxis.set_major_formatter(plt.FuncFormatter(lambda tick_loc,tick_num :  round(tick_loc, 1) ))

    #gene hits
    ax2 = fig.add_subplot(gs[8:10], sharex=ax1)

    # the x coords of this transformation are data, and the y coord are axes
    trans2 = transforms.blended_transform_factory(ax2.transData, ax2.transAxes)
    ax2.vlines(hit_ind, 0, 1,linewidth=.5,transform=trans2)
    ax2.spines['bottom'].set_visible(False)
    ax2.tick_params(axis='both', which='both', bottom='off', top='off',
                    labelbottom='off', right='off', left='off',labelleft='off')
    #colormap
    ax3 =  fig.add_subplot(gs[10],sharex=ax1)
    ax3.imshow(im_matrix, aspect='auto', norm=norm, cmap=plt.cm.seismic, interpolation='none') # cm.coolwarm
    ax3.spines['bottom'].set_visible(False)
    ax3.tick_params(axis='both', which='both', bottom='off', top='off',
                    labelbottom='off', right='off', left='off',labelleft='off')

    # Enrichment score plot
    ax4 = fig.add_subplot(gs[:8],sharex=ax1)
    ax4.plot(x,RES,linewidth=4,color ='#88C544')
    ax4.text(.1, .1, fdr_label, transform=ax4.transAxes)
    ax4.text(.1, .2, pval_label, transform=ax4.transAxes)
    ax4.text(.1, .3, nes_label, transform=ax4.transAxes)

    # the y coords of this transformation are data, and the x coord are axes
    trans4 = transforms.blended_transform_factory(ax4.transAxes, ax4.transData)
    ax4.hlines(0, 0, 1, linewidth=.5, transform=trans4, color='grey')
    ax4.set_ylabel("Enrichment score (ES)", fontsize=14)
    ax4.set_xlim(min(x), max(x))
    ax4.tick_params(axis='both', which='both', bottom='off', top='off', labelbottom='off', right='off')
    ax4.locator_params(axis='y', nbins=5)
    # FuncFormatter need two argment, I don't know why. this lambda function used to format yaxis tick labels.
    ax4.yaxis.set_major_formatter(plt.FuncFormatter(lambda tick_loc,tick_num :  '{:.1f}'.format(tick_loc)) )

    #fig adjustment
    fig.suptitle(enrich_term, fontsize=16)
    fig.subplots_adjust(hspace=0)
    #fig.tight_layout()
    plt.close(fig)

    return fig