def plot_extracellular(ax, lfp, ele_pos, num_x, num_y, time_pt):
    """Plots the extracellular potentials at a given potentials"""

    lfp *= 1000.
    lfp_max = np.max(np.abs(lfp[:, time_pt]))
    levels = np.linspace(-lfp_max, lfp_max, 16)
    im2 = plt.contourf(ele_pos[:,0].reshape(num_x, num_y), 
                       ele_pos[:,1].reshape(num_x, num_y), 
                       lfp[:,time_pt].reshape(num_x,num_y), 
                       levels=levels, cmap=plt.cm.PRGn)


    # cb = plt.colorbar(im2, extend='both')
    # tick_locator = ticker.MaxNLocator(nbins=9, trim=False, prune=None)
    # #tick_locator.bin_boundaries(-lfp_max, lfp_max)
    # cb.locator = tick_locator
    # #cb.ax.yaxis.set_major_locator(ticker.AutoLocator())
    # cb.update_ticks()
    # cb.ax.set_title('$\mu$V')

    plt.title('Time='+str(time_pt/10.)+' ms')
    plt.xlabel('X ($\mu$m)')
    plt.ylabel('Y ($\mu$m)')
    plt.ylim(ymin=-2150,ymax=550)
    plt.xlim(xmin=-450,xmax=450)
    cbaxes = inset_axes(ax,
                        width="50%",  # width = 10% of parent_bbox width
                        height="2%",  # height : 50%
                        loc=1, borderpad=1.5)
    cbar = plt.colorbar(cax=cbaxes, ticks=[-lfp_max,0.,lfp_max], orientation='horizontal', format='%.2f')
    cbar.ax.set_xticklabels([round(-lfp_max,2),str('0 $\mu V$'),round(lfp_max,2)])
    return ax
def plot_eigenvalue_gaps(
        gaps, 
        xlabel=r"$k$", 
        ylabel=r"$\lambda_{k+1}-\lambda_k$", 
        output="eigen_gap.pdf",
        colors=['b', 'r', 'g', 'c'],
        legend=[r'$\rho_{1}$', r'$\rho_{0.5}$', r'$\rho_{0.25}$'],
        marker=['o', '^', 'v']):
    fig = plt.figure(figsize=(fig_width, fig_height))
    ax = fig.add_subplot(111)
    for i, g in enumerate(gaps):
        xs = range(1, len(g)+1)
        ax.plot(xs, g, color=colors[i], linestyle='-', marker=marker[i],
                linewidth=1.5, markersize=5, label=legend[i], alpha=0.7)
    ax.set_ylabel(r'$\lambda_{k+1} - \lambda_k$')
    ax.set_xlabel(r'$k$')
    ax.set_xlim([1, len(xs)])
    ax.legend(loc=2, framealpha=.5, ncol=1)

    axins = inset_axes(ax, width="60%", height="60%", loc=1, 
                        borderpad=0.5)
    for i, g in enumerate(gaps):
        axins.plot(xs, g, color=colors[i], linestyle='-', marker=marker[i],
                linewidth=1.5, markersize=5, alpha=0.7)
    axins.set_xlim([5,12])
    axins.set_ylim([0,0.006])

    fig.savefig(output, bbox_inches='tight')
def plot_obs_pred(obs, pred, radius, loglog, ax = None, inset = False, sites = None):
    """Generic function to generate an observed vs predicted figure with 1:1 line"""
    if not ax:
        fig = plt.figure(figsize = (3.5, 3.5))
        ax = plt.subplot(111)

    axis_min = 0.9 * min(list(obs[obs > 0]) + list(pred[pred > 0]))
    if loglog:
        axis_max = 3 * max(list(obs)+list(pred))
    else:
        axis_max = 1.1 * max(list(obs)+list(pred))
    macroecotools.plot_color_by_pt_dens(np.array(pred), np.array(obs), radius, loglog=loglog, plot_obj = ax)      
    plt.plot([axis_min, axis_max],[axis_min, axis_max], 'k-')
    plt.xlim(axis_min, axis_max)
    plt.ylim(axis_min, axis_max)
    ax.tick_params(axis = 'both', which = 'major', labelsize = 6)
    if loglog:
        plt.annotate(r'$R^2$ = %0.2f' %macroecotools.obs_pred_rsquare(np.log10(obs[(obs != 0) * (pred != 0)]), np.log10(pred[(obs != 0) * (pred != 0)])),
                     xy = (0.05, 0.85), xycoords = 'axes fraction', fontsize = 7)
    else:
        plt.annotate(r'$R^2$ = %0.2f' %macroecotools.obs_pred_rsquare(obs, pred),
                     xy = (0.05, 0.85), xycoords = 'axes fraction', fontsize = 7)
    if inset:
        axins = inset_axes(ax, width="30%", height="30%", loc=4)
        if loglog:
            hist_mete_r2(sites[(obs != 0) * (pred != 0)], np.log10(obs[(obs != 0) * (pred != 0)]), 
                         np.log10(pred[(obs != 0) * (pred != 0)]))
        else:
            hist_mete_r2(sites, obs, pred)
        plt.setp(axins, xticks=[], yticks=[])
    return ax
def plot_elbow_kernel(
        values, 
        xlabel=r"$k$", 
        #ylabel=r"$\textnormal{Tr}(Y^\top G \, Y)$", 
        ylabel=r"$\log Q_{k+1} - \log Q_{k}$", 
        output="elbow.pdf",
        colors=['b', 'r', 'g'],
        legend=[r'$\rho_{1}$', r'$\rho_{0.5}$', r'$\rho_{0.25}$'],
        marker=['o', '^', 'v']):
    fig = plt.figure(figsize=(fig_width, fig_height))
    ax = fig.add_subplot(111)
    for i, g in enumerate(values):
        xs = range(1, len(g)+1)
        ax.plot(xs, g, color=colors[i], linestyle='-', marker=marker[i],
                linewidth=1.5, markersize=5, label=legend[i], alpha=0.7)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_xlim([1, 12])
    ax.legend(loc=2, framealpha=.5, ncol=1)
    
    axins = inset_axes(ax, width="60%", height="60%", loc=1)
    for i, g in enumerate(values):
        axins.plot(xs[4:], g[4:], 
                color=colors[i], linestyle='-', marker=marker[i],
                linewidth=1.5, markersize=5, alpha=0.7)
    #axins.set_xlim([5,12])
    #axins.set_ylim([19.9,20])
    #axins.set_xticks([])
    #axins.set_yticks([])
    fig.savefig(output, bbox_inches='tight')
Beispiel #5
0
def draw_latent_factors(ax, A, x, y, w, h, space=1, max_abs_ylim=1, **kwargs):

    positions = [(x, y), (x, y + h + space), (x, y + 2 * h + 2 * space)]

    #max_abs_ylim = np.max(np.abs(A))

    axes = []
    for i, (x_, y_) in enumerate(positions):

        c = matplotlib.cm.Greys(0.5 + 0.5 * i / 2.)

        print(i, "latent", c)

        ia = inset_axes(ax,
                        width="100%",
                        height="100%",
                        bbox_to_anchor=(x_, y_, w, h),
                        bbox_transform=ax.transData,
                        borderpad=0,
                        loc=3)
        ia.set_xticks([])
        ia.set_yticks([])

        ia.axhline(0, c="#666666", linestyle=":", lw=0.5, ms=0)
        ia.plot(A.T[i], c=c, lw=2, ms=0)
        ia.set_ylabel(r"$\mathbf{{L}}_{0}$".format(i + 1), fontsize=10)

        ia.set_ylim(-max_abs_ylim, +max_abs_ylim)

        axes.append(ia)

    return axes
Beispiel #6
0
def plot_potential(ax, lfp, max_val, title):
    norm = cm.colors.Normalize(vmax=max_val, vmin=-max_val, clip=False)
    im = plt.imshow(lfp[::-1],
                    aspect='auto',
                    norm=norm,
                    interpolation='nearest',
                    cmap=plt.cm.PRGn)
    plt.xlim((2750, 4250))
    plt.xticks(np.arange(3000, 5000, 1000), np.arange(300, 500, 100))
    # plt.ylabel('Electrode depth ($\mu$m)')
    # plt.xlabel('Time (ms)')
    plt.title(title, fontweight="bold", fontsize=12)
    # plt.yticks(np.arange(28))
    plt.gca().set_yticks(np.arange(28))
    plt.gca().set_yticklabels(np.arange(1, 29))
    for label in plt.gca().yaxis.get_ticklabels()[::2]:
        label.set_visible(False)
    # plt.xlim(xmin=2500, xmax=4500)
    # plt.colorbar(extend='both')
    cbaxes = inset_axes(
        ax,
        width="40%",  # width = 10% of parent_bbox width
        height="3%",  # height : 50%
        loc=1,
        borderpad=1)
    cbar = plt.colorbar(cax=cbaxes,
                        ticks=[-max_val, 0., max_val],
                        orientation='horizontal',
                        format='%.2f')
    cbar.ax.set_xticklabels(
        [round(-max_val, 2),
         str('0 $\mu V$'),
         round(max_val, 2)])
    return ax, im
Beispiel #7
0
def cyclic_colorbar(cmap,
                    ax=None,
                    internal_radius=.4,
                    show_border=True,
                    Nb_segments=100,
                    bckgrnd_color='white',
                    bckgrnd_alpha=.5,
                    bckgrnd_radius=1.6,
                    ticks=math_ticks):

    if ax == None:
        print 'toto'
        ax = inset_axes(gca(), width="25%", height="25%", loc=1)
        ax.axis('off')

    theta = linspace(0, 2 * pi, Nb_segments)

    external_radius = 1

    for i in range(len(theta) - 1):

        segment = [z_tuple(external_radius * exp(1j * theta[i]))]
        segment += [z_tuple(external_radius * exp(1j * theta[i + 1]))]
        segment += [z_tuple(internal_radius * exp(1j * theta[i + 1]))]
        segment += [z_tuple(internal_radius * exp(1j * theta[i]))]

        segment += [segment[0]]

        ax.add_collection(
            PatchCollection([Polygon(segment)],
                            facecolor=cmap(theta[i] / (2 * pi)),
                            edgecolor='none'))

    if show_border:
        ax.plot(external_radius * cos(theta), external_radius * sin(theta),
                **border_style)
        ax.plot(internal_radius * cos(theta), internal_radius * sin(theta),
                **border_style)

        ticks_r = external_radius * array([1, 1 + ticks_length])
        ticks_label_r = external_radius * (1 + 3 * ticks_length)
        for tick in ticks:
            theta = tick[0]
            ax.plot(ticks_r * cos(theta), ticks_r * sin(theta), **border_style)
            ax.text(ticks_label_r * cos(theta),
                    ticks_label_r * sin(theta),
                    tick[1],
                    color=border_style['color'],
                    ha='center',
                    va='center')

    if bckgrnd_color != None:
        ax.add_collection(
            PatchCollection([Circle((0, 0), radius=bckgrnd_radius)],
                            facecolor=bckgrnd_color,
                            alpha=bckgrnd_alpha,
                            zorder=0))

    ax.axis('equal')
    ax.axis('off')
Beispiel #8
0
def _plot_legend(pos, colors, axis, bads, outlines='skirt'):
    """Helper function to plot color/channel legends for butterfly plots
    with spatial colors"""
    from mpl_toolkits.axes_grid.inset_locator import inset_axes
    bbox = axis.get_window_extent()  # Determine the correct size.
    ratio = bbox.width / bbox.height
    ax = inset_axes(axis, width=str(30 / ratio) + '%', height='30%', loc=2)
    pos, outlines = _check_outlines(pos, outlines, None)
    pos_x, pos_y = _prepare_topomap(pos, ax)
    ax.scatter(pos_x, pos_y, color=colors, s=25, marker='.', zorder=0)
    for idx in bads:
        ax.scatter(pos_x[idx],
                   pos_y[idx],
                   s=5,
                   marker='.',
                   color='w',
                   zorder=1)

    if isinstance(outlines, dict):
        outlines_ = dict([(k, v) for k, v in outlines.items()
                          if k not in ['patch', 'autoshrink']])
        for k, (x, y) in outlines_.items():
            if 'mask' in k:
                continue
            ax.plot(x, y, color='k', linewidth=1)
def plot_obs_pred_sad(datasets, data_dir='./data/', radius=2):
    """Multiple obs-predicted plotter"""
    fig = plt.figure()
    num_datasets = len(datasets)
    rows = (3 if num_datasets in (5, 6) else 2)
    for i, dataset in enumerate(datasets):
        obs_pred_data = import_obs_pred_data(data_dir + dataset + '_obs_pred.csv') 
        site = ((obs_pred_data["site"]))
        obs = ((obs_pred_data["obs"]))
        pred = ((obs_pred_data["pred"]))
        
        axis_min = 0.5 * min(obs)
        axis_max = 2 * max(obs)
        ax = fig.add_subplot(rows,2,i+1)
        macroecotools.plot_color_by_pt_dens(pred, obs, radius, loglog=1, 
                                            plot_obj=plt.subplot(rows,2,i+1))      
        plt.plot([axis_min, axis_max],[axis_min, axis_max], 'k-')
        plt.xlim(axis_min, axis_max)
        plt.ylim(axis_min, axis_max)
        plt.subplots_adjust(left=0.2, bottom=0.12, right=0.8, top=0.92, 
                            wspace=0.29, hspace=0.21)  
        
        # Create inset for histogram of site level r^2 values
        axins = inset_axes(ax, width="30%", height="30%", loc=4)
        hist_mete_r2(site, np.log10(obs), np.log10(pred))
        plt.setp(axins, xticks=[], yticks=[])
        
    plt.savefig('obs_pred_plots.png', dpi=400, bbox_inches = 'tight', pad_inches=0)
Beispiel #10
0
def plot_sub_boxes(ax, name=None):

    #Plot subboxes
    bbox_to_anchor = (-0.02, -0.08, 1, 0.95)
    if name == 'lstm':
        bbox_to_anchor = (-0.02, -0.28, 1, 0.95)
    subaxes = inset_axes(ax,
                         width='50%',
                         height='30%',
                         bbox_to_anchor=bbox_to_anchor,
                         bbox_transform=ax.transAxes,
                         loc='upper right')
    plts = ax.lines
    #subaxes.set_ylim(bottom=0.85, top=0.95)
    for line in plts:
        x = line.get_xdata()
        y = line.get_ydata()
        half = len(x) * 3 // 4
        subx = x[half:]
        suby = y[half:]
        subaxes.plot(subx,
                     suby,
                     color=line.get_color(),
                     marker=line.get_marker(),
                     markerfacecolor='none',
                     linewidth=1.5)
    subaxes.set_ylim(bottom=subaxes.get_ylim()[0])
def setup_axes(fig, imx_c, imy_c, h):

    grid = axes_grid.Grid(fig, "111",
                          nrows_ncols=(4, 3), #ngrids=11,
                          direction='row', axes_pad=0.02,
                          add_all=True,
                          share_all=False, #False,
                          share_x=False, share_y=False,
                          label_mode='L',
                          axes_class=(pywcsgrid2.Axes, {"header":h}))
    grid.set_aspect(True)



    # colorbar axes
    from mpl_toolkits.axes_grid.inset_locator import inset_axes
    axins = inset_axes(grid[0],
                       width="5%",
                       height="50%",
                       loc=4,
                       )

    axins.axis[:].toggle(all=False)
    axins.axis["left"].toggle(all=True)
    axins.axis["left"].label.set_size(10)

    return grid, axins
def plot_eigenvalue_gaps(
        gaps, 
        xlabel=r"$k$", 
        ylabel=r"$\big|\lambda_{k+1}-\lambda_k\big|$", 
        #ylabel=r"$\lambda_{k}$", 
        output="eigen_gap.pdf",
        colors=['b', 'r', 'g', 'c'],
        legend=[r'$\rho_{1}$', r'$\widehat{\rho}_{2}$'],
        marker=['o', '^', 'v']):
    fig = plt.figure(figsize=(fig_width, fig_height))
    ax = fig.add_subplot(111)
    for i, g in enumerate(gaps):
        xs = range(1, len(g)+1)
        ax.plot(xs, g, color=colors[i], linestyle='-', marker=marker[i],
                linewidth=1.5, markersize=5, label=legend[i], alpha=0.7)
    ax.set_ylabel(ylabel)
    ax.set_xlabel(xlabel)
    ax.set_xlim([1, len(xs)])
    #ax.legend(loc=(0.18,0.6), framealpha=.5, ncol=1)
    ax.legend(loc=0, framealpha=.5, ncol=1)

    #with sns.axes_style("whitegrid"):
    axins = inset_axes(ax, width="50%", height="50%", loc=7, 
                        borderpad=1)
    for i, g in enumerate(gaps):
        axins.plot(xs[2:10], g[2:10], color=colors[i], linestyle='-', 
                       marker=marker[i], linewidth=1.5, markersize=5, 
                       alpha=0.7)
    axins.set_xlim([4,8])
    axins.set_xticks([4,5,6,7,8])
    #axins.set_yticks([])
    #axins.set_ylim([0,0.006])

    fig.savefig(output, bbox_inches='tight')
Beispiel #13
0
def plot_potential(ax, lfp, max_val, title):
    norm = cm.colors.Normalize(vmax=max_val, vmin=-max_val, clip=False)
    im = plt.imshow(
        lfp[::-1],
        aspect='auto',
        norm=norm,
        interpolation='nearest',
        cmap=plt.cm.PRGn)

    # plt.xticks(np.arange(3000, 5000, 1000), np.arange(300, 500, 100))
    # plt.ylabel('Electrode depth ($\mu$m)')
    # plt.xlabel('Time (ms)')
    plt.title(title, fontweight="bold", fontsize=12)
    # plt.xlim(xmin=2500, xmax=4500)
    # plt.colorbar(extend='both')
    plt.gca().set_yticks(np.arange(28))
    plt.gca().set_yticklabels(np.arange(1, 29))
    for label in plt.gca().yaxis.get_ticklabels()[::2]:
        label.set_visible(False)
    cbaxes = inset_axes(ax,
                        width="40%",  # width = 10% of parent_bbox width
                        height="3%",  # height : 50%
                        loc=1, borderpad=1)
    cbar = plt.colorbar(
        cax=cbaxes,
        ticks=[-max_val,
               0.,
               max_val],
        orientation='horizontal',
        format='%.2f')
    cbar.ax.set_xticklabels(
        [round(-max_val, 2), str('0 $\mu V$'), round(max_val, 2)])
    return ax, im
def plot_gap(infile="experiments_data2/energy_synapse_gap.csv", 
             output="gap.pdf", 
             xlabel="$k$", 
             ylabel1=r"$g_k-\left( g_{k+1} - \sigma_{k+1} \right)$", 
             ylabel2=r"$J_k$"):
    df = pd.read_csv(infile, dtype=float)
    fig = plt.figure(figsize=(fig_width, fig_height))
    # plot gaps
    ax = fig.add_subplot(111)
    xs = range(1,len(df["gap"].values)+1)
    #ax.errorbar(xs, df["gap"].values, yerr=df["var"].values, color="b",
    #            linestyle='-', marker="o", markersize=5, elinewidth=.5,
    #            capthick=0.5, linewidth=1.5, barsabove=False)
    ax.plot(xs, df["gap2"].values, color="b", linestyle="-", linewidth=1.5,
                marker="o", markersize=5)
    ax.plot(xs, [0]*len(xs), linestyle='--', color='k')
    ax.set_xlim([1, len(xs)])
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel1)
    #with sns.axes_style("whitegrid"):
    axins = inset_axes(ax, width="50%", height="50%", loc=5, 
                        borderpad=1)
    axins.plot(xs[4:10], df["gap2"].values[4:10], 
                   color='b', linestyle='-', 
                   marker='o', linewidth=1.5, markersize=5, 
                   alpha=0.7)
    axins.set_xticks([5,6,7,8,9])
    axins.set_yticks([])
    fig.savefig(output, bbox_inches='tight')
Beispiel #15
0
def plot_kernel_response(lower_limit, upper_limit, vmag_limit, img, data,
                         stars, outputfile):
    fig = plt.figure()

    ax = fig.add_subplot(1, 1, 1)
    ax.set_yscale('log')

    # draw visibility limits
    x = np.linspace(-5 + stars.vmag.min(), stars.vmag.max() + 5, 20)
    y1 = 10**(x * lower_limit[0] + lower_limit[1])
    y2 = 10**(x * upper_limit[0] + upper_limit[1])

    ax.plot(x, y1, c='red', label='lower limit')
    ax.plot(x, y2, c='green', label='upper limit')

    stars.plot.scatter(
        x='vmag',
        y='response',
        c=stars.visible.values,
        ax=ax,
        cmap=plt.cm.RdYlGn,
        vmin=0,
        vmax=1,
        label='Kernel Response',
    )
    ax.set_xlim((-1, float(data['vmaglimit']) + 0.5))
    ax.set_ylim(10**(lower_limit[0] * vmag_limit + lower_limit[1] - 1),
                10**(-upper_limit[0] + upper_limit[1]))

    ax.set_ylabel('Kernel Response')
    ax.set_xlabel('Star Magnitude')

    ax_in = inset_axes(ax, width='40%', height='40%', loc='lower left')

    vmin = np.nanpercentile(img, 0.5)
    vmax = np.nanpercentile(img, 99.5)
    ax_in.imshow(img, cmap='gray', vmin=vmin, vmax=vmax)

    stars.plot.scatter(
        x='x',
        y='y',
        c='visible',
        cmap='RdYlGn',
        vmin=0,
        vmax=1,
        s=3,
        colorbar=False,
        ax=ax_in,
    )
    ax_in.get_xaxis().set_visible(False)
    ax_in.get_yaxis().set_visible(False)

    leg = ax.legend(loc='lower right')
    leg.legendHandles[2].set_color('yellow')

    fig.tight_layout(pad=0)
    fig.savefig(outputfile, dpi=300)

    plt.close('all')
Beispiel #16
0
def plot_spectrogram(X, param, ax, colorbar = False, title = 'Spectrogram', dB= True, freqscale = 'log', dBMax = None, scaling = 'density', **kwargs):
    # TODO: correct t axis scala
    """
    plot the spectrogram of a STFT
    """
    sR = param['sR']
    # PSD
    PSD, freq, t_i =  stft_PSD(X, param, scaling = scaling, **kwargs)
    if dB:
        Z = 10*np.log10(PSD) - 20*np.log10(2e-5)
    else:
        Z = PSD
    # tempo e frequenza per questo plot é ai bordi
    df, __ = frequency_resolution(param['N'],sR)
    tR = param['R']/sR
    t = np.hstack([t_i[0]-tR/2, t_i + tR/2])
    freq = np.hstack([ freq[0]-df/2, freq + df/2])
    X , Y = np.meshgrid(t , freq)
    
    # plotting
    ax.set_title(title, fontsize = 10)
    #cmap = brewer2mpl.get_map('RdPu', 'Sequential', 9).mpl_colormap
    colormap=['#fff7f3','#fde0dd','#fcc5c0','#fa9fb5','#f768a1','#dd3497','#ae017e','#7a0177','#49006a']
    cmap=LinearSegmentedColormap.from_list('YeOrRe',colormap)
    
    #cmap=LinearSegmentedColormap('RdPu',cmap)
    if dBMax==None:
        norm = matplotlib.colors.Normalize(vmin = 0)
    else:
        norm = matplotlib.colors.Normalize(vmin = 0, vmax=dBMax)
    # np.round(np.max(ZdB)-60 ,-1), vmax = np.round(np.max(ZdB)+5,-1), clip = False)
    spect = ax.pcolormesh(X, Y, np.transpose(Z), norm=norm, cmap = cmap)
    #legenda
    if colorbar:
        axcolorbar = inset_axes(ax,
                width="2.5%", # width = 10% of parent_bbox width
                height="100%", # height : 50%
                loc='upper left',
                bbox_to_anchor=(1.01, 0., 1, 1),
                bbox_transform=ax.transAxes,
                borderpad=0,
                )
        axcolorbar.tick_params(axis='both', which='both', labelsize=8)
        ax.figure.colorbar(spect, cax = axcolorbar)
    #
    if freqscale =='log':
        ax.set_yscale('log')
    else:
        ax.set_yscale('linear')
    ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())
    ax.grid(which= 'both' ,ls="-", linewidth=0.15, color='#aaaaaa', alpha=0.3)
    ax.set_xlim(t.min(),t.max())
    ax.set_ylim(freq.min(),freq.max())
    if not colorbar:
        return(spect)
Beispiel #17
0
def draw_latent_scores(ax,
                       scores,
                       tau,
                       x,
                       y,
                       axis_size,
                       max_abs_lim=2.5,
                       space=1,
                       scatter_kwds=None,
                       **kwargs):

    positions = [(x, y), (x + axis_size + space, y),
                 (x, y + axis_size + space)]

    axes = []
    for i, (x_, y_) in enumerate(positions):
        ia = inset_axes(ax,
                        width="100%",
                        height="100%",
                        bbox_to_anchor=(x_, y_, axis_size, axis_size),
                        bbox_transform=ax.transData,
                        borderpad=0,
                        loc=3)
        ia.set_xticks([])
        ia.set_yticks([])

        axes.append(ia)

    scatter_kwds = scatter_kwds or dict()
    scatter_kwds.setdefault("c", tau)
    scatter_kwds.setdefault("s", 5)

    axes[0].scatter(scores.T[0], scores.T[1], **scatter_kwds)
    axes[1].scatter(scores.T[2], scores.T[1], **scatter_kwds)
    axes[2].scatter(scores.T[0], scores.T[2], **scatter_kwds)

    label_kwds = dict(fontsize=10)
    axes[0].set_xlabel(r"$\mathbf{S}_1$", **label_kwds)
    axes[0].set_ylabel(r"$\mathbf{S}_2$", **label_kwds)

    axes[1].set_xlabel(r"$\mathbf{S}_3$", **label_kwds)
    axes[2].set_ylabel(r"$\mathbf{S}_3$", **label_kwds)

    padding = 0.20
    for ax in axes:
        xlim = ax.get_xlim()
        ylim = ax.get_ylim()

        xptp = np.ptp(xlim) * (1 + padding)
        yptp = np.ptp(ylim) * (1 + padding)

        ax.set_xlim(np.mean(xlim) - 0.5 * xptp, np.mean(xlim) + 0.5 * xptp)
        ax.set_ylim(np.mean(ylim) - 0.5 * yptp, np.mean(ylim) + 0.5 * yptp)

    return axes
def plot_divergence_boxplot_as_inset_axes(divergence, cdf, curr_axes, orig, samplers):
    box_plot_loc = 4 if cdf else 1
    bbox_anchor = (-.02, .12, 1, 1) if cdf else (-.02, -.09, 1, 1)
    in_axes = ins_loc.inset_axes(curr_axes, width="40%", # width = 40% of parent_bbox
        height="40%", # height : 40% of parent box
        loc=box_plot_loc, 
        bbox_to_anchor=bbox_anchor, 
        bbox_transform=curr_axes.transAxes, 
        borderpad=0)
    plot_divergence_boxplot(samplers, orig, divergence, ax=in_axes, notch=1, grid=False)
    return in_axes
def plot_basics(data, data_inst, fig, units):
    from powerlaw import plot_pdf, Fit, pdf
    annotate_coord = (-.4, .95)
    ax1 = fig.add_subplot(n_graphs,n_data,data_inst)
    x, y = pdf(data, linear_bins=True)
    ind = y>0
    y = y[ind]
    x = x[:-1]
    x = x[ind]
    ax1.scatter(x, y, color='r', s=.5)
    plot_pdf(data[data>0], ax=ax1, color='b', linewidth=2)
    from pylab import setp
    setp( ax1.get_xticklabels(), visible=False)

    if data_inst==1:
        ax1.annotate("A", annotate_coord, xycoords="axes fraction", fontproperties=panel_label_font)

    
    from mpl_toolkits.axes_grid.inset_locator import inset_axes
    ax1in = inset_axes(ax1, width = "30%", height = "30%", loc=3)
    ax1in.hist(data, normed=True, color='b')
    ax1in.set_xticks([])
    ax1in.set_yticks([])

    
    ax2 = fig.add_subplot(n_graphs,n_data,n_data+data_inst, sharex=ax1)
    plot_pdf(data, ax=ax2, color='b', linewidth=2)
    fit = Fit(data, xmin=1, discrete=True)
    fit.power_law.plot_pdf(ax=ax2, linestyle=':', color='g')
    p = fit.power_law.pdf()

    ax2.set_xlim(ax1.get_xlim())
    
    fit = Fit(data, discrete=True)
    fit.power_law.plot_pdf(ax=ax2, linestyle='--', color='g')
    from pylab import setp
    setp( ax2.get_xticklabels(), visible=False)

    if data_inst==1:
       ax2.annotate("B", annotate_coord, xycoords="axes fraction", fontproperties=panel_label_font)        
       ax2.set_ylabel(u"p(X)")# (10^n)")
        
    ax3 = fig.add_subplot(n_graphs,n_data,n_data*2+data_inst)#, sharex=ax1)#, sharey=ax2)
    fit.power_law.plot_pdf(ax=ax3, linestyle='--', color='g')
    fit.exponential.plot_pdf(ax=ax3, linestyle='--', color='r')
    fit.plot_pdf(ax=ax3, color='b', linewidth=2)
    
    ax3.set_ylim(ax2.get_ylim())
    ax3.set_xlim(ax1.get_xlim())
    
    if data_inst==1:
        ax3.annotate("C", annotate_coord, xycoords="axes fraction", fontproperties=panel_label_font)

    ax3.set_xlabel(units)
Beispiel #20
0
def plotmulticlus(cls, sizex, sizey):

    ncl = len(cls)

    fig, ax = plt.subplots(ncl, 2, figsize=[sizex, sizey], squeeze=False)
    plt.subplots_adjust(hspace=0.3, wspace=0.3)

    ni = 0
    for i in range(ncl):
        cl = cls[i]

        # Left column: cluster distribution
        a0 = ax[i][0]
        d = pd.DataFrame({'clid': range(1, len(cl) + 1), 'n': map(len, cl)})
        a0.scatter(d.iloc[:, 0], d.iloc[:, 1], marker='.', linewidth=0)
        a0.set_xlabel("Cluster ID")
        a0.set_ylabel("# Elements")
        ia0 = inset_axes(a0, width=1.3, height=0.9)
        ia0.set_xscale("log")
        ia0.set_yscale("log")
        ia0.set_xlabel("log Cluster ID")
        ia0.set_ylabel("log #Elements")
        ia0.scatter(d.iloc[:, 0], d.iloc[:, 1], marker='.', linewidth=0)

        # Right column: neighbor distribution
        a1 = ax[i][1]
        d2 = pd.DataFrame({
            "clsize": d.n.groupby(d.n).unique(),
            "n": d.n.groupby(d.n).sum()
        })
        a1.scatter(d2.iloc[:, 0], d2.iloc[:, 1], marker='.', linewidth=0)
        a1.set_xlabel("Cluster Size")
        a1.set_ylabel("# Elements")
        ia1 = inset_axes(a1, width=1.3, height=0.9)
        ia1.set_xscale("log")
        ia1.set_yscale("log")
        ia1.set_xlabel("log Cluster Size")
        ia1.set_ylabel("log # Elements")
        ia1.scatter(d.iloc[:, 0], d.iloc[:, 1], marker='.', linewidth=0)
    return
Beispiel #21
0
def plot_emp_vs_sim(study_id, data_dir = './out_files/', feas_type = 'partition', ax = None, inset = True, legend = False):
    """Plot of empirical and simulated mean-variance relationships for a given data set
    
    to help visually illustrate our results.
    Includes scatter plot of empirical data and its fitted line, scatter plot and fitted line for one
    set of simulated s_ij^2, 95 quantiles of s_ij^2 for each s_i^2 value, and the distribution of b in an inset.
    
    Input: 
    study_id - ID of the data set of interest, in the form listed in Appendix A. 
    """
    if not ax:
        fig = plt.figure(figsize = (3.5, 3.5))
        ax = plt.subplot(111)
    var_dat = get_var_sample_file(data_dir + 'taylor_QN_var_predicted_' + feas_type + '_full.txt')
    var_study = var_dat[var_dat['study'] == study_id]
    sim_var = [var_study[x][5] for x in xrange(len(var_study))] # take the first simulated sequence
    
    b_emp, inter_emp, r, p, std_err = stats.linregress(np.log(var_study['mean']), np.log(var_study['var']))
    b_list = []
    for k in xrange(len(var_study[0]) - 5):
        study_k = [var_study[x][k + 5] for x in xrange(len(var_study))]
        mean_k = [var_study['mean'][p] for p in xrange(len(var_study)) if study_k[p] != 0]
        study_k = [study_k[p] for p in xrange(len(study_k)) if study_k[p] != 0]
        b_k, inter, r, p, std_err = stats.linregress(np.log(mean_k), np.log(study_k))
        if k == 0: b_0, inter_0 = b_k, inter
        b_list.append(b_k)
   
    ax.set_xscale('log')
    ax.set_yscale('log')
    plt.scatter(var_study['mean'], var_study['var'], s = 8, c = 'black', edgecolors='none')
    emp, = plt.plot(var_study['mean'], np.exp(inter_emp) * var_study['mean'] ** b_emp, '-', c = 'black', linewidth=1.5)
    if feas_type == 'partition': plot_col = '#228B22'
    else: plot_col = '#CD69C9'
    plt.scatter(var_study['mean'], sim_var, s = 8, c = plot_col, edgecolors='none')
    sim, = plt.plot(var_study['mean'], np.exp(inter_0) * var_study['mean'] ** b_0, '-', linewidth=1.5, c = plot_col)
    ax.tick_params(axis = 'both', which = 'major', labelsize = 9)
    ax.set_xlabel('Mean', labelpad = 4, size = 10)
    ax.set_ylabel('Variance', labelpad = 4, size = 10)
    if legend:
        plt.legend([emp, sim], ['Empirical', (feas_type.title()) + 's'], loc = 4, prop = {'size': 8}) 
    if inset:
        axins = inset_axes(ax, width="30%", height="30%", loc=2)
        cov_factor = 0.2
        xs = np.linspace(0.9 * min(b_list + [b_emp]), 1.1 * max(b_list + [b_emp]), 200)
        dens_b = comp_dens(b_list, cov_factor)
        b_dens, = plt.plot(xs, dens_b(xs), c = plot_col, linewidth=1.5)
        ymax = 1.1 * max(dens_b(xs))
        plt.plot((b_emp, b_emp), (0, ymax), 'k-', linewidth = 1.5)
        plt.tick_params(axis = 'y', which = 'major', left = 'off', right = 'off', labelleft = 'off')
        plt.tick_params(axis = 'x', which = 'major', top = 'off', bottom = 'off', labelbottom = 'off')
    return ax
def plotSaturation(title, array, parameters, n, subplot=True, x_reverse=False, diagonal=False, plot_legend=False):

    fig = plt.figure(n)
    ax = fig.add_subplot(111)
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')
    cm = plt.get_cmap('gist_rainbow')
    ax.set_color_cycle([cm(1. * i / len(parameters)) for i in range(len(parameters))])

    ax.plot(array[:, 0], array[:, 1:], linewidth=2.0)
    # ax.plot(array, linewidth=2.0)

    # ax.set_title(title+" VS Sample Number", fontname="Times New Roman")
    # ax.set_xlabel("Number of H3K4me3 Chip-Seq Sample", fontname="Times New Roman")
    # ax.set_ylabel(title, fontname="Times New Roman")

    ax.set_title(title, fontname="Times New Roman")
    ax.set_xlabel("Cutoff", fontname="Times New Roman")
    ax.set_ylabel("Coverage", fontname="Times New Roman")

    if plot_legend:
        legend = ax.legend(parameters, loc='center right', bbox_to_anchor=(1.3, 0.5))

    if subplot:
        inside_ax = inset_axes(ax,
                                width="35%",  # width = 30% of parent_bbox
                                height="35%",  # height : 1 inch
                                loc=5)
        inside_ax.set_color_cycle([cm(1. * i / len(parameters)) for i in range(0, len(parameters))])

        if x_reverse:
            inside_ax.set_xlim(ax.get_xlim()[::-1])

        inside_ax.plot(array[20:, 0], array[20:, 1:], linewidth=2.0)

        inside_ax.tick_params(labelsize=10)

    if x_reverse:
        ax.set_xlim(ax.get_xlim()[::-1])

    if diagonal:
        ax.plot(array[:, 0], array[:, 0], linewidth=2.0, color="orange")

    if plot_legend:
        fig.savefig("./pictures/"+title, dpi=600, facecolor='w', edgecolor='w',
                    orientation='portrait', bbox_extra_artists=(legend,), bbox_inches='tight')
    else:
        fig.savefig("./pictures/" + title, dpi=600, facecolor='w', edgecolor='w',
                    orientation='portrait')
Beispiel #23
0
def plot_morp_ele(ax1, src_pos, ele_pos, pot, time_pt):
    """Plots the morphology midpoints and the electrode positions"""
    ax = plt.subplot(121, aspect='equal')
    plt.scatter(src_pos[:, 0], src_pos[:, 1],
                marker='.', alpha=0.7, color='k', s=0.6)
    plt.scatter(ele_pos[:, 0], ele_pos[:, 1],
                marker='x', alpha=0.8, color='r', s=0.9)
    # for tx in range(len(ele_pos[:,0])):
    #    plt.text(ele_pos[tx, 0], ele_pos[tx, 1], str(tx))
    ele_1 = 152
    ele_2 = 148
    plt.scatter(ele_pos[ele_1, 0], ele_pos[ele_1, 1],
                marker='s', color='r', s=14.)
    plt.scatter(ele_pos[ele_2, 0], ele_pos[ele_2, 1],
                marker='s', color='b', s=14.)
    plt.xlabel('X ($\mu$m)')
    plt.ylabel('Y ($\mu$m)')
    plt.title('Morphology and electrodes')
    plt.ylim(ymin=-2150, ymax=550)
    plt.xlim(xmin=-450, xmax=450)

    cbaxes = inset_axes(ax,
                        width="50%",  # width = 10% of parent_bbox width
                        height="17%",  # height : 50%
                        loc=4, borderpad=2.2)

    plt.plot(np.arange(6000), pot[ele_1, :], color='r', linewidth=0.5)
    plt.plot(np.arange(6000), pot[ele_2, :], color='b', linewidth=0.5)

    dummy_line = np.arange(-0.5, 0.5, 0.1)
    plt.plot(np.zeros_like(dummy_line) + time_pt,
             dummy_line, color='black', linewidth=1)

    # ax=plt.gca()
    # ax.arrow(time_pt, -0.1, 0., 0.075, head_width=0.05,
    #          head_length=0.05, width=0.1,
    #          length_includes_head=True, fc='k', ec='k')
    plt.xlim((2750, 3500))  # 4250))
    # plt.xticks(np.arange(3000, 5000, 1000), np.arange(300, 500, 100))
    plt.xticks(np.arange(2750, 3750, 250), np.arange(275, 375, 25))
    plt.ylim((-0.2, 0.12))
    plt.yticks(np.arange(-0.2, 0.1, 0.1), np.arange(-0.2, 0.1, 0.1))
    ax = plt.gca()
    ax.get_yaxis().tick_right()  # set_tick_params(direction='in')

    # inset_plt = plt.plot(cax=cbaxes,
    # cbar = plt.colorbar(cax=cbaxes, ticks=[-lfp_max,0.,lfp_max], orientation='horizontal', format='%.2f')
    # cbar.ax.set_xticklabels([round(-lfp_max,2),str('0 $\mu V$'),round(lfp_max,2)])

    return ax1
Beispiel #24
0
def doDistribution(players):
	Ytabu = np.load("ipad_tabu_best.npy")
	YRandom = np.load("humain_random.npy")
	Yhumain = [i["score"] for i in players]

	ntabu, binstabu, patches = plt.hist(Ytabu,bins=np.arange(20,80,0.5), cumulative=True, histtype="step",normed=True)
	nhumain, binshumain, patches = plt.hist(Yhumain,bins=np.arange(20,80,0.5), cumulative=True, histtype="step",normed=True)
	nrandom, binsrandom, patches = plt.hist(YRandom,bins=np.arange(20,200,1), cumulative=True, histtype="step",normed=True)

	plt.clf()

	fig = plt.figure(figsize=(10,5))


	plt.hist(Ytabu,bins=5,normed=True, alpha=1.0,facecolor='#FF9600',edgecolor="white",label="Tabou")
	plt.hist(Yhumain,bins=5,normed=True, alpha=1.0,facecolor='#0074C0',edgecolor="white",label="Humain")
	plt.hist(YRandom,bins=20,normed=True, alpha=1.0,facecolor='gray',edgecolor="white",label=r"Al\'eatoire")


	ax = plt.gca()
	ax.set_xlabel("Distance",fontsize=25)
	ax.set_ylabel(r"Distribution",fontsize=25)
	leg =plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
	           ncol=34, mode="expand", borderaxespad=0.,fontsize=20)
	frame = leg.get_frame()
	frame.set_facecolor('white')
	frame.set_edgecolor('none')
	h=0.2
	# ax.set_yticks(np.arange(0.0,1.0+h,h))
	from mpl_toolkits.axes_grid.inset_locator import inset_axes
	inset_axes = inset_axes(ax, 
	                    width="50%", # width = 30% of parent_bbox
	                    height=2.0, # height : 1 inch
	                    loc=1)

	plt.plot(np.arange(20,80-0.5,0.5),ntabu,linewidth=3,color="#FF9600")
	plt.plot(np.arange(20,80-0.5,0.5),nhumain,linewidth=3,color="#0074C0",alpha=1.0)

	sigma = np.std(YRandom)
	mu = np.mean(YRandom)


	print(norm.cdf(np.mean(Yhumain),mu,sigma))
	plt.xlim([30,80])
	plt.ylim([-0.001,1.001])
	plt.yticks(np.arange(0.0,1.1,0.3))
	plt.ylabel("Cumulative",fontsize=20)

	plt.savefig("../Pres_symposium/figures/distribution_human.pdf",bbox_inches='tight')
Beispiel #25
0
def place_inset_ax_in_data_coordinates(ax, bbox):
    """Return an ax inset in the given ax at the given bbox in
    data coordinates (bottom, left, width, height)"""

    bottom, left, width, height = bbox
    pixels_data_00 = ax.transData.transform([0, 0])
    pixels_data_wh = ax.transData.transform([width, height])
    iwidth, iheight = (pixels_data_wh - pixels_data_00) / ax.figure.dpi
    return inset_axes(
        ax,
        iwidth,
        iheight,
        loc=10,  # means "center"
        bbox_to_anchor=[bottom, left, width, height],
        bbox_transform=ax.transData)
Beispiel #26
0
def _plot_legend(pos, colors, axis, bads, outlines):
    """Helper function to plot color/channel legends for butterfly plots
    with spatial colors"""
    from mpl_toolkits.axes_grid.inset_locator import inset_axes
    bbox = axis.get_window_extent()  # Determine the correct size.
    ratio = bbox.width / bbox.height
    ax = inset_axes(axis, width=str(30 / ratio) + '%', height='30%', loc=2)
    pos_x, pos_y = _prepare_topomap(pos, ax)
    ax.scatter(pos_x, pos_y, color=colors, s=25, marker='.', zorder=1)
    for idx in bads:
        ax.scatter(pos_x[idx], pos_y[idx], s=5, marker='.', color='w',
                   zorder=1)

    if isinstance(outlines, dict):
        _draw_outlines(ax, outlines)
Beispiel #27
0
def _plot_legend(pos, colors, axis, bads, outlines):
    """Helper function to plot color/channel legends for butterfly plots
    with spatial colors"""
    from mpl_toolkits.axes_grid.inset_locator import inset_axes
    bbox = axis.get_window_extent()  # Determine the correct size.
    ratio = bbox.width / bbox.height
    ax = inset_axes(axis, width=str(30 / ratio) + '%', height='30%', loc=2)
    pos_x, pos_y = _prepare_topomap(pos, ax)
    ax.scatter(pos_x, pos_y, color=colors, s=25, marker='.', zorder=1)
    for idx in bads:
        ax.scatter(pos_x[idx], pos_y[idx], s=5, marker='.', color='w',
                   zorder=1)

    if isinstance(outlines, dict):
        _draw_outlines(ax, outlines)
Beispiel #28
0
def spatial_decay(M, field='E', indices=None):
    from mpl_toolkits.axes_grid.inset_locator import inset_axes
    import stephane.vortex.track as track

    fields, names, vmin, vmax, labels, units = std_fields()
    j = fields.index(field)

    Z = np.nanmean(getattr(M, field)[..., indices], axis=2)

    X, Y = [], []
    for i in indices:
        tup = track.positions(M, i, field=field, indices=indices, step=1, sigma=10.)
        X.append(tup[1])
        Y.append(tup[3])
    X0, Y0 = np.nanmean(X), np.nanmean(Y)

    R, Theta = Smath.cart2pol(M.x - X0, M.y - Y0)
    R0 = M.param.Diameter

    Z_flat = np.ndarray.flatten(Z)
    R_flat = np.ndarray.flatten(R)
    Theta_flat = np.ndarray.flatten(Theta)

    phi = np.pi / 2
    C = np.mod((Theta_flat + phi + np.pi) / 2 / np.pi, 1)
    cmap = matplotlib.cm.hot
    color = [matplotlib.colors.rgb2hex(cmap(c)[:3]) for c in C]

    fig, ax2 = graphes.set_fig(1, subplot=122)
    fig.set_size_inches(20, 6)
    ax2.scatter(R_flat, Z_flat, marker='o', facecolor=color, alpha=0.3, lw=0, cmap=cmap)

    Rth = np.arange(10 ** 1, 10 ** 2, 1.)
    # graphes.graphloglog(Rth, 10 ** 5 * (Rth / R0) ** -3.2, label='k--')
    # graphes.graphloglog(Rth, 5 * 10 ** 4 * (Rth / R0) ** -4.5, label='k--')
    graphes.set_axis(10 ** 0, 10 ** 2, 10 ** 2, 8 * 10 ** 4)
    figs = graphes.legende('$R$ (mm)', 'Energy (mm$^2$/s$^{2}$)', 'Spatial decay')

    fig, ax1 = graphes.set_fig(1, subplot=121)
    graphes.color_plot(M.x, M.y, Z, fignum=1, vmin=0, vmax=40000, subplot=121)
    graphes.colorbar(label=names[j] + ' (' + units[j] + ')')
    figs.update(graphes.legende('X (mm)', 'Y (mm)', 'Time averaged ' + field, cplot=True))

    inset_ax = inset_axes(ax2, height="50%", width="50%", loc=3)
    inset_ax.pcolormesh(M.x / 10 - 10, M.y / 10 - 10, Theta, cmap=cmap)
    inset_ax.axis('off')

    return figs
Beispiel #29
0
def fig_power(po,
              pos,
              sig_loc,
              start=400,
              stop=405,
              Title='',
              asteriks=[90, 200]):
    global freq
    from mpl_toolkits.axes_grid.inset_locator import inset_axes
    ax1 = py.subplot(gs[pos[2]:pos[3], pos[0]:pos[1]])
    set_axis(ax1, -0.1, 1.05, letter=po)
    labels = ['Olf. bulb', 'Thalamus', 'Visual ctrx']

    for i in range(2, -1, -1):
        sig_loc[i] = notch_filter(sig_loc[i], Fs, np.arange(50, 450, 50))
        freq, sp = welch(sig_loc[i], Fs, nperseg=1 * Fs)
        ax1.plot(freq, sp, lw=2, label=labels[i])
    py.legend(loc=2, fontsize=15)
    ax1.text(asteriks[0], asteriks[1], '*', fontsize=20)
    ax1.text(160, 440, '?', fontsize=20)
    py.xlim(0, 260)
    py.ylim(0, 500)
    py.ylabel('power ($mv^2$)')
    ax1.spines['right'].set_visible(False)
    ax1.spines['top'].set_visible(False)
    py.xlabel('Frequency (Hz)')
    if po != 'B3':
        inset_axes = inset_axes(ax1, width="23%", height=1.0, loc=1)
        for n in range(3, sig_loc.shape[0]):
            sig_loc[n] = notch_filter(sig_loc[n], Fs, np.arange(50, 450, 50))
            freq, sp = welch(sig_loc[n], Fs, nperseg=10 * Fs)
            py.plot(freq, sp, lw=0.7, color='green')
        py.ylim(0, 220)
        py.xlim(0, 260)
        py.xticks(fontsize=11)
        py.yticks(fontsize=11)
        # py.ylim(.1, 10e4)
        # py.yscale('log')
        # py.text(200,100, 'Olf. bulb propofol')
        py.xlabel('Frequency (Hz)')
    if po == 'B1':
        ax1.legend(loc='lower right',
                   bbox_to_anchor=(1.2, 1.1),
                   ncol=3,
                   frameon=True,
                   fontsize=15)
Beispiel #30
0
def add_insetimage(ax, height, loc, image):
    im_ax01 = inset_axes(
        ax,
        height=height,  # set height
        width=height,  # and width
        loc=loc,
        #facecolor='b'
    )  # center, you can check the different codes in plt.legend?
    im_ax01.imshow(image)
    #im_ax01.patch.set_facecolor('red')

    im_ax01.axis('off')

    #im_ax01.set_alpha(0.1)
    #im_ax01.set_facecolor('blue')

    return ax
Beispiel #31
0
def plot_eigenvalue_gaps(
        gaps,
        xlabel=r"$k$",
        ylabel=r"$\big|\lambda_{k+1}-\lambda_k\big|$",
        #ylabel=r"$\lambda_{k}$",
        output="eigen_gap.pdf",
        colors=['b', 'r', 'g', 'c'],
        legend=[r'$\rho_{1}$', r'$\widehat{\rho}_{2}$'],
        marker=['o', '^', 'v']):
    fig = plt.figure(figsize=(fig_width, fig_height))
    ax = fig.add_subplot(111)
    for i, g in enumerate(gaps):
        xs = range(1, len(g) + 1)
        ax.plot(xs,
                g,
                color=colors[i],
                linestyle='-',
                marker=marker[i],
                linewidth=1.5,
                markersize=5,
                label=legend[i],
                alpha=0.7)
    ax.set_ylabel(ylabel)
    ax.set_xlabel(xlabel)
    ax.set_xlim([1, len(xs)])
    #ax.legend(loc=(0.18,0.6), framealpha=.5, ncol=1)
    ax.legend(loc=0, framealpha=.5, ncol=1)

    #with sns.axes_style("whitegrid"):
    axins = inset_axes(ax, width="50%", height="50%", loc=7, borderpad=1)
    for i, g in enumerate(gaps):
        axins.plot(xs[2:10],
                   g[2:10],
                   color=colors[i],
                   linestyle='-',
                   marker=marker[i],
                   linewidth=1.5,
                   markersize=5,
                   alpha=0.7)
    axins.set_xlim([4, 8])
    axins.set_xticks([4, 5, 6, 7, 8])
    #axins.set_yticks([])
    #axins.set_ylim([0,0.006])

    fig.savefig(output, bbox_inches='tight')
Beispiel #32
0
def plot_divergence_boxplot_as_inset_axes(divergence, cdf, curr_axes, orig,
                                          samplers):
    box_plot_loc = 4 if cdf else 1
    bbox_anchor = (-.02, .12, 1, 1) if cdf else (-.02, -.09, 1, 1)
    in_axes = ins_loc.inset_axes(
        curr_axes,
        width="40%",  # width = 40% of parent_bbox
        height="40%",  # height : 40% of parent box
        loc=box_plot_loc,
        bbox_to_anchor=bbox_anchor,
        bbox_transform=curr_axes.transAxes,
        borderpad=0)
    plot_divergence_boxplot(samplers,
                            orig,
                            divergence,
                            ax=in_axes,
                            notch=1,
                            grid=False)
    return in_axes
Beispiel #33
0
def plot_elbow_kernel(
        values,
        xlabel=r"$k$",
        #ylabel=r"$\textnormal{Tr}(Y^\top G \, Y)$",
        ylabel=r"$\log Q_{k+1} - \log Q_{k}$",
        output="elbow.pdf",
        colors=['b', 'r', 'g'],
        legend=[r'$\widehat{\rho}_{\sqrt{7}}$', r'$\rho_{1}$'],
        marker=['o', 's']):
    fig = plt.figure(figsize=(fig_width, fig_height))
    ax = fig.add_subplot(111)
    for i, g in enumerate(values):
        xs = range(1, len(g) + 1)
        ax.plot(xs,
                g,
                color=colors[i],
                linestyle='-',
                marker=marker[i],
                linewidth=1.5,
                markersize=5,
                label=legend[i],
                alpha=0.7)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_xlim([1, 12])
    ax.legend(loc=2, framealpha=.5, ncol=1)

    with sns.axes_style("whitegrid"):
        axins = inset_axes(ax, width="50%", height="50%", loc=1)
        for i, g in enumerate(values):
            axins.plot(xs[2:10],
                       g[2:10],
                       color=colors[i],
                       linestyle='-',
                       marker=marker[i],
                       linewidth=1.5,
                       markersize=5,
                       alpha=0.7)
    #axins.set_xlim([5,12])
    #axins.set_ylim([19.9,20])
    #axins.set_xticks([])
    #axins.set_yticks([])
    fig.savefig(output, bbox_inches='tight')
Beispiel #34
0
    def colorbars(self,
                  cax,
                  pixels=200,
                  orientation='horizontal',
                  vstacked=False):
        """Draws a 3 colorbar legend into the cax axes object."""
        from mpl_toolkits.axes_grid.inset_locator import inset_axes
        cax.set_yticks([])
        cax.set_xticks([])
        cax.patch.set_alpha(0)
        for s in cax.spines.values():
            s.set_visible(False)

        if (orientation == 'vertical') ^ (not vstacked):
            width, height, locs = '100%', '23%', [9, 10, 8]
        else:
            width, height, locs = '25%', '100%', [6, 10, 7]
        axs = [inset_axes(cax, width, height, loc) for loc in locs]
        for i, ax in enumerate(axs):
            if i == 0: fun = lambda a: self.color(a, 0, 0)
            elif i == 1: fun = lambda b: self.color(0, b, 0)
            else: fun = lambda c: self.color(0, 0, c)
            img = np.array(
                [[fun(d) for d in np.linspace(0, self.maxdiff, pixels)]])
            if orientation == 'vertical':
                img = img.transpose(1, 0, 2)
            ax.imshow(img,
                      extent=[0, self.maxdiff, 0, self.maxdiff],
                      origin='lower',
                      aspect='auto',
                      interpolation='bicubic')
            if orientation == 'vertical':
                ax.set_xticks([])
                ax.set_ticks = ax.set_yticks
                ax.set_ticklabels = ax.set_yticklabels
            else:
                ax.set_yticks([])
                ax.set_ticks = ax.set_xticks
                ax.set_ticklabels = ax.set_xticklabels
            ax.set_ticks([0, self.maxdiff])
            ax.set_ticklabels(['same', 'max'])
        cax.subaxes = axs
Beispiel #35
0
def _plot_legend(pos, colors, axis, bads, outlines):
    """Helper function to plot color/channel legends for butterfly plots
    with spatial colors"""
    from mpl_toolkits.axes_grid.inset_locator import inset_axes
    bbox = axis.get_window_extent()  # Determine the correct size.
    ratio = bbox.width / bbox.height
    ax = inset_axes(axis, width=str(30 / ratio) + '%', height='30%', loc=2)
    pos_x, pos_y = _prepare_topomap(pos, ax)
    ax.scatter(pos_x, pos_y, color=colors, s=25, marker='.', zorder=0)
    for idx in bads:
        ax.scatter(pos_x[idx], pos_y[idx], s=5, marker='.', color='w',
                   zorder=1)

    if isinstance(outlines, dict):
        outlines_ = dict([(k, v) for k, v in outlines.items() if k not in
                          ['patch', 'autoshrink']])
        for k, (x, y) in outlines_.items():
            if 'mask' in k:
                continue
            ax.plot(x, y, color='k', linewidth=1)
Beispiel #36
0
def fig_power(po, pos, sig_loc, start=400, stop = 405, Title = '', asteriks=[0,0]):
    global freq
    from mpl_toolkits.axes_grid.inset_locator import inset_axes
    ax1 = py.subplot(gs[pos[2]:pos[3], pos[0]:pos[1]])
    py.title(Title, fontsize=15)
    set_axis(ax1, -0.1, 1.05, letter= po)
    labels= ['Olf. bulb', 'Thalamus', 'Visual ctrx']
    for i in range(2,-1,-1):
        sig_loc[i] = notch_filter(sig_loc[i], Fs, np.arange(50, 450, 50))
        freq, sp = welch(sig_loc[i], Fs, nperseg = 1*Fs)
        ax1.plot(freq, sp, lw=4, label=labels[i])
        # ax1.text(asteriks[0], asteriks[1] , '*', fontsize=20)
        py.arrow(asteriks[0], asteriks[1], 0, -12, length_includes_head=True, clip_on = False,
                 head_width=2, head_length=4)
    # py.ylim(.1, 10e4)
    py.ylim(0,220)
    py.xlim(0, 155)
    py.ylabel('power $mV^2$')
    ax1.spines['right'].set_visible(False)
    ax1.spines['top'].set_visible(False)
    py.xlabel('Frequency (Hz)')
    if po!='B1': 
        inset_axes = inset_axes(ax1, width="23%", height=1.0, loc=1)
        for n in range(3,sig_loc.shape[0]):
            sig_loc[n] = notch_filter(sig_loc[n], Fs, np.arange(50, 450, 50))
            freq, sp = welch(sig_loc[n], Fs, nperseg = 1*Fs)
            py.plot(freq, sp, lw=2, color='green')
        py.ylim(0,220)
        py.xlim(0,155)
        py.xticks(fontsize=11)
        py.yticks(fontsize=11)
    # py.ylim(.1, 10e4)
    # py.yscale('log')
    # py.text(200,100, 'Olf. bulb propofol')
        py.xlabel('Frequency (Hz)')
    if po=='B1': 
        ket = mpatches.Patch(color='green', label='Olf. bulb')
        kx = mpatches.Patch(color='orange', label='Thalamus LGN')
        gam = mpatches.Patch(color='blue', label='Visual cortex')
        ax1.legend(loc='lower right', bbox_to_anchor=(1.2, .7), handles=[ket,kx,gam],
                   ncol=1, frameon = True, fontsize = 15)
Beispiel #37
0
def plot_extracellular(ax, lfp, ele_pos, num_x, num_y, time_pt):
    """Plots the extracellular potentials at a given potentials"""

    lfp *= 1000.
    lfp_max = np.max(np.abs(lfp[:, time_pt]))
    levels = np.linspace(-lfp_max, lfp_max, 16)
    im2 = plt.contourf(ele_pos[:, 0].reshape(num_x, num_y),
                       ele_pos[:, 1].reshape(num_x, num_y),
                       lfp[:, time_pt].reshape(num_x, num_y),
                       levels=levels,
                       cmap=plt.cm.PRGn)

    # cb = plt.colorbar(im2, extend='both')
    # tick_locator = ticker.MaxNLocator(nbins=9, trim=False, prune=None)
    # #tick_locator.bin_boundaries(-lfp_max, lfp_max)
    # cb.locator = tick_locator
    # #cb.ax.yaxis.set_major_locator(ticker.AutoLocator())
    # cb.update_ticks()
    # cb.ax.set_title('$\mu$V')

    plt.title('Time=' + str(time_pt / 10.) + ' ms')
    plt.xlabel('X ($\mu$m)')
    plt.ylabel('Y ($\mu$m)')
    plt.ylim(ymin=-2150, ymax=550)
    plt.xlim(xmin=-450, xmax=450)
    cbaxes = inset_axes(
        ax,
        width="50%",  # width = 10% of parent_bbox width
        height="2%",  # height : 50%
        loc=1,
        borderpad=1.5)
    cbar = plt.colorbar(cax=cbaxes,
                        ticks=[-lfp_max, 0., lfp_max],
                        orientation='horizontal',
                        format='%.2f')
    cbar.ax.set_xticklabels(
        [round(-lfp_max, 2),
         str('0 $\mu V$'),
         round(lfp_max, 2)])
    return ax
Beispiel #38
0
def plot_eigenvalue_gaps(
        gaps,
        xlabel=r"$k$",
        ylabel=r"$\lambda_{k+1}-\lambda_k$",
        output="eigen_gap.pdf",
        colors=['b', 'r', 'g', 'c'],
        legend=[r'$\rho_{1}$', r'$\rho_{0.5}$', r'$\rho_{0.25}$'],
        marker=['o', '^', 'v']):
    fig = plt.figure(figsize=(fig_width, fig_height))
    ax = fig.add_subplot(111)
    for i, g in enumerate(gaps):
        xs = range(1, len(g) + 1)
        ax.plot(xs,
                g,
                color=colors[i],
                linestyle='-',
                marker=marker[i],
                linewidth=1.5,
                markersize=5,
                label=legend[i],
                alpha=0.7)
    ax.set_ylabel(r'$\lambda_{k+1} - \lambda_k$')
    ax.set_xlabel(r'$k$')
    ax.set_xlim([1, len(xs)])
    ax.legend(loc=2, framealpha=.5, ncol=1)

    axins = inset_axes(ax, width="60%", height="60%", loc=1, borderpad=0.5)
    for i, g in enumerate(gaps):
        axins.plot(xs,
                   g,
                   color=colors[i],
                   linestyle='-',
                   marker=marker[i],
                   linewidth=1.5,
                   markersize=5,
                   alpha=0.7)
    axins.set_xlim([5, 12])
    axins.set_ylim([0, 0.006])

    fig.savefig(output, bbox_inches='tight')
Beispiel #39
0
def inset_hist_fig(fig, outer_ax, v, size, loc, ids=None):
    '''
    Inset histogram into the outer_ax at location.

    Params:
      fig       - figure
      outer_ax  - Main axes
      v         - array of values
      size      - percent of parent fig size [width, height]
      loc       - quadrant location

    Return:
      fig - The main figure with inset figure
  '''

    in_axes = inset_axes(outer_ax, width=size[0], height=size[1], loc=loc)

    #in_axes.patch.set_alpha(0.6)

    plot_hist(in_axes, v, bins=200, title=r'Distribution', ids=ids)

    return fig
def add_inset_box(current_event, ax):
    """Add an inset box to the lightcurve box giving a zoom-in around a 
    selected feature. 
    Based on code by E. Bachelet
    """

    inset_axfig1 = inset_axes(ax,
                              width="25%",
                              height="40%",
                              bbox_to_anchor=(-0.35, -0.2, 1.0, 1.2),
                              borderpad=5,
                              bbox_transform=ax.transAxes)

    microloutputs.LM_plot_model(current_event.fits[0], inset_axfig1)
    microloutputs.LM_plot_align_data(current_event.fits[0], inset_axfig1)

    inset_axfig1.legend_.remove()
    inset_axfig1.texts[0].set_visible(False)

    x1, x2, y1, y2 = 2458225.0, 2458250.0, 13.25, 11.0  # specify the limits
    inset_axfig1.set_xlim(x1, x2)  # apply the x-limits
    inset_axfig1.set_ylim(y1, y2)  # apply the y-limits

    patch, pp1, pp2 = mark_inset(ax,
                                 inset_axfig1,
                                 loc1=2,
                                 loc2=4,
                                 fc="none",
                                 ec="0.5")
    pp1.loc1 = 1
    pp1.loc2 = 3
    pp2.loc1 = 4
    pp2.loc2 = 2
    inset_axfig1.get_xaxis().get_major_formatter().set_useOffset(False)
    #inset_axfig1.set_xticks([2457084,2457085.2])
    inset_axfig1.tick_params(axis='both', labelsize=10)
    plt.xticks(rotation=30)
    plt.grid()
Beispiel #41
0
def pl_inset_title_box(ax,title,bwidth="20%",location=1):
    """
    Function that puts title of subplot in a box
    
    :ax:    Name of matplotlib axis to add inset title text box too
    :title: 'string to put inside text box'
    :returns: @todo
    """

    axins = inset_axes(ax,
                       width=bwidth, # width = 30% of parent_bbox
                       height=.30, # height : 1 inch
                       loc=location)

    plt.setp(axins.get_xticklabels(), visible=False)
    plt.setp(axins.get_yticklabels(), visible=False)
    axins.set_xticks([])
    axins.set_yticks([])

    axins.text(0.5,0.3,title,
            horizontalalignment='center',
            transform=axins.transAxes,size=10)
    return
Beispiel #42
0
def plot_csd(ax, lfp, max_val, title, start_t, end_t):
    norm = cm.colors.Normalize(vmax=max_val, vmin=-max_val, clip=False)
    im = plt.imshow(lfp[::-1], aspect='auto', norm=norm, interpolation='nearest', cmap=plt.cm.bwr_r)
    #plt.xlim((2750, 4250))
    plt.xticks(np.arange(3000-start_t, 5000-start_t, 1000), np.arange(300, 500, 100))
    #plt.ylabel('Electrode depth ($\mu$m)')
    plt.xlabel('Time (ms)')
    plt.gca().yaxis.set_major_locator(plt.NullLocator())
    plt.title(title)#, fontweight="bold", fontsize=12)
    #plt.yticks(np.arange(28))
    # plt.gca().set_yticks(np.arange(28))
    # plt.gca().set_yticklabels(np.arange(1,29))
    for label in plt.gca().yaxis.get_ticklabels()[::2]:
        label.set_visible(False)
    #plt.xlim(xmin=2500, xmax=4500)
    #plt.colorbar(extend='both')
    cbaxes = inset_axes(ax,
                        width="40%",  # width = 10% of parent_bbox width
                        height="3%",  # height : 50%
                        loc=1, borderpad=1 )
    cbar = plt.colorbar(cax=cbaxes, ticks=[-max_val,0.,max_val], orientation='horizontal', format='%.2f')
    cbar.ax.set_xticklabels(['source',str('0'),'sink'])
    return ax, im
Beispiel #43
0
def plot_gap(infile="experiments_data2/energy_synapse_gap.csv",
             output="gap.pdf",
             xlabel="$k$",
             ylabel1=r"$g_k-\left( g_{k+1} - \sigma_{k+1} \right)$",
             ylabel2=r"$J_k$"):
    df = pd.read_csv(infile, dtype=float)
    fig = plt.figure(figsize=(fig_width, fig_height))
    # plot gaps
    ax = fig.add_subplot(111)
    xs = range(1, len(df["gap"].values) + 1)
    #ax.errorbar(xs, df["gap"].values, yerr=df["var"].values, color="b",
    #            linestyle='-', marker="o", markersize=5, elinewidth=.5,
    #            capthick=0.5, linewidth=1.5, barsabove=False)
    ax.plot(xs,
            df["gap2"].values,
            color="b",
            linestyle="-",
            linewidth=1.5,
            marker="o",
            markersize=5)
    ax.plot(xs, [0] * len(xs), linestyle='--', color='k')
    ax.set_xlim([1, len(xs)])
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel1)
    #with sns.axes_style("whitegrid"):
    axins = inset_axes(ax, width="50%", height="50%", loc=5, borderpad=1)
    axins.plot(xs[4:10],
               df["gap2"].values[4:10],
               color='b',
               linestyle='-',
               marker='o',
               linewidth=1.5,
               markersize=5,
               alpha=0.7)
    axins.set_xticks([5, 6, 7, 8, 9])
    axins.set_yticks([])
    fig.savefig(output, bbox_inches='tight')
Beispiel #44
0
def plotGraphStats(fileNames):
    """Import and plot data from c++ program's
    output"""
    nDataFig = plt.figure(len(fileNames)+1)
    nDataAx = nDataFig.add_subplot(111)
    nData = 0
    haveGraphStats = False
    plotIndividuals = True
    i = 0
    for fileName in fileNames:
        pathToFile = os.path.realpath(fileName)
        toPlot = np.genfromtxt(pathToFile, delimiter = ',')
        if "convergenceData" in fileName:
            #runs per step
            rps = 10
            nSteps = toPlot.shape[0]/rps
            fig = plt.figure();
            ax = fig.add_subplot(111);
            for i in range(nSteps):
                if toPlot[i*rps, 1] == 0.482:
                    toPlot[i*rps:(i+1)*rps, 1] = 0
            xData = [sum(toPlot[i*rps:(i+1)*rps, 1])/rps for i in range(nSteps)]
            yData = [sum(toPlot[i*rps:(i+1)*rps, 0])/rps for i in range(nSteps)]
            xMax = 1.0*np.max(xData)
            yMax = 1.0*np.max(yData)
            xUpLim = xMax
            yUpLim = 1000000
            ax.scatter(xData, yData, c='r', s=36)
            ax.set_xlabel('Projection interval')
            ax.set_ylabel('Steps to consensus (log scale)')
            ax.set_yscale('log')
            ax.set_ylim((10000, yUpLim))
            ax.set_xlim((0, xMax))
            insets = []
            #copy list to allow modifications
            fileList = fileNames
            fileList.remove(fileName)
            for i in range(nSteps):
                for f in fileList:
                    #if have graphstats with same projection step, plot in subplot
                    if "graphStats" and str(xData[i]) in f:
                        pathToFile = os.path.realpath(f)
                        toPlotInset = np.genfromtxt(pathToFile, delimiter = ',')
                        insets.append(insetAxes.inset_axes(ax, width="50%", height="50%", loc=3, bbox_to_anchor=(xData[i]/xMax, np.log10(yData[i])/np.log10(yUpLim), 0.4, 0.4), bbox_transform=ax.transAxes))
                        insets[i].set_xticks([])
                        insets[i].set_yticks([])
                        insets[i].plot(toPlotInset[:,1], toPlotInset[:,2])
                        break
            plt.show(fig)
        #don't do individual plotting right now
        if ("graphstats" in fileName) & (plotIndividuals):
            haveGraphStats = True
            paramstr = fileName
            us = paramstr.find("_")
            paramstr = paramstr[us+1:]
            params = {}
            while us > 0:
                us = paramstr.find("_")
                us2 = paramstr.find("_", us+1)
                params[paramstr[:us]] = float(paramstr[us+1:us2])
                if "initDist" in paramstr[:us]:
                    period = paramstr.find(".", us2+1)
                    period2 = paramstr.find(".", period+1)
                    params[paramstr[:us]] = [float(paramstr[us+1:us2]), float(paramstr[us2+1:period2])]
                    us = -1
                else:
                    paramstr = paramstr[us2+1:]
            for key in params:
                if("initDist" not in key):
                    if(params[key] % 1 == 0):
                        params[key] = int(params[key])
            print params
            alpha = params['alpha']
            nData = nData + 1
            i = i + 1
            scaleUp = 16.0/15.0
            scaleDown = 14.0/15.0
            #get graph limits
            l0Low = min(toPlot[:,0])*scaleDown
            l0Up = max(toPlot[:,0])*scaleUp
            l1Low = min(toPlot[:,1])*scaleDown
            l1Up = max(toPlot[:,1])*scaleUp
            l2Low = min(toPlot[:,2])*scaleDown
            l2Up = max(toPlot[:,2])*scaleUp
            nSteps = toPlot.shape[0]
            f1 = plt.figure(i)
            ax2 = f1.add_subplot(211, ylabel="Number conflicting edges")
            ax2.plot(toPlot[:,0],toPlot[:,2], '-', color="#47D147")
            ax2.set_ylim([l2Low, l2Up])
            ax2.set_xlim([0,nSteps])
            ax1 = f1.add_subplot(212, sharex=ax2, ylabel="Minority fraction", xlabel="Time")
            ax1.plot(toPlot[:,0], toPlot[:,1], '-', color="#70AAFF")
            ax1.set_ylim([l1Low,l1Up])
            plt.setp(ax2.get_xticklabels(), visible=False)
            plt.subplots_adjust(hspace=0)
            saveFilename = fileName[:-4] + "_fig1" + ".png"
            plt.savefig(saveFilename, edgecolor='k')
            nDataAx.plot(toPlot[:,1],toPlot[:,2],'b-', label=r'$\alpha$' + " = " + str(alpha),  color=[1-alpha, np.cos(np.pi*alpha/2), alpha])
        elif "bifData" in fileName:
            i = i + 1
            fig = plt.figure(i)
            ax = fig.add_subplot(111)
            alpha = 0
            #filtering by completion of runs: x[2] == 0
            toPlot = filter(lambda x: ((x[2] == 0) & (x[3] != 0)), toPlot)
            toPlot = np.asarray(toPlot)
            n = toPlot.shape[0]
            #ids is a 2d list, with the first holding
            #the different values of alpha, the second
            #the corresponding initial minority fraction
            ids = {}
            colorList = []
            nu0 = 0
            nAlpha = 0
            for i in range(n):
                alpha = int(100*toPlot[i,0])
                u0 = int(100*toPlot[i,3])
                uf = toPlot[i,1]
                if not alpha in ids:
                    ids[alpha] = {}
                if not u0 in ids[alpha]:
                    ids[alpha][u0] = []
                ids[alpha][u0].append(uf)
                nAlpha = len(ids)
                if len(ids[alpha]) > nu0:
                    nu0 = len(ids[alpha])
            toPlot = np.zeros((nu0,nAlpha,3))
            u0s = []
            u0f = []
            j = 0
            for a in ids:
                u0s = ids[a].keys()
                u0s.sort()
                i = 0
                for u0 in u0s:
                    ids[a][u0] = np.average(np.asarray(ids[a][u0]))
                    toPlot[i,j,0] = a/100.0
                    toPlot[i,j,1] = ids[a][u0]
                    i = i + 1
                if len(u0s) > len(u0f):
                    u0f = u0s
                j = j + 1
            for i in range(nu0):
                u0 = u0f[i]/100.0
                ax.plot(toPlot[i,:,0], toPlot[i,:,1], 'o', color=[1-2*u0, np.cos(np.pi*u0), 2*u0], label="initial fraction= " + str(u0))
            ax.set_xlabel(r'$\alpha$', fontsize=20)
            ax.set_ylabel("Final minority fraction")
            colorList.sort()
            ax.legend(loc=3)
            ax.set_xlim([0,1])
            ax.set_ylim([0,0.5])
            saveFilename = fileName[:-4] + ".png"
            plt.savefig(saveFilename, edgecolor='k')
    if haveGraphStats:
        nDataAx.set_title("Number of conflicting edges vs. Minority fraction")
        nDataAx.legend(loc=2)
        saveFilename = "nData.png"
        plt.savefig(saveFilename, edgecolor='k')
        plt.show()
    else:
        plt.close(nDataFig)
    all_res.append(data['resistance'][0])
    res_error.append(data['error'][0])

titles = ['(a)', '(b)', '(c)', '(d)', '(e)', '(f)', '(g)', '(h)', '(i)']
m_s = 6
x_ticks = [0, 0.04, 0.08, 0.12, 0.16]
x_ticks2 = [0, 0.16]
res_fig = plt.figure()
for i in range(0, len(length)):
    ax = plt.subplot(3, 3, i + 1)
    if i == 1:
        fill_temp = np.delete(fill_factor, 7)
        res_temp = np.delete(all_res[i], [7, 9, 10])
        err_temp = np.delete(res_error[i], [7, 9, 10])
        ax.errorbar(fill_temp, res_temp, yerr=err_temp, fmt='o', ms=m_s)
        ax2 = inset_axes(ax, width="30%", height=1, loc=2)
        ip = InsetPosition(ax, [0.18, 0.62, 0.4, 0.3])
        ax2.errorbar(fill_factor,
                     all_res[i][:len(fill_factor)],
                     yerr=res_error[i][:len(fill_factor)],
                     fmt='o')
        ax2.set_axes_locator(ip)
        ax2.xaxis.set_ticks(x_ticks2)
        ax2.yaxis.set_ticks([0, 15, 30])
        ax2.set_xlim(-0.01, 0.17)
    elif i == 8:
        fill_temp = np.delete(fill_factor, 4)
        res_temp = np.delete(all_res[i], 4)
        err_temp = np.delete(res_error[i], 4)
        ax.errorbar(fill_temp, res_temp, yerr=err_temp, fmt='o', ms=m_s)
        ax2 = inset_axes(ax, width="30%", height=1, loc=2)
Beispiel #46
0
#legend = mpatches.Circle((0.5, 0.5), 1, facecolor='k', linewidth=3)

legends.append(legend)

leg = plt.legend(handles=legends,
                 title='Strain (25 bins)',
                 ncol=7,
                 loc='upper center',
                 bbox_to_anchor=(0.5, 1.05))
plt.ylabel(r"Median $K_{sn}$")
plt.xlabel("Elevation (50m bins)")
leg.get_frame().set_alpha(1)

#adding inset histogram
new_axes = inset_axes(ax,
                      width="40%",
                      height="40%",
                      bbox_to_anchor=(0.5, 0.5, 1200, 300))
data_2 = getAxisHist("segmented_")
new_colour = []
new_colour.append('k')
for x in colours:
    new_colour.append(x)
plt.hist(data_2, bins=x_series, stacked=True, color=new_colour[:7])
plt.title("Histogram of Data Points in Elevation Bins")
plt.ylabel("Frequency")
plt.xlabel("Elevation (50m bins)")

leg.get_frame().set_alpha(1)

fig.savefig('../elevation_scatter_Strain.png', bbox_inches='tight')
def fig2(n=352899, figname = 'Fig2', data_dir=mydir, \
    stratify = True, radius=2, remove = 0, zipfType = 'mle', RGF = False, \
    lognormType = 'pln', saveAs = 'eps'):
    # TAKEN FROM THE mete_sads.py script used for White et al. (2012)
    # Used for Figure 3 Locey and White (2013)
    """Multiple obs-predicted plotter"""
    fig = plt.figure()
    count = 0
    plot_dim = 2
    methods = ['geom', 'lognorm', 'mete', 'zipf']
    fig.subplots_adjust(bottom= 0.30)
    for i, method in enumerate(methods):
        if method == 'zipf':
            obs_pred_data = importData.import_obs_pred_data(data_dir + 'data/ObsPred/Stratified/'+ method + '_'+  zipfType+'_obs_pred_stratify.txt')
            INh2 = importData.import_NSR2_data(data_dir + 'data/NSR2/Stratified/' + method + '_mle' + '_NSR2_stratify.txt')
        elif method == 'lognorm':
            obs_pred_data = importData.import_obs_pred_data(data_dir + 'data/ObsPred/Stratified/'+ method + '_'+  lognormType+'_obs_pred_stratify.txt')
            INh2 = importData.import_NSR2_data(data_dir + 'data/NSR2/Stratified/' + method + '_'+  lognormType + '_NSR2_stratify.txt')
        else:
            obs_pred_data = importData.import_obs_pred_data(data_dir + 'data/ObsPred/Stratified/'+ method +'_obs_pred_stratify.txt')
            INh2 = importData.import_NSR2_data(data_dir + 'data/NSR2/Stratified/' + method + '_NSR2_stratify.txt')
        obs = np.asarray(list(((obs_pred_data["obs"]))))
        pred = np.asarray(list(((obs_pred_data["pred"]))))
        site = np.asarray(list(((obs_pred_data["site"]))))

        obs2 = []
        pred2 = []
        site2 = []

        obs_all = np.asarray(obs)
        pred_all = np.asarray(pred)
        site_all = np.asarray(site)

        if n == 'all' or len(obs) <= n:
            obs2 = list(obs)
            pred2 = list(pred)
            site2 = list(site)

        else:
            if len(obs) > n:
                inds = np.random.choice(range(len(site)), size=n, replace=False)
                for ind in inds:
                    obs2.append(obs[ind])
                    pred2.append(pred[ind])
                    site2.append(site[ind])

        obs = np.asarray(obs2)
        pred = np.asarray(pred2)
        site =  np.asarray(site2)

        if method == 'zipf':
            axis_min = 0
            axis_max = 2  * max(pred)
        else:
            axis_min = 0
            axis_max = 2 * max(obs)
        ax = fig.add_subplot(plot_dim, plot_dim, count+1)
        if method == 'zipf':
            NSR2_BS = importData.import_NSR2_data(data_dir + 'data/NSR2/Stratified_Test/'+ method  + '_mle_NSR2_stratify.txt')
        elif method == 'lognorm':
            NSR2_BS = importData.import_NSR2_data(data_dir + 'data/NSR2/Stratified_Test/'+ method  + '_pln_NSR2_stratify.txt')
        else:
            NSR2_BS = importData.import_NSR2_data(data_dir + 'data/NSR2/Stratified_Test/'+ method  +'_NSR2_stratify.txt')

        if method == 'geom':
            ax.set_title("Broken-stick")
        elif method == 'lognorm':
            ax.set_title("Lognormal")
        elif method == 'mete':
            ax.set_title("Log-series")
        elif method == 'zipf':
            ax.set_title("Zipf")
        print len(pred), len(obs)
        macroecotools.plot_color_by_pt_dens(pred, obs, radius, loglog=1,
                        plot_obj=plt.subplot(plot_dim,plot_dim,count+1))

        plt.plot([axis_min, axis_max],[axis_min, axis_max], 'k-')
        if method == 'zipf':
            plt.xlim(0, axis_max)
            plt.ylim(0, axis_max)
        else:
            plt.xlim(0, axis_max)
            plt.ylim(0, axis_max)
        r2s = ((INh2["R2"]))
        r2s = r2s.astype(float)
        # insert r2 of all data
        r2_all = np.mean(((NSR2_BS["R2"])))
        print method + ' mean = ' + str(r2_all)
        print method + ' std dev = ' +str(np.std(r2_all))
        r2text = r"${}^{{2}}_{{m}} = {:.{p}f} $".format('r',r2_all , p=2)
        if method == 'geom':
            plt.text(0.25, 0.90, r2text,  fontsize=14,
                horizontalalignment='center',
                verticalalignment='center',transform = ax.transAxes)
        else:
            plt.text(0.22, 0.90, r2text,  fontsize=14,
                horizontalalignment='center',
                verticalalignment='center',transform = ax.transAxes)
        plt.tick_params(axis='both', which='major', labelsize=10)
        plt.subplots_adjust(wspace=0.0000000001, hspace=0.5)

        axins = inset_axes(ax, width="30%", height="30%", loc=4)

        hist_r2 = np.histogram(r2s, range=(0, 1))
        xvals = hist_r2[1] + (hist_r2[1][1] - hist_r2[1][0])
        xvals = xvals[0:len(xvals)-1]
        yvals = hist_r2[0]
        plt.plot(xvals, yvals, 'k-', linewidth=2)
        plt.axis([0, 1, 0, 1.1 * max(yvals)])

        ax.set(adjustable='box-forced', aspect='equal')
        plt.setp(axins, xticks=[], yticks=[])


        count += 1
    plt.tight_layout(pad=1.5, w_pad=0.8, h_pad=0.8)
    fig.text(0.50, 0.03, 'Predicted abundance', ha='center', va='center', fontsize=16)
    fig.text(0.08, 0.5, 'Observed abundance', ha='center', va='center', rotation='vertical', fontsize=16)
    fig_name = str(mydir + 'figures/' + figname + '_RGB.' + saveAs)
    plt.savefig(fig_name, dpi=600, format = saveAs)#, bbox_inches = 'tight')#, pad_inches=0)
    plt.close()
def figS1(n=35289, figname = 'FigS1', data_dir=mydir, radius=2, zipfType = 'mle', \
    saveAs = 'eps', lognormType = 'pln'):
    methods = ['geom', 'lognorm', 'mete', 'zipf']
    datasets = ['95', '97', '99']
    fig = plt.figure()
    count = 0
    rows = len(datasets)
    columns = len(methods)
    for i, dataset in enumerate(datasets):
        for j, method in enumerate(methods):
            print count
            if method == 'zipf':
                obs_pred_data = importData.import_obs_pred_data(data_dir + 'data/ObsPred/Stratified/'+ method + '_'+  zipfType+'_obs_pred_stratify.txt')
                INh2 = importData.import_NSR2_data(data_dir + 'data/NSR2/Stratified/' + method + '_mle' + '_NSR2_stratify.txt')
            elif method == 'lognorm':
                obs_pred_data = importData.import_obs_pred_data(data_dir + 'data/ObsPred/Stratified/'+ method + '_'+  lognormType+'_obs_pred_stratify.txt')
                INh2 = importData.import_NSR2_data(data_dir + 'data/NSR2/Stratified/' + method + '_'+  lognormType + '_NSR2_stratify.txt')
            else:
                obs_pred_data = importData.import_obs_pred_data(data_dir + 'data/ObsPred/Stratified/'+ method +'_obs_pred_stratify.txt')
                INh2 = importData.import_NSR2_data(data_dir + 'data/NSR2/Stratified/' + method + '_NSR2_stratify.txt')
            obs = np.asarray(list(((obs_pred_data["obs"]))))
            pred = np.asarray(list(((obs_pred_data["pred"]))))
            site = np.asarray(list(((obs_pred_data["site"]))))


            obs2 = []
            pred2 = []
            site2 = []

            obs_all = np.asarray(obs)
            pred_all = np.asarray(pred)
            site_all = np.asarray(site)

            if n == 'all' or len(obs) <= n:
                obs2 = list(obs)
                pred2 = list(pred)
                site2 = list(site)

            else:
                if len(obs) > n:
                    inds = np.random.choice(range(len(site)), size=n, replace=False)
                    for ind in inds:
                        obs2.append(obs[ind])
                        pred2.append(pred[ind])
                        site2.append(site[ind])

            obs = np.asarray(obs2)
            pred = np.asarray(pred2)
            site =  np.asarray(site2)

            print "number of points " + str(len(obs))
            if method == 'zipf':
                axis_min = 0
                axis_max = 2  * max(pred)
            else:
                axis_min = 0
                axis_max = 2 * max(obs)
            ax = fig.add_subplot(rows, columns, count+1)

            if i == 0 and j == 0:
                ax.set_title("Broken-stick")
            elif i == 0 and j == 1:
                ax.set_title("Lognormal")
            elif i == 0 and j == 2:
                ax.set_title("Log-series")
            elif i == 0 and j == 3:
                ax.set_title("Zipf")

            if j == 0:
                if dataset == '95':
                    ax.set_ylabel("MG-RAST 95%", rotation=90, size=12)
                elif dataset == '97':
                    ax.set_ylabel("MG-RAST 97%", rotation=90, size=12)
                elif dataset == '99':
                    ax.set_ylabel("MG-RAST 99%", rotation=90, size=12)

            macroecotools.plot_color_by_pt_dens(pred, obs, radius, loglog=1,
                            plot_obj=plt.subplot(rows,columns,count+1))

            plt.plot([axis_min, axis_max],[axis_min, axis_max], 'k-')
            if method == 'zipf':
                plt.xlim(0, axis_max)
                plt.ylim(0, axis_max)
            else:
                plt.xlim(0, axis_max)
                plt.ylim(0, axis_max)
            r2s = ((INh2["R2"]))
            r2s = r2s.astype(float)
            mean_r2s = np.mean(r2s)
            std_r2s = np.std(r2s)
            print method, dataset
            print "Mean r2 " + str(mean_r2s)
            print "Standard dev. " + str(std_r2s)
            if method == 'zipf':
                getR2 = importData.import_NSR2_data(data_dir + 'data/NSR2/Stratified_Test/SequenceSimilarity/'+ method  + '_mle_' +dataset +'_NSR2_stratify.txt')
            elif method == 'lognorm':
                getR2 = importData.import_NSR2_data(data_dir + 'data/NSR2/Stratified_Test/SequenceSimilarity/'+ method  + '_' + lognormType + '_' +dataset  +'_NSR2_stratify.txt')
            else:
                getR2 = importData.import_NSR2_data(data_dir + 'data/NSR2/Stratified_Test/SequenceSimilarity/'+ method + '_' +dataset +'_NSR2_stratify.txt')
            r2_mean = np.mean(((getR2["R2"])))
            if method == 'geom':
                r2text = r"${}^{{2}}_{{m}} = {:.{p}f} $".format('r',r2_mean , p=3)
            else:
                r2text = r"${}^{{2}}_{{m}} = {:.{p}f} $".format('r',r2_mean , p=2)
            if method == 'geom':
                plt.text(0.28, 0.90, r2text,  fontsize=10,
                    horizontalalignment='center',
                    verticalalignment='center',transform = ax.transAxes)
            else:
                plt.text(0.25, 0.90, r2text,  fontsize=10,
                    horizontalalignment='center',
                    verticalalignment='center',transform = ax.transAxes)
            plt.tick_params(axis='both', which='major', labelsize=8)
            plt.subplots_adjust(wspace=0.0000000001, hspace=0.5)

            axins = inset_axes(ax, width="30%", height="30%", loc=4)

            hist_r2 = np.histogram(r2s, range=(0, 1))
            xvals = hist_r2[1] + (hist_r2[1][1] - hist_r2[1][0])
            xvals = xvals[0:len(xvals)-1]
            yvals = hist_r2[0]
            plt.plot(xvals, yvals, 'k-', linewidth=2)
            plt.axis([0, 1, 0, 1.1 * max(yvals)])

            ax.set(adjustable='box-forced', aspect='equal')
            plt.setp(axins, xticks=[], yticks=[])

            count += 1

    plt.tight_layout(pad=1.5, w_pad=0.8, h_pad=0.8)
    fig.subplots_adjust(left=0.1)
    fig.text(0.50, 0.02, 'Predicted abundance', ha='center', va='center', fontsize=14)
    fig.text(0.03, 0.5, 'Observed abundance', ha='center', va='center', rotation='vertical', fontsize=14)
    fig_name = str(mydir + 'figures/' + figname + '_RGB.' + saveAs)
    plt.savefig(fig_name, dpi=600, format = saveAs)#, bbox_inches = 'tight')#, pad_inches=0)
    plt.close()
def build_composite_band_plot(res, res0):

    sx = 1
    sy = 8

    X_min = - sx / 2
    X_max = sx / 2
    Y_min = -sy / 2
    Y_max = sy / 2

    fig = plt.figure()
    gs1 = mpl.gridspec.GridSpec(1,1)
    gs1.update(left=0.05, right=0.71, bottom=0.05, top=0.71)
    gs2 = mpl.gridspec.GridSpec(1,1)
    gs2.update(left=0.79, right=0.95, bottom=0.05, top=0.71)

    ax1 = plt.subplot(gs1[:,:])
    ax2 = plt.subplot(gs2[:,:], sharey=ax1)
    ax3 = ax2.twiny()
    plt.setp(ax2.get_yticklabels(), visible=False)

    # ratio.plot(ax=ax2, lw=3)
    r = res0.flux_ratio[0.15:0.5]
    rx = r.values
    ry = r.index
    ax2.plot(rx, ry, 'k', lw=3)

    ax2.set_xticks([0,0.5,1])
    ax2.set_xlim(0,1)

    c3 = cmap7.mpl_colors[0]
    l = res0.ldos[0.15:0.5]
    lx = l.values
    ly = l.index

    ax3.plot(lx, ly, c=c3, lw=3)
    ax3.set_xlim(0,1)
    ax3.set_xticks([0,1])
    ax3.set_xlabel("LDOS/"r"$\varepsilon_{hi}$")

    for obj in ax3.get_xticklabels() + [ax3.spines['top'], ax3.xaxis.label] + ax3.get_xticklines():
        obj.set_color(c3)
        obj.set_zorder(2)

    ax2.spines['top'].set_visible(False)
    ax2.set_xticks([0,1])
    ax2.set_xlabel("$P_{rad} / P_0$")

    ax1.set_xlabel("$k_x a / (2 \pi)$")
    ax1.set_ylabel("$\omega a / (2 \pi c)$")
    ax1.set_xlim(0,0.5)
    ax1.set_ylim(0,0.5)
    ax1.set_aspect('equal')
    ax1.set_autoscale_on(False)

    # add an inset image of epsilon
    a = inset_locator.inset_axes(ax1, height=1.8, width=0.225, loc=8,
                                 bbox_to_anchor=(0.9, 0.01), bbox_transform=ax1.transAxes)
    a.imshow(res.epsilon, extent=(X_min,X_max, Y_min, Y_max), cmap=plt.cm.gray)

    a.set_aspect("equal")

    plt.setp(a.xaxis, visible=False)
    plt.setp(a.yaxis, visible=False)

    return fig
ax.set(aspect=1,
       xlim=(-15, 15),
       ylim=(-20, 5))


axins = zoomed_inset_axes(ax, 2, loc=2) # zoom = 6
im = axins.imshow(Z, extent=extent, interpolation="nearest",
                  origin="lower")

plt.xticks(visible=False)
plt.yticks(visible=False)


# colorbar
cax = inset_axes(axins,
                 width="5%", # width = 10% of parent_bbox width
                 height="100%", # height : 50%
                 loc=3,
                 bbox_to_anchor=(1.05, 0., 1, 1),
                 bbox_transform=axins.transAxes,
                 borderpad=0,
                 )


colorbar(im, cax=cax) #, ticks=[1,2,3])


plt.draw()
plt.show()

def SAD_SSAD(fs):
    switch = 0
    dataset = 'BCI'
    fig = plt.figure()
        
    """ This does this ... figure 3 of Locey and McGilnn 2013"""
    
    ax =fig.add_subplot(2,2,1)
    pattern = 'SAD'
    RADs = get_obs_pred(dataset, pattern)
    obsRAD = RADs[0]
    predRAD = RADs[1]
    print obs_pred_rsquare(np.log(obsRAD), np.log(predRAD))
    N = sum(obsRAD)
    S = len(obsRAD)
    
    DATA = open('/home/kenlocey/combined1/' + str(N) + '-' + str(S) + '.txt','r')
    RADs = []
    for d in DATA:
        rad = eval(d)
        RADs.append(rad)
    DATA.close()
    
    x = []
    y = []
    for rad in RADs:
        rank = 1
        for j in rad:
            x.append(rank)
            y.append(np.log(j))
            rank += 1

    plt.hexbin(x,y,bins='log',gridsize=100,mincnt=1,cmap=cm.Reds) # bins can be 'log' or None
    plt.tick_params(axis='both', which='major', labelsize=fs-3)
    ranks = range(1,301+1)
    plt.scatter(ranks,np.log(obsRAD), color='0.3', marker = '.')
    plt.text(225, 8, '0.28',fontsize=fs+2)
    plt.xlabel("Rank in abundance",fontsize=fs)
    plt.ylabel("ln(abundance)",fontsize=fs)
    #plt.ylim(-0.1,19.5)
    plt.xlim(0.01,310)
    
    
    ax =fig.add_subplot(2,2,2)
    
    SSADs_freqs = get_SSADs(dataset)
    SSADs = hist_to_rank(SSADs_freqs)
    
    Pvals = []
    for i, obsSSAD in enumerate(SSADs):
        
        Q = sum(obsSSAD)
        N = len(obsSSAD)
        
        partitions = []
        PATH = '/home/kenlocey/combined1/' + str(Q) + '-' + str(N) + '.txt'
        if path.exists(PATH) and path.isfile(PATH) and access(PATH, R_OK):
            DATA = open(PATH,'r')
            DATA.readline() # first line has no abundance info, so skip it
            for d in DATA:
                partitions.append(eval(d))
        else: continue
        
        if len(partitions) == 0:
            print Q,N,'something is wrong'
            sys.exit()  
              
        predSSAD = parts.central_tendency(partitions)
        print sum(obsSSAD),len(obsSSAD),' ',sum(predSSAD),len(predSSAD),
        
        pval = stats.ks_2samp(obsSSAD, predSSAD)[1]
        Pvals.append(pval)
        print pval
        
        if pval > 0.05 and Q > 1000 and switch == 0:
            
            SSADs = []
            for part in partitions:
                ssad = rank_to_PrestonPlot(part) 
                ssad2 = lose_trailing_zeros(ssad)
                SSADs.append(ssad2)
            
            #print SSADs[0]
            #sys.exit()
            
            x = []
            y = []
            for ssad in SSADs:
                ab_class = 0
                for j in ssad:
                    x.append(ab_class)
                    y.append(j)
                    ab_class += 1
            
            plt.hexbin(x,y,bins=None,gridsize=25,mincnt=1,cmap=cm.Reds) 
            obsSSAD2 = rank_to_PrestonPlot(obsSSAD)
            obsSSAD3 = lose_trailing_zeros(obsSSAD2)
            bins = range(0,len(obsSSAD2))
            #plt.plot(obsSSAD, color='0.3', lw=2)
            plt.scatter(bins, obsSSAD3, color='0.3', marker = 'o')
            #plt.xlim(-0.5,max(bins))
            #plt.ylim(-0.5,max(max(predSSAD),max(obsSSAD))+10)
            plt.xlabel("Abundance class",fontsize=fs)
            plt.ylabel("frequency",fontsize=fs)
            plt.tick_params(axis='both', which='major', labelsize=fs-3)
            
            switch += 1
            
        if len(Pvals) > 50 and switch == 1: break
    # Create inset for histogram of site level r^2 values
    axins = inset_axes(ax, width="30%", height="30%", loc=1)
    D = get_kdens(Pvals)
    plt.plot(D[0],D[1],color='0.2',lw=2.0)
    plt.setp(axins, xticks=[0.0, 0.5, 1.0])
    plt.tick_params(axis='both', which='major', labelsize=fs-4)
    plt.xlim(0.0,1.0)
    #plt.ylim(0.0, max(D[1])+0.003)
    plt.subplots_adjust(wspace=0.3)
    plt.savefig('/home/kenlocey/partitions/SAD-SSAD.png', dpi=400, bbox_inches = 'tight', pad_inches=0.03)
Beispiel #52
0
def displacement(ofile,timestep,Natoms,matrix0,Type,Time,frontname,pathtodatabase,systemsize):
    '''
    timestep,system_size,matrix0 contain the initial information about the system.
    we have to go through sortedfiles to find information about the particles at
    later timesteps.
    '''
    factor = 10**(-8)                                               # conversionfactor from [A^2/ps] -> [m^2/s]

    Lx = systemsize[1] -systemsize[0]    
    Ly = systemsize[3] -systemsize[2]
    Lz = systemsize[5] -systemsize[4]
    halfsystemsize = 0.5*(Lx+Ly+Lz)/3.0   # half of average system size
    
    time = []
    for t in Time:
        time.append(timestep*t/1000.0)   # to picoseconds
        #time.append(t)
        
    MSDX = [];MSDY = [];MSDZ = [];MSD = [];D_local = []
    dt = (time[1]-time[0])
    for T in Time:
        path = frontname + '.%r.txt' % (T)
        print path
        msdx = 0; msdy = 0; msdz = 0; msd = 0
        filename = os.path.abspath(os.path.join(pathtodatabase,path))
        t, Natoms, system_size, matrix, readstructure, entries, types = readfile(filename)
        counter = 0
        for i in range(Natoms):
            if (matrix['type'][i] == Type):
                ID = matrix['id'][i]
                initial_index = None
                for j in range(Natoms):
                    k = matrix0['id'][j]
                    if (k == ID):
                        initial_index = j
                        break
                
                dx = matrix['x'][i] - matrix0['x'][initial_index]
                dy = matrix['y'][i] - matrix0['y'][initial_index]
                dz = matrix['z'][i] - matrix0['z'][initial_index]
                msdx += (dx)**2
                msdy += (dy)**2
                msdz += (dz)**2
                ########################################
                #        MINIMUM IMAGE CONVENTION      #
                if (dx < -halfsystemsize): dx = dx + Lx
                if (dx > halfsystemsize): dx = dx - Lx
                if (dy < -halfsystemsize): dy = dy + Ly
                if (dy > halfsystemsize): dy = dy - Ly
                if (dz < -halfsystemsize): dz = dz + Lz
                if (dz > halfsystemsize): dz = dz - Lz
                ########################################
                msd += dx**2 + dy**2 + dz**2
                counter += 1
    
        D_local.append((msd/(counter*6*T)))
        MSDX.append(msdx/(6*counter));MSDY.append(msdy/(6*counter));MSDZ.append(msdz/(6*counter));MSD.append(msd/(6*counter))
        

    # ballistic_end = 100ps
    degree = 1
    start = int(round(len(MSD)/5.0))
    p = np.polyfit(time[start:],MSD[start:],degree)   # last 4/5 of the dataset
    f = np.polyval(p,time)    
    d_mean_lastpart = p[0]#*10**(-8)        # to get [m^2/s]. [A^2/ps] = 10**(-8)[m^2/s]

    p1 = np.polyfit(time[0:start],MSD[0:start],degree)
    f1 = np.polyval(p1,time)    
    d_mean_firstpart = p1[0]#*10**(8)       # to get [m^2/s]. [A^2/ps] = 10**(-8)[m^2/s]

    p2 = np.polyfit(time[0:int(round(start/2.0))],MSD[0:int(round(start/2.0))],degree)
    f2 = np.polyval(p2,time)    
    d_mean_initpart = p2[0]#*10**(8)        # to get [m^2/s]. [A^2/ps] = 10**(-8)[m^2/s]
    
    p3 = np.polyfit(time[0:100],MSD[0:100],degree)
    f3 = np.polyval(p3,time)
    d_mean_actual = p3[0]#*10**(8)          # to get [m^2/s]. [A^2/ps] = 10**(-8)[m^2/s]

    print "#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#"
    print " Nvalues in estimate 1 = 100"
    print " Nvalues in estimate 2 = %g" % (int(round(start/2.0)))
    print " Nvalues in estimate 3 = %g" % (int(round(start)))
    print " Nvalues in estimate 4 = %g" % (len(time[start:]))
    
    ###############################################################################
    #                             plotting
    #plt.close('all')
    plt.figure()                                                                # Figure 1
    Title = 'Mean square displacement'
    legends = ['$msd_{x}$','$msd_{y}$','$msd_{z}$','$msd$']#['$msd$']#
    Ylabel = 'mean square displacement $ [A^2] $'
    Xlabel = 'time $ [ps] $'
    pltname = 'MSD_bulkwater'
    linestyles = ['--r','--y','--k','o-b']#['--r'] #
    plt.hold(True)
    plt.plot(time,MSDX,linestyles[0])
    plt.plot(time,MSDY,linestyles[1])
    plt.plot(time,MSDZ,linestyles[2])
    plt.plot(time,MSD,linestyles[3],markevery=10)
    plt.title(Title)
    plt.xlabel(Xlabel)
    plt.ylabel(Ylabel)
    plt.legend(legends,loc='lower right')
    plt.hold(False)
    write_to_file(ofile,Title,Xlabel,Ylabel,pltname,legends,linestyles,[time],[MSDX,MSDY,MSDZ,MSD])
    
    
    from mpl_toolkits.axes_grid.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

    plt.figure()
    ax = plt.axes()                                                             # Figure 2
    Title = 'Mean square displacement'
    legends = ['MSD','$f_1 %.3f $' % (d_mean_actual),'$f_2 %.3f $' % (d_mean_initpart),'$f_3 %.3f $' % (d_mean_firstpart),'$f_4 %.3f $' % (d_mean_lastpart)]
    pltname = 'MSD_bulkwater_mean'
    Xlabel = 'time $ [ps] $'
    Ylabel = 'mean square displacement $ [A^2] $'
    linestyles = ['b-','--y','--r','--m','--y']
    
    plt.hold(True)
    plt.plot(time,MSD,linestyles[0])
    plt.plot(time[0:int(round(len(f)/8.0))],f3[0:int(round(len(f)/8.0))],linestyles[1])  # very first part
    plt.plot(time[0:int(round(len(f)/6.0))],f2[0:int(round(len(f)/6.0))],linestyles[2])  # initpart
    plt.plot(time[0:int(round(len(f)/5.0))],f1[0:int(round(len(f)/5.0))],linestyles[3])  # firstpart
    plt.plot(time,f,linestyles[4])                                                       # lastpart

    plt.hold(False)
    plt.xlabel(Xlabel)
    plt.ylabel(Ylabel)
    plt.legend(legends,loc='lower right')
    plt.title(Title)
    
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()
    
    axin = inset_axes(ax, width="30%", height="35%", loc=8)
    plt.hold(True)
    axin.plot(time,MSD,linestyles[0])
    axin.plot(time,f3,linestyles[1],linewidth=3.0)
    axin.plot(time,f2,linestyles[2])
    #axin.plot(time,f1,linestyles[3])
    plt.hold(False)
    axin.set_xlim(500, 520)
    ya = 0.0
    yb = 4.0
    Npoints = 4
    points = np.linspace(ya,yb,Npoints)
    axin.set_ylim(ya, yb)
    axin.set_xticks([])
    axin.set_yticks(points)
    mark_inset(ax, axin, loc1=3, loc2=4, fc="none", ec="0.5")    
    
    write_to_file(ofile,Title,Xlabel,Ylabel,pltname,legends,linestyles,[time],[MSD,f])
    
    print "#################################################################"
    print "# Diffusion estimate f1   : D = %.10f " % (d_mean_actual)    
    print "# Diffusion estimate f2   : D = %.10f " % (d_mean_initpart)
    print "# Diffusion estimate f3   : D = %.10f " % (d_mean_firstpart) 
    print "# Diffusion estimate f4   : D = %.10f " % (d_mean_lastpart)

    plt.figure()                                                                # Figure 3
    Title = 'Time evolution of the local diffusion constant. $ D=(msd/6dt) $'
    legends = ['$D(t)$']; linestyles = ['-y']
    pltname = 'Diffusion_bulkwater'
    Ylabel = 'displacement $ [ %g m^2/s]$' % factor
    plt.hold(True)
    plt.plot(time,D_local,linestyles[0])    
    plt.hold(False)
    plt.legend(legends,loc='upper right')
    plt.title(Title)
    plt.xlabel(Xlabel)
    plt.ylabel(Ylabel)
    write_to_file(ofile,Title,Xlabel,Ylabel,pltname,legends,linestyles,[time],[D_local])

    plt.show()
Beispiel #53
0
	def plot(self, profile, statsResults):
		if len(statsResults.activeData) <= 0:
			self.emptyAxis()			
			return
			
		axesColour = str(self.preferences['Axes colour'].name())
		
		# *** Get data to plot 
		if self.fieldToPlot == 'p-values':
			data = statsResults.getColumn('pValues')
			xLabel = 'p-value'
		elif self.fieldToPlot == 'p-values (corrected)':
			data = statsResults.getColumn('pValuesCorrected')
			xLabel = 'p-value (corrected)'
		
		# *** Set size of figure
		self.fig.clear()
		self.fig.set_size_inches(self.figWidth, self.figHeight) 
		heightBottomLabels = 0.4	# inches
		widthSideLabel = 0.5			# inches 
		padding = 0.2						 # inches
		axesHist = self.fig.add_axes([widthSideLabel/self.figWidth,heightBottomLabels/self.figHeight,\
																		1.0-(widthSideLabel+padding)/self.figWidth,\
																		1.0-(heightBottomLabels+padding)/self.figHeight])
		
		# *** Histogram plot 
		bins = [0.0]
		binWidth = self.binWidth
		binEnd = binWidth
		while binEnd <= 1.0:
			bins.append(binEnd)
			binEnd += binWidth
			

		n, bins, patch = axesHist.hist(data, bins=bins, log=self.yAxisLogScale,color=(0.5,0.5,0.5))	
		axesHist.set_xlabel(xLabel)
		axesHist.set_ylabel('Number of features')
			

		# *** Prettify plot	 
		for a in axesHist.yaxis.majorTicks:
			a.tick1On=True
			a.tick2On=False
				
		for a in axesHist.xaxis.majorTicks:
			a.tick1On=True
			a.tick2On=False
			
		for line in axesHist.yaxis.get_ticklines(): 
			line.set_color(axesColour)
				
		for line in axesHist.xaxis.get_ticklines(): 
			line.set_color(axesColour)
			
		for loc, spine in axesHist.spines.iteritems():
			if loc in ['right','top']:
				spine.set_color('none') 
			else:
				spine.set_color(axesColour)
			
		# *** Plot inset		
		if self.bShowInset:
			bins = [0.0]
			binWidth = self.insetBinWidth
			binEnd = binWidth
			while binEnd <= self.xLimit:
				bins.append(binEnd)
				binEnd += binWidth
				
			widthStr = str(self.insetWidth) + '%'
			heightStr = str(self.insetHeight) + '%'
			axins = inset_axes(axesHist, width=widthStr, height=heightStr, loc=1)
			filteredData = [d for d in data if d <= self.xLimit]
			if filteredData:
				n, bins, patch = axins.hist(filteredData, bins=bins, log=self.insetLogScale, color=(0.5,0.5,0.5))	
			axins.set_xlim(0, self.xLimit)
			
			# *** Prettify inset	 
			for a in axins.yaxis.majorTicks:
				a.tick1On=True
				a.tick2On=False
					
			for a in axins.xaxis.majorTicks:
				a.tick1On=True
				a.tick2On=False
				
			for line in axins.yaxis.get_ticklines(): 
				line.set_color(axesColour)
				
			for line in axins.xaxis.get_ticklines(): 
				line.set_color(axesColour)
				
			for loc, spine in axins.spines.iteritems():
				if loc in ['right','top']:
					spine.set_color('none') 
				else:
						spine.set_color(axesColour)
				
		self.updateGeometry()			 
		self.draw()
fg7.set_xlim([12,37])
fg7.set_ylim([0.45,1.])
fg7.set_yticks([0.5,0.75,1.])
fg7.set_xticks([15,20,25,30,35])
fg7.tick_params(axis='both', which='major', labelsize=30)
fg7.set_xlabel(r'Threshold ($x_f$)',fontsize=50)
fg7.set_ylabel(r'Proportion Pot./Dep. ($q_f$)',fontsize=50)

#fg7.axhline(y=.7, xmin=0, xmax=100, linewidth=10, color = 'b',alpha=0.5, linestyle='dashed')
# Make a colorbar for the ContourSet returned by the contourf call.
fg7.axvline(x=model_step.mean_patterns, ymin=0, ymax=1, linewidth=10, color = 'g',alpha=0.5, linestyle='dashed')
fg7.axvline(x=model_step.median_patterns, ymin=0, ymax=1, linewidth=10, color = 'peru',alpha=0.5, linestyle='dashed')
fg7.scatter(themaxcap[2][5:-1],themaxcap[3][5:-1],s=1000*(np.array(themaxcap[1][5:-1])/max(themaxcap[1])),alpha=0.5,color='b')
fg7.set_title('(F)',fontsize=50,fontweight="bold",y=1.06)
fg7.text(16,0.95,'Potentiation',fontsize=50)
fg7.text(28,0.8,'Depresion',fontsize=50)
inset_axes = inset_axes(fg7,width=5, height=3,loc=1,bbox_to_anchor=(0.895, 0.265),bbox_transform=fg7.figure.transFigure)
inset_axes.plot(themaxcap[0][5:-1],themaxcap[1][5:-1],lw=8,color='maroon',alpha=0.8)
inset_axes.set_xlim([0.5,7])
inset_axes.set_ylim([0.4,0.8])
#inset_axes.set_xticks([25.,75,100])
inset_axes.set_yticks([0.4,0.6,0.8])
inset_axes.tick_params(labelsize=30)
inset_axes.set_xlabel(r'A',fontsize=30)
inset_axes.set_ylabel(r'Larg.Max.Cap.($\alpha_c$)',fontsize=30)
#cbar.set_ticklabels([0.08,0.32,0.64])
plt.savefig('fig3.pdf', bbox_inches='tight')
print themaxcap[0][5]
#plt.show()

def show_coord_topo_zoom(windpark, show = True):
    """Plot the topology of a given windpark

    Topographic Map with farms
    see: http://matplotlib.org/basemap/users/examples.html
    Basemap

    Parameters
    ----------

    windpark : Windpark
               A given windpark to show the topology.
    """

    plt.clf()

    turbines = windpark.get_turbines()
    target = windpark.get_target()
    radius = windpark.get_radius()

    #pack latitude and longitude in lists
    rel_input_lat = []
    rel_input_lon = []
    for row in turbines:
        rel_input_lat.append(np.float64(row.latitude))
        rel_input_lon.append(np.float64(row.longitude))

    targetcoord = [0.0, 0.0]
    targetcoord[0] = np.float64(target.latitude)
    targetcoord[1] = np.float64(target.longitude)

    graddiff = (800/111.0) + 0.5  # degree in km... 800km

    fig = plt.figure(figsize=(11.7,8.3))
    plt.title("Location of the farm")

    #Custom adjust of the subplots
    plt.subplots_adjust(left=0.05,right=0.95,top=0.90,bottom=0.05,wspace=0.15,hspace=0.05)
    ax = plt.subplot(111)

    m = Basemap(projection='lcc', lon_0=targetcoord[1], lat_0=targetcoord[0],\
        llcrnrlon = targetcoord[1]-graddiff*2, llcrnrlat = targetcoord[0]-graddiff ,\
        urcrnrlon = targetcoord[1]+graddiff, urcrnrlat = targetcoord[0]+graddiff ,\
        rsphere=6371200., resolution = None, area_thresh=1000)

    # Target
    x_target,y_target = m(targetcoord[1],targetcoord[0])
    # Input Farms
    rel_inputs_lon, rel_inputs_lat = m(rel_input_lon, rel_input_lat)

    # labels = [left,right,top,bottom]
    parallels = np.arange(int(targetcoord[0]-7), int(targetcoord[0]+7), 2.)
    m.drawparallels(parallels,labels=[False,True,True,False])
    meridians = np.arange(int(targetcoord[1]-7), int(targetcoord[1]+7), 2.)
    m.drawmeridians(meridians,labels=[True,False,False,True])


    # plot farms in the radius
    m.plot(x_target, y_target, 'bo')
    # m.plot(rel_inputs_lon, rel_inputs_lat, 'r*')

    #m.bluemarble()
    m.shadedrelief()

    # we define the inset_axes, with a zoom of 2 and at location 2 (upper left corner)
    # axins = zoomed_inset_axes(ax, 40, loc=2)
    axins = inset_axes(ax,
                        width="65%", # width = 30% of parent_bbox
                        height="65%", # height : 1 inch
                        loc=3)

    # plot farms in the radius
    m.plot(x_target, y_target, 'bo')
    m.plot(rel_inputs_lon, rel_inputs_lat, 'r*')

    #m.bluemarble()
    m.shadedrelief()
    #m.etopo()
    #m.drawcoastlines()

    graddiff_park = (radius/(111.0*0.7))  # degree in km
    x,y = m(targetcoord[1]-graddiff_park,targetcoord[0]-graddiff_park)
    x2,y2 = m(targetcoord[1]+graddiff_park,targetcoord[0]+graddiff_park)

    axins.set_xlim(x,x2) # and we apply the limits of the zoom plot to the inset axes
    axins.set_ylim(y,y2) # idem
    plt.xticks(visible=False) # we hide the ticks
    plt.yticks(visible=False)
    mark_inset(ax, axins, loc1=1, loc2=4, fc="none", ec="0.9", linewidth = 3) # we draw the "zoom effect" on the main map (ax), joining cornder 1 & 3

    plt.title("Selected Wind Farms")
    if(show):
        plt.show()
for i in list_index_alp: 
	fg2.plot(rates,myprobs_pres_fam[i],lw=12,alpha=0.8,label=' ')
colormap = plt.cm.Accent
plt.gca().set_color_cycle([colormap(i) for i in np.linspace(0, 0.9,len_index_alp)])
for i in list_index_alp: 
	fg2.plot(rates,myprobs_pres_nov[i],lw=12,ls='--',alpha=0.8)
fg2.set_xlim([0.01,30])
fg2.set_ylim([0,0.3])
fg2.set_yticks([0,0.1,0.2,0.3])
#fg2.set_xticks([0,0.1,0.2,0.3,0.4,0.5])
fg2.set_xlabel(r'Rate (Hz)',fontsize=45)
fg2.set_ylabel(r'Dist. Rates',fontsize=45)
fg2.tick_params(labelsize=35)
fg2.set_title('(A)',fontsize=50,fontweight="bold",y=1.06)
fg2.legend(loc=(0.01,0.47),numpoints=1,prop={'size':12})
inset_axes = inset_axes(fg2,width=5, height=3,loc=1,bbox_to_anchor=(0.345, 0.885),bbox_transform=fg2.figure.transFigure)
colormap = plt.cm.Accent
plt.gca().set_color_cycle([colormap(i) for i in np.linspace(0, 0.9,len_index_alp)])
for i in list_index_alp: 
	inset_axes.plot(rates,myprobs_pres_fam[i],lw=8,alpha=0.8)
colormap = plt.cm.Accent
plt.gca().set_color_cycle([colormap(i) for i in np.linspace(0, 0.9,len_index_alp)])
for i in list_index_alp: 
	inset_axes.plot(rates,myprobs_pres_nov[i],lw=8,ls='--',alpha=0.8)

inset_axes.set_xlim([25,100])
inset_axes.set_ylim([0,0.02])
inset_axes.set_xticks([25.,75,100])
inset_axes.set_yticks([0.02])
inset_axes.tick_params(labelsize=30)
inset_axes.set_xlabel(r'Rate (Hz)',fontsize=30)
Beispiel #57
0
                # ax1.set_xlabel(r'Rest frame wavelength')
                '''
                ax3 = plt.subplot(gs[1], sharex=ax1)  # ax2 = smaller lower axis
                ax3.plot(wave_rest, chi, 'o', color='k')  # plot chi
                plt.axhline(y=0, color='k')  # plot horizontal line at y=0 on chi plot
                yticks = ax3.yaxis.get_major_ticks()  # show ytick labels on lower axis
                yticks[-1].label1.set_visible(False)  # hide uppermost ytick label on lower axis to prevent overlap
                ax3.set_ylabel(r'$\chi$', fontsize=fs_text)
                # ax3.set_xlabel(r'Rest frame wavelength', fontsize=fs)  # 30
                # plt.subplots_adjust(hspace=.0)
                '''
                ax1.legend(numpoints=1, loc='upper left',
                           prop={'size': 20})  # , line2) ... , r'$\chi$']

                loc_uvj = 1
                inset_axes(ax1, width=8 * 0.32, height=8 * 0.28, loc=loc_uvj)
                # NOTE: height = 0.875 width (3.5 units vs 4 units) 20%/0.875=0.22857 --> if height 28%, set width to 32%
                # create inset axis: width (%), height (inches), location
                # loc=1 (upper right), loc=2 (upper left) --> loc=3 (lower left), loc=4 (lower right); loc=7 (center right)
                # https://stackoverflow.com/questions/10824156/matplotlib-legend-location-numbers
                uvj.uvj_plot(-1,
                             'all',
                             objlist=[str(obj) + '_' + field],
                             title=False,
                             labels=False,
                             lims=True,
                             size=20,
                             show=False,
                             col=['purple'])
                print('uvj1')
Beispiel #58
0
def Make_Z_Plot(grbdict, z_key="grbox_z", Nbins=31, z_cutoff=4.0):
    """Given any dictionary which has the redshift as one of the keywords, plot
    a histogram of those redshifts.
    """
    z_list = []
    zname_list = []
    date_list = []

    # 'un'zip all_grbs (is there a better way to do this? just assign rather than a for loop?)
    for key, value in grbdict.iteritems():
        # date_list.append(value['date'])
        z_list.append(value[z_key])
        zname_list.append(key)
    print "***All***"
    print " "
    print z_list
    print len(z_list)

    ### Print out the most distant GRB as a function of time
    zmax = 0.0
    rr = []
    for key, value in grbdict.iteritems():
        if value[z_key] > zmax:
            rr.append(key)
            zmax = value[z_key]
            # print value['date'].year + value['date'].timetuple().tm_yday/365.0, zmax, "#  ", key

    ax = plt.subplot(111)
    n, bins, patches = plt.hist(plt.log10(z_list), bins=Nbins, facecolor="grey", edgecolor="grey")

    # Define pre-swift burst index as bursts before 041210
    # high_z_i = plt.where(plt.array(date_list) < datetime.date(2004,12,10))

    # high_z_list = [z_list[i] for i in list(high_z_i[0])]
    # print high_z_list
    # n, bins1, patches = plt.hist(plt.log10(high_z_list),bins=bins,facecolor='black',edgecolor='black',alpha=0.6)

    if overplot_high_z:
        high_z_list = [z for z in z_list if z > z_cutoff]
        n, bins1, patches = plt.hist(plt.log10(high_z_list), bins=bins, facecolor="black", edgecolor="black")

    ay = ax.twinx()

    argg = list(plt.ones(len(z_list)).cumsum().repeat(2))
    zz = copy.copy(z_list)
    zz.sort()
    tmp = list(plt.log10(zz).repeat(2))

    tmp.append(1)
    yy = [0]
    yy.extend(argg)

    ay.plot(tmp, yy, aa=True, linewidth=4, color="black")

    argg = list(plt.ones(len(high_z_list)).cumsum().repeat(2))
    zz = copy.copy(high_z_list)
    zz.sort()
    tmp = list(plt.log10(zz).repeat(2))

    tmp.append(1)
    yy = [0]
    yy.extend(argg)

    ay.plot(tmp, yy, aa=True, linewidth=2, color="grey")
    ay.set_ylim((0, len(z_list) * 1.05))
    ay.set_ylabel("Cumulative Number", fontsize=20)
    # formatter for bottom x axis
    def ff(x, pos=None):
        if x < -1:
            return "%.2f" % (10 ** x)
        elif x < 0:
            return "%.1f" % (10 ** x)
        elif 10 ** x == 8.5:
            return "%.1f" % (10 ** x)
        else:
            return "%i" % (10 ** x)

    formatter = FuncFormatter(ff)
    ax.set_xticks([-2, -1, plt.log10(0.3), 0, plt.log10(2), plt.log10(3), plt.log10(4), plt.log10(6), plt.log10(8.5)])
    ax.xaxis.set_major_formatter(formatter)
    ax.set_xlabel("Redshift ($z$)", fontsize=20)
    ax.set_ylabel("Number", fontsize=20)

    ax.set_xlim((plt.log10(0.005), plt.log10(10)))

    ax2 = ax.twiny()
    xlim = ax.get_xlim()
    # ax2.set_xscale("log")
    ax2.set_xlim((xlim[0], xlim[1]))

    # Define function for plotting the top X axis; time since big bang in Gyr
    def rr(x, pos=None):
        g = cosmocalc.cosmocalc(10.0 ** x, H0=71.0)
        if g["zage_Gyr"] < 1:
            return "%.2f" % g["zage_Gyr"]  # Return 2 dec place if age < 1; e.g 0.62
        else:
            return "%.1f" % g["zage_Gyr"]  # Return 1 dec place if age > 1; e.g. 1.5

    ax2.set_xticks([-1.91, -1.3, -0.752, -0.283, 0.102, 0.349, 0.62, plt.log10(8.3)])

    formatter1 = FuncFormatter(rr)
    ax2.xaxis.set_major_formatter(formatter1)
    ax2.set_xlabel("Time since Big Bang (Gyr)", fontsize=20)

    # plt.bar(l,a['yy'],width=w,log=False)
    # ax.set_xscale("log",nonposx='clip')

    ## Now plot inset plot of GRBs greater than z=z_cutoff

    axins = inset_axes(ax2, width="30%", height="30%")  # width = 30% of parent_bbox  # height : 1 inch)

    locator = axins.get_axes_locator()
    locator.set_bbox_to_anchor((-0.8, -0.45, 1.35, 1.35), ax.transAxes)
    locator.borderpad = 0.0

    high_z_list = [z for z in z_list if z > z_cutoff]
    if high_z_list:  # if there are any high-z's, plot them
        n, bins, patches = plt.hist(plt.array(high_z_list), facecolor="black", edgecolor="black")
    axins.set_xlim(z_cutoff, 8.5)
    axins.set_xlabel("z")
    axins.set_ylabel("N")

    # high_z_i = plt.where(plt.array(date_list) < datetime.date(2004,12,10))
    # high_z_list = [z_list[i] for i in list(high_z_i[0]) if z_list[i] > z_cutoff]

    n, bins, patches = plt.hist(plt.array(high_z_list), bins=bins, facecolor="black", edgecolor="black")

    high_z_list = [z for z in z_list if z > z_cutoff]

    if high_z_list:  # if there are any high-z's, plot them
        n, bins, patches = plt.hist(plt.array(high_z_list), facecolor="black", edgecolor="black")

    axins.set_xlim(z_cutoff, 9.0)
    # mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")

    # axins2.set_xlabel("Time since Big Bang [Gyr]",fontsize=20)
    ylabels = ax.get_yticklabels()
    plt.setp(ylabels, size=14, name="times", weight="light", color="k")

    xlabels = ax.get_xticklabels()
    plt.setp(xlabels, size=14, name="times", weight="light", color="k")

    xlabels = ax2.get_xticklabels()
    plt.setp(xlabels, size=14, name="times", weight="light", color="k")

    xlabels = ay.get_yticklabels()
    plt.setp(xlabels, size=14, name="times", weight="light", color="k")

    plt.savefig("z_plot.eps")
    plt.draw()
    return z_list