예제 #1
0
def plot_label_heatmap(samples, bars_y = 30):
    angles = np.linspace(0., np.pi, len(samples[0]['y']))
    min_x = np.amin(angles)
    max_x = np.amax(angles)
    radii = np.zeros((len(samples), len(angles)))
    for i, s in enumerate(samples):
        radii[i] = s['y']
    min_y = np.amin(radii)
    max_y = np.amax(radii)
    heatmap_array = np.zeros((bars_y, len(angles)))
    for i in xrange(np.shape(radii)[0]):
        for j in xrange(np.shape(radii)[1]):
            dest_j = j
            dest_i = round((radii[i,j] - min_y) / (max_y - min_y) * bars_y)-1
            heatmap_array[dest_i, dest_j] += 1
    indices = np.linspace(min_y, max_y, bars_y)
    indices = ["%.1f" % i for i in indices]
    columns = np.linspace(0., 180., len(angles))
    columns = ["%.1f" % i for i in columns]
    heatmap_array = np.flipud(heatmap_array)
    heatmap_frame = pandas.DataFrame(data=heatmap_array, index=reversed(indices), columns=columns)
    f = sns.heatmap(heatmap_frame)
    plt.subplots_adjust(top=0.9)
    plt.title("Labels Heatmap")
    sns.axlabel("Angle", "Radius")
    sns.plt.show(f)
    def plot_kmeans_components(self, fig1, gs, kmeans_clusters, clrs, plot_title='Hb', num_subplots=1,
                               flag_separate=1, gridspecs=[0, 0]):
        with sns.axes_style('darkgrid'):
            if flag_separate:
                ax1 = fig1.add_subplot(2, 1, num_subplots)
            else:
                ax1 = eval('fig1.add_subplot(gs' + gridspecs + ')')

            plt.gca().set_color_cycle(clrs)
            for ii in xrange(0, size(kmeans_clusters, 1)):
                plt.plot(kmeans_clusters[:, ii], lw=4, label=str(ii))

            plt.locator_params(axis='y', nbins=4)
            sns.axlabel("Time (seconds)", "a.u")
            ax1.legend(prop={'size': 14}, loc='center left', bbox_to_anchor=(1, 0.5), ncol=1, fancybox=True,
                       shadow=True)

            plt.title(plot_title, fontsize=14)

            plt.ylim((min(kmeans_clusters) - 0.0001,
                      max(kmeans_clusters) + 0.0001))
            plt.xlim((0, size(kmeans_clusters, 0)))
            plt.axhline(y=0, linestyle='-', color='k', linewidth=1)
            self.plot_vertical_lines_onset()
            self.plot_vertical_lines_offset()
    def plot_joint(self, cmap="BuGn"):
        """Plot the current joint distribution P(p, I)."""
        pal = sns.color_palette(cmap, 256)
        lc = pal[int(.7 * 256)]
        bg = pal[0]
        
        fig = plt.figure(figsize=(7, 7))
        gs = plt.GridSpec(6, 6)
        
        p_lim = self.p_grid.min(), self.p_grid.max()
        I_lim = self.I_grid.min(), self.I_grid.max()
     
        ax1 = fig.add_subplot(gs[1:, :-1])
        ax1.set(xlim=p_lim, ylim=I_lim)

        ax1.contourf(self.p_grid, self.I_grid, self.pI.T, 30, cmap=cmap)

        sns.axlabel("$p$", "$I$", size=16)

        ax2 = fig.add_subplot(gs[1:, -1], axis_bgcolor=bg)
        ax2.set(ylim=I_lim)
        ax2.plot(self.pI.sum(axis=0), self.I_grid, c=lc, lw=3)
        ax2.set_xticks([])
        ax2.set_yticks([])

        ax3 = fig.add_subplot(gs[0, :-1], axis_bgcolor=bg)
        ax3.set(xlim=p_lim)
        ax3.plot(self.p_grid, self.pI.sum(axis=1), c=lc, lw=3)
        ax3.set_xticks([])
        ax3.set_yticks([])
def plot_scores(matched_signals, unique_clrs, ind, stimulus_on_time, stimulus_off_time):
######Plot mean signals according to color and boxplot of number of pixels in each plane
    sns.tsplot(np.array(matched_signals[ind].clr_grped_signal), linewidth=3, ci=95, err_style="ci_band", color=unique_clrs[ind])  
    plt.locator_params(axis = 'y', nbins = 4)            
    sns.axlabel("Time (seconds)","a.u")            
    plot_vertical_lines_onset(stimulus_on_time)
    plot_vertical_lines_offset(stimulus_off_time)
    plt.axhline(y=0, linestyle='-', color='k', linewidth=1)
예제 #5
0
def plot_prediction_error(name, clf, X, y):
    plt.figure()
    cv = KFold(X.shape[0], 5, shuffle=True)
    predicted = cross_val_predict(clf, X, y, cv=cv)
    print("%.3f = mean squared error" % mean_squared_error(y, predicted))
    sns.regplot(x=y[:1000], y=predicted[:1000])
    sns.axlabel("actual", "predicted")
    plt.savefig("plot_validation_" + name + ".png")
예제 #6
0
def tshist(ax,X,Y):
  B=25
  assert(X.size==Y.shape[1])
  img=np.zeros((B,X.size)) 
  for t in range(X.size):
    hc,be=np.histogram(Y[:,t],bins=B,range=(-1,1))
    img[::-1,t]=hc.astype(np.float)/Y.shape[0]
  sns.heatmap(img,ax=ax,cmap='gray')
  sns.axlabel('X','A')
예제 #7
0
def grafico_l2(conjunto, xl=None, yl=None, titulox="", tituloy="", titulo="", filename="", tamanho=5):
    a = np.array(conjunto[0].map(_dic_cruzes))
    b = np.array(conjunto[1].map(_dic_cruzes))
    c = DataFrame([a, b]).transpose()
    c.columns = ["A", "B"]
    sns.lmplot("A", "B", c, x_jitter=0.2, y_jitter=0.3, size=tamanho)
    plt.title(titulo, fontsize=16)
    sns.axlabel(titulox, tituloy, fontsize=fontetamanho)
    plt.savefig(filename)
예제 #8
0
def grafico_j(conjunto, xl=None, yl=None, titulox="", tituloy="", filename="", tamanho=5, titulo=""):
    a = np.array(conjunto[0].map(float))
    b = np.array(conjunto[1].map(float))
    c = DataFrame([a, b]).transpose()
    c.columns = ["A", "B"]
    g = sns.jointplot(
        "A", "B", c, xlim=xl, ylim=yl, kind="reg", stat_func=stats.spearmanr, marginal_kws={"bins": 25}, size=tamanho
    )
    # marginal_kws={"bins": 297}
    sns.axlabel(titulox, tituloy, fontsize=fontetamanho)
    plt.title(titulo, y=1.22, fontsize=20)
    plt.savefig(filename, bbox_inches="tight", format="png")
예제 #9
0
def plot_normed_intensities(normed_intensities, path=""):
    """
    Plot the normalized intensities to show that the distributions
    overlap post-normalization
    """
    for col in normed_intensities.columns:
        sns.kdeplot(np.log2(normed_intensities[col]).dropna(), label=col, shade=True)
        plt.legend(bbox_to_anchor=(1.3, 0.5), loc="center right")
    sns.despine()
    sns.axlabel("Log$_2$ Normalized Intensities", "Density")
    plt.tight_layout()
    plt.savefig(os.path.join(path, "normed_intensities_wcl.png"), dpi=300)
 def plot_scores(self, fig1, gs, matched_signals, unique_clrs, plot_title='Habenula', gridspecs='[0,0]'):
     with sns.axes_style('dark'):
         ax1 = eval('fig1.add_subplot(gs' + gridspecs + ')')
         for ind in range(0, size(unique_clrs, 0)):
             sns.tsplot(array(matched_signals[ind].clr_grped_signal), linewidth=5, ci=95, err_style="ci_band",
                        color=unique_clrs[ind])
             ax1.locator_params(axis='y', nbins=4)
             sns.axlabel("Time (seconds)", "a.u")
             plt.title(plot_title, fontsize=14)
             self.plot_vertical_lines_onset()
             self.plot_vertical_lines_offset()
             plt.axhline(y=0, linestyle='-', color='k', linewidth=1)
def plot_ica_components(ica_components_plot, colors_ica, ax1,stimulus_on_time, stimulus_off_time):
########### Plot components ##################    
    for ii in xrange(0, np.size(ica_components_plot, 1)):
        plt.plot(ica_components_plot[:,ii], color=colors_ica[ii])    
    plt.locator_params(axis = 'y', nbins = 4)
    sns.axlabel("Time (seconds)","a.u")
    
    A = []
    for ii in xrange(0,np.size(ica_components_plot, 1)):
        A = np.append(A, [str(ii+1)])
        
    ax1.legend(A, loc=4)
    plt.axhline(y=0, linestyle='-', color='k', linewidth=1)
    plot_vertical_lines_onset(stimulus_on_time)
    plot_vertical_lines_offset(stimulus_off_time)        
    def plot_matchedpixels(fig1, gs, matched_pixels, unique_clrs, gridspecs=[0, 0]):
        ax1 = eval('fig1.add_subplot(gs' + gridspecs + ')')
        with sns.axes_style("darkgrid"):
            for ii in xrange(0, size(matched_pixels, 0)):
                plt.plot(ii + 1, transpose(matched_pixels[ii, :]), 'o', color=unique_clrs[ii], markersize=10)
                plt.xlim([0, size(matched_pixels, 0) + 1])

            for ii in range(0, size(unique_clrs, 0)):
                plt.plot(repeat(ii + 1, size(matched_pixels, 1)), transpose(matched_pixels[ii, :]), 's',
                         color=unique_clrs[ii], markersize=10, markeredgecolor='k', markeredgewidth=2)

            x = range(0, size(unique_clrs, 0)+1)
            labels = [str(e) for e in x]

            plt.xticks(x, labels, rotation='vertical')
            sns.axlabel("Colors", "Number of Pixels")
            sns.despine(offset=10, trim=True)
예제 #13
0
def graph_func2(perrault):
    sns.set( font_scale=.8)
    sns.axlabel('Color', 'Frequency' )
    #colors from http://www.color-hex.com and wikipedia
    flatui = ["#4b0082","#ffd700", "#e6e6fa", "#ffff00", "#FF2400", "#ff6eb4", "#d2b48c", "#ff00ff", "#0000ff", "#C8A2C8",
              "#800080", "#FF007F", "#FD3F92", "#000000", "#dc143c", "#CCCCFF", "#ffffff", "#ff0000", "#631919", "#fffff0",
              "#ffa500","#730000", "#808000","#00ffff","#c0c0c0","#808080",  "#7fffd4", "#808080", "#008000", "#f5f5dc",
              "#329999", "#f0ffff", "#FFEF00"]
    custom_palette = sns.color_palette(flatui)
    colors = perrault[0]
    occurences = perrault[1]
    ax2 = sns.barplot(colors, occurences, palette = custom_palette)
    fig2 = ax2.get_figure()
    for item in ax2.get_xticklabels():
        item.set_rotation(45)
    sns.plt.title('Color Word Frequencies in Charles Perrault Stories')
    fig2.savefig('perrault_chart.png')
    fig2.clf()
def plot_pca_components(pca_components,ax1,stimulus_on_time, stimulus_off_time,required_pcs):
########### Plot components ##################    
    for ii in range(np.size(pca_components,1)):
        if ii in required_pcs:
            plt.plot(pca_components[:,ii],'--', linewidth=4)
        else:
            plt.plot(pca_components[:,ii])
    
    plt.locator_params(axis = 'y', nbins = 4)
    sns.axlabel("Time (seconds)","a.u")
    
    A = []
    for ii in xrange(0,np.size(pca_components, 1)):
        A = np.append(A, [str(ii)])
        
    ax1.legend(A, loc=4)
    plt.axhline(y=0, linestyle='-', color='k', linewidth=1)
    plot_vertical_lines_onset(stimulus_on_time)
    plot_vertical_lines_offset(stimulus_off_time)
def plot_boxplot(fig2, matched_pixels, unique_clrs):
#### Plot Boxplot of number of pixels
    ## Dont plot boxplot if there is only one Z
    if np.size(matched_pixels,1) == 1:
        with sns.axes_style("darkgrid"):
            for ii in xrange(0,np.size(matched_pixels,0)):
                fig2 = plt.plot(ii+1,np.transpose(matched_pixels[ii,:]),'o', color=unique_clrs[ii])
                plt.xlim([0,np.size(matched_pixels,0)+1])
    else:
        fig2 = sns.boxplot(np.transpose(matched_pixels),linewidth=3, widths=.5, color=unique_clrs)
        
    for ii in range(0,np.size(unique_clrs,0)):
        fig2 = plt.plot(np.repeat(ii+1,np.size(matched_pixels,1)), np.transpose(matched_pixels[ii,:]),'s', \
        color=unique_clrs[ii], markersize=5, markeredgecolor='k', markeredgewidth=2) 
    
    plt.locator_params(axis = 'y', nbins = 2)
    sns.axlabel("Colors", "Number of Pixels")
    sns.despine(offset=10, trim=True)
    return fig2
예제 #16
0
def plot_scatter_intensities(intensity_cols, experiment1, experiment2="Control_WCL", path=""):
    """
    Create a scatter plot of the per-protein raw intensities between
    two experiments. Experiment names should be the names of the columns
    minus the "Intensity " part.
    """
    if "Intensity %s"%experiment1 not in intensity_cols.columns:
        raise ValueError("Supplied column name not in dataframe")
    f = plt.figure(figsize=(3, 3))
    plt.loglog()
    tmp_prot_groups = intensity_cols.loc[:, ["Intensity %s"%experiment1, "Intensity %s"%experiment2]]
    sns.regplot(tmp_prot_groups.ix[:, 1], tmp_prot_groups.ix[:, 0], fit_reg=False)
    xs = np.linspace(tmp_prot_groups.min()[0], tmp_prot_groups.max()[0])
    plt.plot(xs, tmp_prot_groups.sum()[0]/tmp_prot_groups.sum()[1]*xs, "r", alpha=0.4)
    sns.axlabel("%s Raw Intensities"%experiment1.replace("_", " "),
                "%s Raw Intensities"%experiment2.replace("_", " "))
    sns.despine()
    plt.tight_layout()
    plt.savefig(os.path.join(path, "%sv%s_intensities.png"%(experiment1, experiment2)), dpi=300)
    def plot_pca_components(self, fig1, gs, pca_components, required_pcs, plot_title='Habneula', gridspecs='[0,0]'):
        ax1 = eval('fig1.add_subplot(gs' + gridspecs + ')')
        with sns.axes_style('darkgrid'):
            for ii in range(size(pca_components, 1)):
                if ii in required_pcs:
                    plt.plot(pca_components[:, ii], '-', linewidth=5, label=str(ii))
                else:
                    plt.plot(pca_components[:, ii], '--', label=str(ii))

            plt.title(plot_title, fontsize=14)
            sns.axlabel("Time (seconds)", "a.u")
            plt.locator_params(axis='y', nbins=4)
            sns.axlabel("Time (seconds)", "a.u")
            ax1.legend(prop={'size': 14}, loc='center left', bbox_to_anchor=(1, 0.5), ncol=1, fancybox=True,
                       shadow=True)
            plt.axhline(y=0, linestyle='-', color='k', linewidth=1)
            ax1.locator_params(axis='y', pad=50, nbins=2)
            plt.ylim((min(pca_components) - 0.0001, max(pca_components) + 0.0001))
            self.plot_vertical_lines_onset()
            self.plot_vertical_lines_offset()
예제 #18
0
def universal_graph_func(text_variable,title_string,save_file_name_string):
    sns.set(font_scale=.8)
    sns.axlabel('Color', 'Frequency')
    # colors from http://www.color-hex.com and wikipedia
    flatui = ["#4b0082", "#ffd700", "#e6e6fa", "#ffff00", "#FF2400", "#ff6eb4", "#d2b48c", "#ff00ff", "#0000ff",
              "#C8A2C8",
              "#800080", "#FF007F", "#FD3F92", "#000000", "#dc143c", "#CCCCFF", "#ffffff", "#ff0000", "#631919",
              "#fffff0",
              "#ffa500", "#730000", "#808000", "#00ffff", "#c0c0c0", "#808080", "#7fffd4", "#808080", "#008000",
              "#f5f5dc",
              "#329999", "#f0ffff", "#FFEF00"]
    custom_palette = sns.color_palette(flatui)
    colors = text_variable[0]
    occurences = text_variable[1]
    ax = sns.barplot(colors, occurences, palette = custom_palette)
    fig = ax.get_figure()
    for item in ax.get_xticklabels():
        item.set_rotation(45)
    sns.plt.title(title_string)
    fig.savefig(save_file_name_string)
    fig.clf()
예제 #19
0
def plot_heatmap(df, title, file_name, vmax=1.5, vmin=-1.5, cmap=sns.diverging_palette(220, 20, n=7, as_cmap=True), figsize=(16, 8), dpi=300):

    sns.set_style("white")
    fig = plt.figure(figsize=figsize)
    df = df.reindex(['G', 'A', 'V', 'I', 'L', 'M', 'F', 'Y', 'W', 'C', 'S', 'T', 'P', 'D', 'E', 'N', 'Q', 'H', 'K', 'R', '*'])
    df.index.values[-1:] = ['STOP']
    if 77 in df.columns:
        df = df.loc[:, :76]
    if 0 in df.columns:
        df.drop(0, axis=1, inplace=True)
    sns.heatmap(df, square=True, linewidths=0.25, xticklabels=2, cmap=cmap, vmin=vmin, vmax=vmax)
    yeast_ubq = np.array(utils.canonical_yeast_ubq)
    mask = df.apply(lambda x: x.index.isin(np.where(yeast_ubq == x.name)[0]+1), axis=1)
    df.loc[:, :] = 1
    sns.heatmap(df, mask=~mask, cmap=sns.dark_palette("grey", n_colors=1, as_cmap=True, reverse=True), xticklabels=2, cbar=False, square=True, alpha=0.6)

    plt.yticks(rotation=0)
    plt.title(title, fontsize=16)
    pos = fig.axes[1].get_position()
    fig.axes[1].set_position([pos.x0, 0.4, 0.1, 0.2])
    sns.axlabel("Ub position", "Amino acid")
    if file_name is not None:
        plt.savefig(file_name, dpi=dpi, bbox_inches='tight', pad_inches=0)
    return fig
예제 #20
0
def graph_func3(grimm):
    sns.set( font_scale=.8)
    sns.axlabel('Color', 'Frequency' )

    #colors from http://www.color-hex.com and wikipedia
    #flatui = ["#521515", "#fffff0", "#4b0082","#ffd700", "#7fffd4", "#e6e6fa", "#ffff00",
    #          "#dc143c", "#ffc0cb", "#660000", "#808000", "#00ffff", "#d2b48c", "#c0c0c0",
    #          "#ff00ff", "#0000ff", "#808080", "#ffec8b","#ab82ff", "#ee4000", "#993299",
    #          "#ffaeb9", "#FF00FF", "#808080", '#f0ffff', "#008000", "#f5f5dc", "#008080",
    #          "#CCCCFF","#ffa500", "#000000", "#ffffff", "#ff0000"]
    flatui = ["#4b0082","#ffd700", "#e6e6fa", "#ffff00", "#FF2400", "#ff6eb4", "#d2b48c", "#ff00ff", "#0000ff", "#C8A2C8",
              "#800080", "#FF007F", "#FD3F92", "#000000", "#dc143c", "#CCCCFF", "#ffffff", "#ff0000", "#631919", "#fffff0",
              "#ffa500","#730000", "#808000","#00ffff","#c0c0c0","#808080",  "#7fffd4", "#808080", "#008000", "#f5f5dc",
              "#329999", "#f0ffff", "#FFEF00"]
    custom_palette = sns.color_palette(flatui)
    colors = grimm[0]
    occurences = grimm[1]
    ax3 = sns.barplot(colors, occurences, palette = custom_palette)
    fig3 = ax3.get_figure()
    for item in ax3.get_xticklabels():
        item.set_rotation(45)
    sns.plt.title('Color Word Frequencies in Brothers Grimm Stories')
    fig3.savefig('grimm_chart.png')
    fig3.clf()
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

data = np.array(list(map(lambda x: list(map(float, x.split("\t"))),
"""10	100	250	750	2250	6200	10000	12000
0.244	10.666	20.033	45.213	195.22	949.797	1413.038	1836.463
0.001	0.008	0.059	1.201	29.594	595.976	2522.441	8134.59""".split("\n"))))

sns.set(style="white", palette="muted")
b, g, r, p = sns.color_palette("muted", 4)
ax = sns.tsplot(data[1], time=data[0], condition="Learning",color=g)
plt.tight_layout()

ax.fill_between(data[0], 1e-12, data[1], color=g, alpha=0.25)
ax2 = sns.tsplot(data[1] + data[2],condition="Learning + Inversion", time=data[0], color=b)
ax2.fill_between(data[0],  data[1] + data[2], data[1], color=b, alpha=0.25)
plt.legend(loc='upper left')
plt.title("System Computation time vs. Recommendable Documents")
sns.axlabel("# Of Documents", "Time (s)")
plt.savefig("images/computation_time.pdf", bbox_inches="tight")
예제 #22
0
# 
# - Plotting function parameters, e.g. sns.distplot(kde=False)
# - Seaborn functions, called on the sns Seaborn object synonym
# 
# Similar to how you use plt, matplotlib's import synonym, to customize matplotlib graphics, you use sns, seaborn's import synonym, to refer to a plot and call functions from <a href = "https://stanford.edu/~mwaskom/software/seaborn/api.html#style-frontend">Seaborn's API</a> to customize it. For example, to set the x-axis and y-axis labels, use the <a href = "https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.axlabel.html#seaborn.axlabel">.axlabel() function</a>:
# 
#     sns.distplot(births['prglngth'], kde=False)
#     sns.axlabel('Pregnancy Length, weeks', 'Frequency')

# In[5]:

import seaborn as sns
get_ipython().magic('matplotlib inline')

sns.distplot(births['prglngth'], kde=False)
sns.axlabel('Pregnancy Length, weeks', 'Frequency')


# ###6: Practice: customizing distplot()

# Now it's your turn to practice customizing histograms using Seaborn!

# ####Instructions

# Plot a histogram of the birthord column with the following tweaks:
# 
#         x-axis label: Birth number
#         y-axis label: Frequency
#         style: "dark"

# In[6]:
예제 #23
0
def plot_pca_figures(pca, maps, pts, clrs, recon,tt,unique_clrs, matched_pixels,matched_signals, Exp_Folder, filename_suffix, Exp_Name):  

    #Plotting as pdf
    Figure_PDFDirectory = Exp_Folder+'Figures'+filesep
    if not os.path.exists(Figure_PDFDirectory):
        os.makedirs(Figure_PDFDirectory)           
    pp = PdfPages(Figure_PDFDirectory+filename_suffix+'_PCA.pdf')

    sns.set_context("poster")  
    
    dIPN = [Exp_Name.index(s) for s in Exp_Name if "dIPN" in s]
    vIPN = [Exp_Name.index(s) for s in Exp_Name if "vIPN" in s]

############ Plot Colormaps of scores ############
    
    #If there is only one stack, else plot each stack
    if len(maps.shape)==3:
        #Plot colored maps for each stack
        with sns.axes_style("white"):
            fig2 = plt.imshow(maps[:,:,:].transpose((1,0,2)))
            plt.title(Exp_Name[0])
            fig2 = plt.gcf()
            pp.savefig(fig2)
            plt.close()

    else:
        #Plot dIPN
        fig2 = plt.figure()
        for ii in range(0,np.size(dIPN,0)):           
            with sns.axes_style("white"):
                plt.subplot(2,3,ii+1)                        
                plt.imshow(maps[:,:,dIPN[ii],:])
                plt.axis('off')
                plt.title(Exp_Name[dIPN[ii]][15:18],fontsize=10)            
#        plt.tight_layout()   
        fig2 = plt.gcf()
        pp.savefig(fig2)
        plt.close()
                
        #Plot vIPN
        fig2 = plt.figure()
        for ii in range(0,np.size(vIPN,0)):           
            with sns.axes_style("white"):
                plt.subplot(2,3,ii+1)                        
                plt.imshow(maps[:,:,vIPN[ii],:])
                plt.axis('off')
                plt.title(Exp_Name[vIPN[ii]][15:18], fontsize=10)            
#        plt.tight_layout()   
        fig2 = plt.gcf()
        pp.savefig(fig2)
        plt.close()        

    ########### Plot components ##################
    fig2 = plt.figure()
    sns.set_context("talk", font_scale=1.25)
    with sns.axes_style("dark"):
        ax1 = plt.subplot(231)
        plt.plot(pca.comps.T);
        plt.locator_params(axis = 'y', nbins = 4)
        sns.axlabel("Time (seconds)","a.u")
        A = []
        for ii in xrange(0,np.size(pca.comps.T, 0)):
            A = np.append(A, ['comp' + str(ii+1)])
        ax1.legend(A, loc=4)
        plot_vertical_lines()
        plt.axhline(y=0, linestyle='-', color='k', linewidth=1)
        
    #Plot mean signals according to color and boxplot of number of pixels in each plane
    with sns.axes_style("dark"):
        for ii in range(0,np.size(unique_clrs,0)):       
            fig2 = plt.subplot(234)
            sns.tsplot(np.array(matched_signals[ii].clr_grped_signal), ci=95, err_style="ci_band", color=unique_clrs[ii])
            plt.locator_params(axis = 'y', nbins = 4)            
            sns.axlabel("Time (seconds)","a.u")            
            plot_vertical_lines()
        plt.axhline(y=0, linestyle='-', color='k', linewidth=1)

    matching = [Exp_Name.index(s) for s in Exp_Name if "vIPN" in s]
    temp_matched_pixels = matched_pixels[:,matching]
    with sns.axes_style("white"):
        fig2 = plt.subplot(232)
        fig2 = sns.boxplot(np.transpose(temp_matched_pixels),linewidth=2, widths=.5, color=unique_clrs)
        for ii in range(0,np.size(unique_clrs,0)):
            fig2 = plt.plot(np.repeat(ii+1,np.size(temp_matched_pixels,1)), np.transpose(temp_matched_pixels[ii,:]),'s', \
            color=unique_clrs[ii], markersize=5, markeredgecolor='k', markeredgewidth=2) 
            plt.locator_params(axis = 'y', nbins = 4)
        plt.title('vIPN')

#            plt.ylim((0, 1000))
        sns.axlabel("Colors", "Number of Pixels")
        sns.despine(offset=10, trim=True);    
        
    matching = [Exp_Name.index(s) for s in Exp_Name if "dIPN" in s]
    temp_matched_pixels = matched_pixels[:,matching]
    with sns.axes_style("white"):
        fig2 = plt.subplot(233)
        fig2 = sns.boxplot(np.transpose(temp_matched_pixels),linewidth=2, widths=.5, color=unique_clrs)
        for ii in range(0,np.size(unique_clrs,0)):
            fig2 = plt.plot(np.repeat(ii+1,np.size(temp_matched_pixels,1)), np.transpose(temp_matched_pixels[ii,:]),'s', \
            color=unique_clrs[ii], markersize=5, markeredgecolor='k', markeredgewidth=2) 
            plt.locator_params(axis = 'y', nbins = 4)
#            plt.ylim((0, 1000))
        sns.axlabel("Colors", "Number of Pixels")
        plt.title('dIPN')
        sns.despine(offset=10, trim=True);    
        
        
    #Create an lm plot seperating Before and After number of pixels
    #Make Panda data frame    
    A = np.zeros((3,np.size(matched_pixels,0)*np.size(matched_pixels,1)), dtype=np.int)
    count = 0
    for ii in range(0,np.size(matched_pixels,0)):
        for jj in range(0,np.size(matched_pixels,1)):
            A[0,count] = matched_pixels[ii,jj]
            A[1,count] = ii
            if jj in [0,1,3,5]:
                A[2,count] = 1 #vIPN
            else:
                A[2,count] = 0 #dIPN
            count = count+1
    A = np.transpose(A)
    B = pd.DataFrame({'Pixel':A[:,0], 'response':A[:,1], 'IPN':A[:,2]})
    B["Region"] = B.IPN.map({1: "vIPN", 0: "dIPN"})
    



    #Plot mean projection        
    with sns.axes_style("white"):  
        fig2 = plt.subplot(235)
        matching = [Exp_Name.index(s) for s in Exp_Name if "vIPN" in s]
        temp = np.max(maps[:,:,matching,:], axis=2)
        plt.imshow(temp.astype(np.float16).transpose((1,0,2)))
        plt.axis('off')
        plt.title('Max vIPN')
        
        fig2 = plt.subplot(236)
        matching = [Exp_Name.index(s) for s in Exp_Name if "dIPN" in s]
        temp = np.max(maps[:,:,matching,:], axis=2)
        plt.imshow(temp.astype(np.float16).transpose((1,0,2)))
        plt.axis('off')
        plt.title('Max dIPN')
        
        plt.tight_layout()
        fig2 = plt.gcf()
        pp.savefig(fig2)
        plt.close()

    with sns.axes_style("dark"):
         fig3 = plt.figure()
         g = sns.lmplot("Pixel", "IPN", B, y_jitter=.20, hue="response", fit_reg=False, palette=unique_clrs, markers="s", scatter_kws={"s": 50})
         g.set(ylim = (-0.2, 1.2), yticks=[0, 1], yticklabels=["dIPN", "vIPN"])
         plt.axhline(y=0.5, linestyle='-', color='w', linewidth=0.5)
         fig3 = plt.gcf()
         pp.savefig(fig3)
         plt.close()

    with sns.axes_style("dark"):
         fig3 = plt.figure()
         g = sns.lmplot("Pixel", "IPN", B, y_jitter=.20, fit_reg=True, palette=unique_clrs, markers="s", scatter_kws={"s": 50})
         g.set(ylim = (-0.2, 1.2), yticks=[0, 1], yticklabels=["dIPN", "vIPN"])
         plt.axhline(y=0.5, linestyle='-', color='w', linewidth=0.5)
         fig3 = plt.gcf()
         pp.savefig(fig3)
         plt.close()  
         
    
        
    pp.close()
def plot_pca_maps_for_stacks(pca, maps, pts, clrs, recon, unique_clrs, matched_pixels, matched_signals, num_z_planes,\
        Exp_Folder, filename_save_prefix, Stimulus_Name, stim_start, stim_end):
        
    filesep = os.path.sep
     
    # To save as pdf create file
    Figure_PDFDirectory = Exp_Folder+filesep+'Figures'+filesep
    if not os.path.exists(Figure_PDFDirectory):
        os.makedirs(Figure_PDFDirectory)           
    pp = PdfPages(Figure_PDFDirectory+filename_save_prefix+'_PCA_Stacks.pdf')
                
    sns.set_context("poster") 
    
    if num_z_planes!=0:
        Filenames_stim = [ii + ' Z='+ str(jj)  for jj in num_z_planes for ii in Stimulus_Name]
    else:
        Filenames_stim = [ii + ' Z='+ str(jj+1) for jj in range(0,np.size(maps,2)/np.size(Stimulus_Name)) for ii in Stimulus_Name]
    
    ############ Plot Colormaps of scores ############    
    for ii in range(0,np.size(Filenames_stim)):
        with sns.axes_style("white"):
            fig2 = plt.imshow(maps[:,:,ii,:])
            plt.title((Filenames_stim[ii]))
            plt.axis('off')                   
            fig2 = plt.gcf()
            pp.savefig(fig2)
            plt.close()    
            
    
    ########### Plot components ##################
    fig2 = plt.figure()
    sns.set_context("talk", font_scale=1.25)
    with sns.axes_style("darkgrid"):
        ax1 = plt.subplot(221)
        plt.plot(pca.comps.T);
        plt.locator_params(axis = 'y', nbins = 4)
        sns.axlabel("Time (seconds)","a.u")
        A = []
        for ii in xrange(0,np.size(pca.comps.T, 0)):
            A = np.append(A, [str(ii+1)])
            
        ax1.legend(A, loc=4)
        plt.axhline(y=0, linestyle='-', color='k', linewidth=1)
        plot_vertical_lines(stim_start,stim_end)
        
    
    #Plot mean signals according to color and boxplot of number of pixels in each plane
    with sns.axes_style("darkgrid"):
        for ii in range(0,np.size(unique_clrs,0)):       
            fig2 = plt.subplot(223)
            sns.tsplot(np.array(matched_signals[ii].clr_grped_signal), linewidth=3, ci=95, err_style="ci_band", color=unique_clrs[ii])
            plt.locator_params(axis = 'y', nbins = 4)            
            sns.axlabel("Time (seconds)","a.u")            
        plot_vertical_lines(stim_start,stim_end)
        plt.axhline(y=0, linestyle='-', color='k', linewidth=1)

    
    with sns.axes_style("white"):
        fig2 = plt.subplot(222)
        fig2 = sns.boxplot(np.transpose(matched_pixels),linewidth=3, widths=.5, color=unique_clrs)
        for ii in range(0,np.size(unique_clrs,0)):
            fig2 = plt.plot(np.repeat(ii+1,np.size(matched_pixels,1)), np.transpose(matched_pixels[ii,:]),'s', \
            color=unique_clrs[ii], markersize=5, markeredgecolor='k', markeredgewidth=2) 
            plt.locator_params(axis = 'y', nbins = 4)
        sns.axlabel("Colors", "Number of Pixels")
        sns.despine(offset=10, trim=True);  
        
    
    plt.tight_layout()
    fig2 = plt.gcf()
    pp.savefig(fig2)
    plt.close()
   
    for stim in xrange(0,np.size(Stimulus_Name)):
       with sns.axes_style("white"):
           same_stim_folders = [Filenames_stim.index(ii) for ii in Filenames_stim if ii.find(Stimulus_Name[stim])==0]
           fig2 = plt.subplot(221)
           matched_pixels_stim = matched_pixels[:,same_stim_folders]
           
           if np.size(matched_pixels_stim,1) == 1:
               for ii in xrange(0,np.size(matched_pixels_stim,0)):
                   fig2 = plt.plot(ii+1,np.transpose(matched_pixels_stim[ii,:]),'o', color=unique_clrs[ii])
               plt.xlim([0,np.size(matched_pixels_stim,0)+1])
           else:
               fig2 = sns.boxplot(np.transpose(matched_pixels_stim),linewidth=3, widths=.5, color=unique_clrs)
           
           for ii in range(0,np.size(unique_clrs,0)):
               fig2 = plt.plot(np.repeat(ii+1,np.size(matched_pixels_stim,1)), np.transpose(matched_pixels_stim[ii,:]),'s', \
               color=unique_clrs[ii], markersize=5, markeredgecolor='k', markeredgewidth=2) 
               plt.locator_params(axis = 'y', nbins = 4)
               
           sns.axlabel("Colors", "Number of Pixels")
           sns.despine(offset=10, trim=True)  
           
           
           for ii in range(0,np.size(unique_clrs,0)):       
                fig2 = plt.subplot(223)
                sns.tsplot(np.array(matched_signals[ii].clr_grped_signal), linewidth=3, ci=95, err_style="ci_band", color=unique_clrs[ii])
                plt.locator_params(axis = 'y', nbins = 4)            
                sns.axlabel("Time (seconds)","a.u")            
                plot_vertical_lines(stim_start,stim_end)
           plt.axhline(y=0, linestyle='-', color='k', linewidth=1)
           
           fig2 = plt.subplot(222)
           temp = (np.mean(maps[:,:,same_stim_folders,:], axis=2))
           plt.imshow(temp.astype(np.float16))
           plt.axis('off')
           plt.title('Mean projection' + Stimulus_Name[stim])
           plt.tight_layout()
           
           fig2 = plt.gcf()
           pp.savefig(fig2)
           plt.close()
    
    pp.close()
예제 #25
0
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np


# Script used to generate timing plot for different error correction methods
timings = np.array([12, 15, 3, 3, 10, 67, 62])
IDs = ["Quake", "Bless", "Musket", "BFC", "Seecer", "BayesHammer", "MultiRes"]
sns.barplot(x=IDs, y=timings)
sns.axlabel("Algorithms", "Timings(in minutes)")
sns.plt.title("Comparison of timings for error correction algorithms")
예제 #26
0
    plt.figure(figsize=(16, 10))
    sns.set_context("poster", font_scale=0.6) #rc={"lines.linewidth": 2.5}

    """ # the view of everthing
    sns.heatmap(refpubyear_count, linewidths=.5, yticklabels=3)
    ax.xaxis.tick_top()
    ax.invert_yaxis()
    sns.axlabel(conf + ' paper-published-year', 'reference-published-year')
    """

    # the subset of reference years
    ax = sns.heatmap(refpubyear_count.loc[1975:2015], linewidths=.5, annot=True, fmt=".0f", cmap="GnBu")
    ax.xaxis.tick_top()
    ax.invert_yaxis()
    sns.axlabel(conf + ' paper-published-year', 'reference-published-year')

    plt.savefig(os.path.join(plot_dir, conf, conf+'_year_ref.png'), transparent=True)

    """ # box plot of the age of paper being cited 
    dataframe:  df_citing
    y: RefPubYear
    y: ref age (paperpubyear - refpubyear)
    x (group by): PaperPubYear   
    """
    plt.figure(figsize=(16, 4))
    df_citing['RefAge'] = - df_citing['PaperPubYear'] + df_citing['RefPubYear']
    axb = sns.boxplot(x="PaperPubYear", y="RefAge", data=df_citing, 
                     linewidth=1., palette=bar_colrs3)
    ylim = axb.get_ylim()
    axb.set_ylim([max(-60, ylim[0]), min(5, ylim[1])])
예제 #27
0
                                  header=None,
                                  names=["inst", "time"],
                                  usecols=["time"],
                                  na_values=["t"])
    except IOError:
        next

color = '#000000'
format = 'pdf'
if sys.argv[1] == "eps":
    color = '#796045'
    format = 'eps'
sns.set(font_scale=1.41)
sns.set_style("whitegrid",
              rc={
                  "grid.color": color,
                  "xtick.color": color,
                  "ytick.color": color,
                  "axes.edgecolor": color,
                  "axes.labelcolor": color,
                  "text.facecolor": 'white',
              })
sns.set_palette("Set1", desat=0.22)
sns.axlabel("time needed", "")  #"heuristic")
ax = sns.boxplot(frame, orient="h", width=0.79)
ax.get_figure().subplots_adjust(left=0.24)
ax.set(xscale="log")
ax.get_figure().savefig('build/tsplib_med_time.' + format,
                        format=format,
                        transparent=True)
# Simple plot of linear, quadratic, and cubic curves
x = np.linspace(0, 2, 100)
plt.plot(x, x, label='linear')
plt.plot(x, x**2, label='quadratic')
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend(loc="best")
plt.show()


# Histogram
x = np.random.normal(size=1000)
sns.distplot(x, bins=20, kde=True, rug=False, label="Histogram w/o Density")
sns.axlabel("Value", "Frequency")
plt.title("Histogram of a Random Sample from a Normal Distribution")
plt.legend()
plt.show()


# Scatter plot
mean, cov = [5, 10], [(1, .5), (.5, 1)]
data = np.random.multivariate_normal(mean, cov, 200)
data_frame = pd.DataFrame(data, columns=["x", "y"])
sns.jointplot(x="x", y="y", data=data_frame, kind="reg").set_axis_labels("x", "y")
plt.suptitle("Joint Plot of Two Variables with Bivariate and Univariate Graphs")
plt.show()


# Pairwise bivariate
예제 #29
0
    for s in range(100):
        U[s, :] = e.policy_batch.eval(e.sess, X).flat
    tshist(axarr[i, 1], X, U)

    # column 2 log-loss surfaces after learning
    x0v, u0v = np.meshgrid(np.linspace(0, 1, 30), np.linspace(-1, 1, 30))
    x0v, u0v = x0v.reshape((-1, 1)), u0v.reshape((-1, 1))
    x1v = np.array([sim.fstep(x, u0v[j]) for j, x in enumerate(x0v)]).reshape(
        (-1, 1))
    Lr = e.eval_1d(e.loss_log, x0v, u0v, x1v)
    sns.heatmap(Lr.reshape(30, 30),
                ax=axarr[i, 2],
                cmap='gray',
                vmin=-13,
                vmax=-.5)
    sns.axlabel('X', 'A')

    # column 3 - prediction loss under a variety of
    #Lp = e.eval_1d(e.loss_abs_p,x0v,u0v,x1v)
    #sns.heatmap(Lp.reshape(30,30),ax=axarr[i,3],cmap='gray',vmin=0.,vmax=1.)
    #Xr = e.eval_1d(e.loss_predict,X,X,X) # the second 2 args are hacks
    #axarr[i,3].plot(X,Xr)
    print(c)

# # test
# x0v = X
# u0v = np.ones((e.batch_size,1))
# x1v = np.ones((e.batch_size,1)) # irrelevant
# xp = e.eval_1d(e.x_predict,x0v,u0v,x1v)
# pdb.set_trace()
예제 #30
0
print ('chisq test statistic = {}; p-value = {}'.format(*chisq))

# graph plotting with seaborn
sns.set_style('white')
sns.set_style('ticks')
plt.figure(figsize=(8,5))
sns.distplot(obs_distances, 
             bins=np.linspace(0, WINDOW, 41), norm_hist=True, color='#d8b365',
             hist_kws={'alpha': 0.3}, kde_kws={'bw': increment}, label='Observed')
sns.distplot(exp_distances, 
             bins=np.linspace(0, WINDOW, 41), norm_hist=True, color='#5ab4ac',
             hist_kws={'alpha': 0.3}, kde_kws={'bw': increment}, label='Expected')

if args.dist == 'upstream_to_start':
    sns.plt.xlim(int(WINDOW * 1.01), int(WINDOW * -0.01))
    sns.axlabel("Distance to gene 5' end (bp)", 'Density')
elif args.dist == 'downstream_from_start':
    sns.plt.xlim(int(WINDOW * -0.01), int(WINDOW * 1.01))
    sns.axlabel("Distance from gene 5' end (bp)", 'Density')
elif args.dist == 'upstream_to_end':
    sns.plt.xlim(int(WINDOW * 1.01), int(WINDOW * -0.01))
    sns.axlabel("Distance to gene 3' end (bp)", 'Density')
elif args.dist == 'downstream_from_end':
    sns.plt.xlim(int(WINDOW * -0.01), int(WINDOW * 1.01))
    sns.axlabel("Distance from gene 3' end (bp)", 'Density')

plt.legend(loc=9, ncol=2)
sns.despine(offset=10, trim=True)

# save plot
fig = plt.gcf()
예제 #31
0
plt.show()

# Look at the distribution of quality by wine type
red_wine = wine.ix[wine['type']=='red', 'quality']
white_wine = wine.ix[wine['type']=='white', 'quality']

sns.set_style("dark")
print("""\nsns.distplot(red_wine, 
                   norm_hist=True, kde=False, color=red, label=Red wine)""")
print(sns.distplot(red_wine, \
		norm_hist=True, kde=False, color="red", label="Red wine"))
print("""\nsns.distplot(white_wine, 
                   norm_hist=True, kde=False, color=white, label=White wine)""")
print(sns.distplot(white_wine, \
		norm_hist=True, kde=False, color="white", label="White wine"))
sns.axlabel("Quality Score", "Density")
plt.title("Distribution of Quality by Wine Type")
plt.legend()
#plt.show()

# Test whether mean quality is different between red and white wines
print("\nwine.groupby(['type'])[['quality']].agg(['std', 'mean'])")
print(wine.groupby(['type'])[['quality']].agg(['std', 'mean']))
tstat, pvalue, df = sm.stats.ttest_ind(red_wine, white_wine)
print("\n'tstat: %.3f  pvalue: %.4f' % (tstat, pvalue)")
print('tstat: %.3f  pvalue: %.4f' % (tstat, pvalue))

# Fit a multivariate linear regression model
#wine_standardized = (wine - wine.mean()) / wine.std()
#formula_all = 'quality ~ alcohol + chlorides + citric_acid + density + fixed_acidity + free_sulfur_dioxide + pH + residual_sugar + sulphates + total_sulfur_dioxide + volatile_acidity'
my_formula = 'quality ~ alcohol + chlorides + citric_acid + density + fixed_acidity + free_sulfur_dioxide + pH + residual_sugar + sulphates + total_sulfur_dioxide + volatile_acidity'
    
if args.end:
    endTime = re.sub('\.{1}','T',args.end)
    endTime+=":00"
    firstIndex = dateRange.index(endTime)
else:
    firstIndex = 0
    
palette = it.cycle(sea.color_palette())

fig = plt.figure()
sea.set_style('darkgrid')
fig.suptitle('MS Band Hourly Summary',fontsize=16)


ax1 = fig.add_subplot(311)
ax1.plot_date(x[firstIndex:lastIndex],caloriesBurned[firstIndex:lastIndex],color=next(palette),linestyle='-',fillstyle='none')
sea.axlabel('','Calories Burned')

ax2 = fig.add_subplot(312)                        # 3 rows, 1 column, plot #2
ax2.plot_date(x[firstIndex:lastIndex],stepsTaken[firstIndex:lastIndex],color=next(palette),linestyle='-',fillstyle='none')
sea.axlabel('','Steps Taken')

ax3 = fig.add_subplot(313)                        # 3 rows, 1 column, plot #3
ax3.plot_date(x[firstIndex:lastIndex],avgHeartRate[firstIndex:lastIndex],color=next(palette),linestyle='-',fillstyle='none')
ax3.plot_date(x[firstIndex:lastIndex],lowHeartRate[firstIndex:lastIndex],color=next(palette),linestyle='-',fillstyle='none')
ax3.plot_date(x[firstIndex:lastIndex],peakHeartRate[firstIndex:lastIndex],color=next(palette),linestyle='-',fillstyle='none')
ax3.xaxis.set_major_formatter(dates.DateFormatter('%m/%d/%Y %H:%M'))
fig.autofmt_xdate()               # angle the dates for easier reading
sea.axlabel('Date','Heart Rate')
예제 #33
0
import seaborn as sns
import matplotlib.pyplot as plt
from datos import data

sns.set(style="whitegrid")
d = data('mtcars')
sns.countplot(x="gear", hue="cyl", data=d)
sns.axlabel("Number of Gears", "Frequency")
plt.title('Car Distribution by Gear and Cylindres', family='Serif', size=16)
plt.show()
roi_names, roi_coords = load_msdl_names_and_coords()
stat_av = read_test('pc', 'av', 'avg')
stat_v = read_test('pc', 'v', 'avg')
stat2 = read_test2('pc', ['av', 'v'], 'avg')


i, j = np.unravel_index(stat2.argmax(), stat2.shape)
print 'av 1sample pval :', stat_av[i, j]
print 'v 1sample pval :', stat_v[i, j]
print roi_names[i], roi_names[j]
print i, j

m = np.eye(2)
m[1,0] = stat2[i, j]
m[0,1] = m[1,0] 
plot_connectome(m, [roi_coords[i], roi_coords[j]])


conn = []
behav = []
for i in range(len(dataset.subjects)):
    c = load_dynacomp_fc(dataset.subjects[i], session='func1', metric='pc', msdl=True)
    conn.append(c[i, j])
    b = behav_data[i]['postRT'] - behav_data[i]['preRT']
    behav.append(b)

sns.jointplot(np.array(conn), np.array(behav), kind='kde')
sns.axlabel('Connectivity', 'Behavior')

예제 #35
0
def plot_regression_error(clf, X_train, y_train, name):
    predicted = cross_val_predict(clf, X_train, y_train, cv=5)
    sns.regplot(x=y_train, y=predicted)
    sns.axlabel("actual", "predicted")
    plt.savefig("plot_validation_" + name + ".png")
def plot_pca_figures(pca, maps, pts, clrs, recon,tt,unique_clrs, matched_pixels,matched_signals, Exp_Folder, filename_suffix, Exp_Name):  

    #Plotting as pdf
    Figure_PDFDirectory = Exp_Folder+'Figures'+filesep
    if not os.path.exists(Figure_PDFDirectory):
        os.makedirs(Figure_PDFDirectory)           
    pp = PdfPages(Figure_PDFDirectory+filename_suffix+'_PCA.pdf')

    sns.set_context("poster")  
    
#Pick experiemnt names and seperate to indeces for plotting     
    Fishnum = np.unique([np.int(ii[15:18]) for ii in Exp_Name])

############ Plot Colormaps of scores ############
    
    #If there is only one stack, else plot each stack
    if len(maps.shape)==3:
        #Plot colored maps for each stack
        with sns.axes_style("white"):
            fig2 = plt.imshow(maps[:,:,:].transpose((1,0,2)))
            plt.title(Exp_Name[0])
            fig2 = plt.gcf()
            pp.savefig(fig2)
            plt.close()

    else:
        count = 0
        for ii in range(0,np.size(Fishnum,0)):
            fig2 = plt.figure()
            count2=3
            with sns.axes_style("white"):               
                for jj in range(3):   
                    print str(ii) + ' ' + str(jj)
                    if ii == 0 and jj == 2:
                        continue
                    if "Before" in Exp_Name[count]:
                        plt.subplot(2,2,1)                        
                        plt.imshow(maps[:,:,count,:].transpose((1,0,2)))
                        plt.axis('off')
                        plt.title(Exp_Name[count][15:-4])
                        count = count+1
                    else: 
                        plt.subplot(2,2,count2)
                        plt.imshow(maps[:,:,count,:].transpose((1,0,2)))
                        plt.axis('off')
                        plt.title(Exp_Name[count][15:-4])
                        count = count+1
                        count2=count2+1

                
                plt.tight_layout()   
                fig2 = plt.gcf()
                pp.savefig(fig2)
                plt.close()
                
        ########### Plot components ##################
        fig2 = plt.figure()
        sns.set_context("talk", font_scale=1.25)
        with sns.axes_style("dark"):
            ax1 = plt.subplot(231)
            plt.plot(pca.comps.T);
            plt.locator_params(axis = 'y', nbins = 4)
            sns.axlabel("Time (seconds)","a.u")
            A = []
            for ii in xrange(0,np.size(pca.comps.T, 0)):
                A = np.append(A, ['comp' + str(ii+1)])
            ax1.legend(A, loc=4)
            plot_vertical_lines()
            plt.axhline(y=0, linestyle='-', color='k', linewidth=1)
            
        #Plot mean signals according to color and boxplot of number of pixels in each plane
        with sns.axes_style("dark"):
            for ii in range(0,np.size(unique_clrs,0)):       
                fig2 = plt.subplot(234)
                sns.tsplot(np.array(matched_signals[ii].clr_grped_signal), ci=95, err_style="ci_band", color=unique_clrs[ii])
                plt.locator_params(axis = 'y', nbins = 4)            
                sns.axlabel("Time (seconds)","a.u")            
                plot_vertical_lines()
            plt.axhline(y=0, linestyle='-', color='k', linewidth=1)        

        matching = [Exp_Name.index(s) for s in Exp_Name if "Before" in s]
        temp_matched_pixels = matched_pixels[:,matching]
        with sns.axes_style("white"):
            fig2 = plt.subplot(232)
            fig2 = sns.boxplot(np.transpose(temp_matched_pixels),linewidth=2, widths=.5, color=unique_clrs)
            for ii in range(0,np.size(unique_clrs,0)):
                fig2 = plt.plot(np.repeat(ii+1,np.size(temp_matched_pixels,1)), np.transpose(temp_matched_pixels[ii,:]),'s', \
                color=unique_clrs[ii], markersize=5, markeredgecolor='k', markeredgewidth=2) 
                plt.locator_params(axis = 'y', nbins = 4)
#                plt.ylim((0, 600))
            sns.axlabel("Colors", "Number of Pixels")
            sns.despine(offset=10, trim=True);    
            
        matching = [Exp_Name.index(s) for s in Exp_Name if "After" in s]
        temp_matched_pixels = matched_pixels[:,matching]
        with sns.axes_style("white"):
            fig2 = plt.subplot(233)
            fig2 = sns.boxplot(np.transpose(temp_matched_pixels),linewidth=2, widths=.5, color=unique_clrs)
            for ii in range(0,np.size(unique_clrs,0)):
                fig2 = plt.plot(np.repeat(ii+1,np.size(temp_matched_pixels,1)), np.transpose(temp_matched_pixels[ii,:]),'s', \
                color=unique_clrs[ii], markersize=5, markeredgecolor='k', markeredgewidth=2) 
                plt.locator_params(axis = 'y', nbins = 4)
#                plt.ylim((0, 600))
            sns.axlabel("Colors", "Number of Pixels")
            sns.despine(offset=10, trim=True);    
            
            
        #Create an lm plot seperating Before and After number of pixels
        #Make Panda data frame    
        A = np.zeros((3,np.size(matched_pixels,0)*np.size(matched_pixels,1)), dtype=np.int)
        count = 0
        for ii in range(0,np.size(matched_pixels,0)):
            for jj in range(0,np.size(matched_pixels,1)):
                A[0,count] = matched_pixels[ii,jj]
                A[1,count] = ii
                if jj in [0,2,5]:
                    A[2,count] = 1 #Before Lesion
                else:
                    A[2,count] = 0 #After Lesion
                count = count+1
        A = np.transpose(A)
        B = pd.DataFrame({'Pixel':A[:,0], 'response':A[:,1], 'Lesion':A[:,2]})
        B["BeforeAfter"] = B.Lesion.map({1: "Before", 0: "After"})
        
        
    
        #Plot mean projection        
        with sns.axes_style("white"):  
            fig2 = plt.subplot(438)
            matching = [Exp_Name.index(s) for s in Exp_Name if "Before" in s]
            temp = np.max(maps[:,:,matching,:], axis=2)
            plt.imshow(temp.astype(np.float16).transpose((1,0,2)))
            plt.axis('off')
            plt.title('Max DRBefore')
            
            fig2 = plt.subplot(4,3,11)
            matching = [Exp_Name.index(s) for s in Exp_Name if "After" in s]
            temp = np.max(maps[:,:,matching[1:],:], axis=2)+0.2
            plt.imshow(temp.astype(np.float16).transpose((1,0,2)))
            plt.axis('off')
            plt.title('Max DRAfter')
            
            plt.tight_layout()
            fig2 = plt.gcf()
            pp.savefig(fig2)
            plt.close()
    
        with sns.axes_style("dark"):
             fig3 = plt.figure()
             g = sns.lmplot("Pixel", "Lesion", B, y_jitter=.20, hue="response", fit_reg=False, palette=unique_clrs, markers="s", scatter_kws={"s": 50})
             g.set(ylim = (-0.2, 1.2), yticks=[0, 1], yticklabels=["After", "Before"])
             plt.axhline(y=0.5, linestyle='-', color='w', linewidth=0.5)
             fig3 = plt.gcf()
             pp.savefig(fig3)
             plt.close()
    
        with sns.axes_style("dark"):
             fig3 = plt.figure()
             g = sns.lmplot("Pixel", "Lesion", B, y_jitter=.20, fit_reg=True, palette=unique_clrs, markers="s", scatter_kws={"s": 50})
             g.set(ylim = (-0.2, 1.2), yticks=[0, 1], yticklabels=["After", "Before"])
             plt.axhline(y=0.5, linestyle='-', color='w', linewidth=0.5)
             fig3 = plt.gcf()
             pp.savefig(fig3)
             plt.close()  
        
        matched_pixels1 = np.delete(matched_pixels, [0],0)
        A = np.zeros((3,np.size(matched_pixels1,0)*np.size(matched_pixels1,1)), dtype=np.float)
        count = 0
        for ii in range(0,np.size(matched_pixels1,0)):
            for jj in range(0,np.size(matched_pixels1,1)):
                A[0,count] = matched_pixels1[ii,jj]/220
                if ii == 2 or ii == 3 or ii == 4:
                    A[1,count] = 1
                else:
                    A[1,count] = 0     
                    
                if jj in [0,2,5]:
                    A[2,count] = 0 #Before Lesion
                else:
                    A[2,count] = 1 #After Lesion
                count = count+1 
        A = np.transpose(A)        
        B = pd.DataFrame({'Cells':A[:,0], 'response':A[:,1], 'Lesion':A[:,2]})
        B["Bef_aft"] = B.Lesion.map({0: "Before", 1: "CAfter"})
        B["Response"] = B.response.map({0: "Excitatory On", 1: "Inhibitory On"})
        fig2 = plt.figure()
        fig2 = sns.factorplot("Response", "Cells", "Bef_aft", B, kind="point", dodge=0.05)
        fig2 = plt.gcf()
        pp.savefig(fig2)
        plt.close()
                
        pp.close()
예제 #37
0
# - Plotting function parameters, e.g. sns.distplot(kde=False)
# - Seaborn functions, called on the sns Seaborn object synonym
#
# Similar to how you use plt, matplotlib's import synonym, to customize matplotlib graphics, you use sns, seaborn's import synonym, to refer to a plot and call functions from <a href = "https://stanford.edu/~mwaskom/software/seaborn/api.html#style-frontend">Seaborn's API</a> to customize it. For example, to set the x-axis and y-axis labels, use the <a href = "https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.axlabel.html#seaborn.axlabel">.axlabel() function</a>:
#
#     sns.distplot(births['prglngth'], kde=False)
#     sns.axlabel('Pregnancy Length, weeks', 'Frequency')

# In[5]:

import seaborn as sns

get_ipython().magic('matplotlib inline')

sns.distplot(births['prglngth'], kde=False)
sns.axlabel('Pregnancy Length, weeks', 'Frequency')

# ###6: Practice: customizing distplot()

# Now it's your turn to practice customizing histograms using Seaborn!

# ####Instructions

# Plot a histogram of the birthord column with the following tweaks:
#
#         x-axis label: Birth number
#         y-axis label: Frequency
#         style: "dark"

# In[6]: