Exemple #1
0
    def _bp_all_timepoints(time_dfs, bp_positions, feat, colors):
        """
        Plot progression score distributions per time point as boxplots.

        :param time_dfs: Dictionary storing the calculated progression scores per time point.
        :param bp_positions: List storing the boxplot positions
        :param feat: Feature name for which plot shall be created.
        :param colors: Iterable storing the colors that shall be used for visualizing. One color per dataset in the \
        DataCollection.
        :return:
        """

        timepoints = list(time_dfs.keys())
        timepoints.sort()

        for time, bp_time_pos in zip(timepoints, bp_positions):

            # prepare data for plotting: extract feature data and exclude NaN's and inf's
            time_data = [timepoint[feat].replace(np.inf, np.nan).dropna() for timepoint in time_dfs[time]]

            # create boxplots, i iterates over the number of different datasets
            for i in range(len(time_data)):

                # check and skip dataset for current time point if no data is available
                if len(time_data[i]) > 1:
                    # create boxplot at specific position
                    bp = plt.boxplot(time_data[i], positions=[bp_time_pos[i]], patch_artist=True, widths=0.6)

                    # change boxplot outline colors
                    for bp_part in ['boxes', 'whiskers', 'fliers', 'caps']:
                        for element in bp[bp_part]:
                            plt.setp(element, color=colors[i])
                else:
                    continue
Exemple #2
0
def boxplot(data, x, y, figsize=(10, 8), xticklabels=None,
            savefile=None, box_quantiles=None, notch=False):
    fig, ax = plt.subplots(1)
    whis = (1, 99) if box_quantiles is not None else 1.5
    sns.boxplot(x=x, y=y, data=data, notch=notch,
                linewidth=2, width=0.4, whis=whis)
    prettify(figsize)

    for i, artist in enumerate(ax.artists):
        # Set the linecolor on the artist to the facecolor, and set the facecolor to None
        # col = artist.get_facecolor()
        col = (0.0, 0.0, 0.0)
        artist.set_edgecolor((0.0, 0.0, 0.0))
        artist.set_facecolor('None')

        # Each box has 6 associated Line2D objects (to make the whiskers, fliers, etc.)
        # Loop over them here, and use the same colour as above
        for j in range(i * 6, i * 6 + 6):
            line = ax.lines[j]
            line.set_color(col)
            line.set_mfc(col)
            line.set_mec(col)

    plt.xlabel('')
    if xticklabels is not None:
        ax.set_xticklabels(xticklabels)
    plt.setp(ax.get_xticklabels(), rotation=0, horizontalalignment='center')

    if savefile is not None:
        plt.savefig(savefile, format='eps', bbox_inches='tight')
Exemple #3
0
def pie(codes,pounds,filename):

	plt.xlabel("Date")
	plt.ylabel("Pound")
	fig = plt.figure(facecolor='white')

	ax = fig.add_axes([0.05, 0.0, 0.80, 0.94])

	# Set graph label size
	matplotlib.rcParams['font.size'] = 7

	# Generate pie chart
	patches, texts, autotexts = ax.pie(pounds,labels=codes, autopct='%1.1f%%')
	
	# Don't show percentages on pie chart
	proptease = fm.FontProperties()
	proptease.set_size('0')
	plt.setp(autotexts, fontproperties=proptease)

	# Set graph size
	F = pylab.gcf()
	DefaultSize = F.get_size_inches()
	F.set_size_inches( (DefaultSize[0]*0.7, DefaultSize[1]*0.7) )
	
	# Save graph
	plt.savefig(filename) 
	plt.close()
Exemple #4
0
    def plot_std_meshlines(self, step=0.1):
        '''
        plot mesh circles for stdv
        '''

        color = self.std_color

        nstdmax = self.stdmax
        if self.negative:
            axmin = -np.pi / 2.
        else:
            axmin = 0.

        th = np.arange(axmin, np.pi / 2, 0.01)

        for ra in np.arange(0, nstdmax + 0.1 * step, step):
            self.ax.plot(ra * np.sin(th), ra * np.cos(th), ':', color=color)

        if self.normalize:
            self.ax.set_ylabel('$\sigma / \sigma_{obs}$', color=color)
            self.ax.set_xlabel('$\sigma / \sigma_{obs}$', color=color)
        else:
            self.ax.set_ylabel('Standard Deviation', color=color)
            self.ax.set_xlabel('Standard Deviation', color=color)

        xticklabels = plt.getp(plt.gca(), 'xticklabels')
        plt.setp(xticklabels, color=color)
        yticklabels = plt.getp(plt.gca(), 'yticklabels')
        plt.setp(yticklabels, color=color)
Exemple #5
0
    def plot_std_meshlines(self, step=0.1):
        '''
        plot mesh circles for stdv
        '''

        color = self.std_color

        nstdmax = self.stdmax
        if self.negative:
            axmin = -np.pi / 2.
        else:
            axmin = 0.

        th = np.arange(axmin, np.pi / 2, 0.01)

        for ra in np.arange(0, nstdmax + 0.1 * step, step):
            self.ax.plot(ra * np.sin(th), ra * np.cos(th), ':', color=color)

        if self.normalize:
            self.ax.set_ylabel('$\sigma / \sigma_{obs}$', color=color)
            self.ax.set_xlabel('$\sigma / \sigma_{obs}$', color=color)
        else:
            self.ax.set_ylabel('Standard Deviation', color=color)
            self.ax.set_xlabel('Standard Deviation', color=color)

        xticklabels = plt.getp(plt.gca(), 'xticklabels')
        plt.setp(xticklabels, color=color)
        yticklabels = plt.getp(plt.gca(), 'yticklabels')
        plt.setp(yticklabels, color=color)
    def plot_correlation(self, metric=None):
        """
        Make a correlation plot. Shows you the correlation between all the word embeddings. Can
        also be configured to show distances instead.

        Arguments:
            metric: don't plot correlation but a distance measure, must be scipy compatible (cosine, euclidean, etc)

        Usage:

        ```python
        from whatlies.language import SpacyLanguage
        lang = SpacyLanguage("en_core_web_md")

        names = ['red', 'blue', 'green', 'yellow', 'cat', 'dog', 'mouse', 'rat', 'bike', 'car']
        emb = lang[names]
        emb.plot_correlation()
        ```

        ![](https://rasahq.github.io/whatlies/images/corrplot.png)
        """
        df = self.to_dataframe().T
        corr_df = (
            pairwise_distances(self.to_matrix(), metric=metric) if metric else df.corr()
        )

        fig, ax = plt.subplots()
        plt.imshow(corr_df)
        plt.xticks(range(len(df.columns)), df.columns)
        plt.yticks(range(len(df.columns)), df.columns)
        plt.colorbar()

        # Rotate the tick labels and set their alignment.
        plt.setp(ax.get_xticklabels(), rotation=90, ha="right", rotation_mode="anchor")
        plt.show()
Exemple #7
0
def caculate_distance_threshold(distance_list):
    distance_list.sort()
    # 画平滑前的密度序列图(未归一化)
    pl.figure(figsize=Utility.figure_size)
    l = pl.plot(distance_list, 'og')
    pl.setp(l, markersize=3)
    pl.xlabel('sequence')
    pl.ylabel('density')
    pl.show()
    max_potential = max(distance_list)
    kernel = Utility.generate_gaus_kernel(4)
    smoothed_potential_list = Utility.calculate_conv(distance_list, kernel)
    # 画平滑后的密度序列图
    pl.figure(figsize=Utility.figure_size)
    l2 = pl.plot(smoothed_potential_list, 'og')
    pl.setp(l2, markersize=3)
    pl.xlabel('sequence')
    pl.ylabel('density')
    pl.show()
    curvature_index = Utility.calculate_curvature3(smoothed_potential_list,
                                                   True)

    if curvature_index > 0:
        threshold_candid = smoothed_potential_list[curvature_index]
        if max_potential / threshold_candid > 2:
            print '*' * 30
            print max_potential
            print threshold_candid
            print '*' * 30
            threshold_candid = max_potential / math.sqrt(2)
        threshold = threshold_candid
        return threshold
    else:
        return -1
Exemple #8
0
def test2():
    mu = 10.0
    sigma = 2.0

    x = Variable("x", float)
    loggauss = -0.5 * math.log(2.0 * math.pi * sigma * sigma) - 0.5 * (
        (x - mu)**2) / (sigma * sigma)

    f = Function(name="foo", params=(x, ), rettype=float, expr=loggauss)
    engine = create_execution_engine()
    module = f.compile(engine)
    func_ptr = engine.get_pointer_to_function(module.get_function("foo"))

    samples = metropolis_hastings(func_ptr, sigma, 0.0, 1000, 2)
    #plt.plot(np.arange(len(samples)), samples)

    n, bins, patches = plt.hist(samples[500:],
                                25,
                                normed=1,
                                histtype='stepfilled')
    plt.setp(patches, 'facecolor', 'g', 'alpha', 0.75)

    # add a line showing the expected distribution
    y = plt.normpdf(bins, mu, sigma)
    l = plt.plot(bins, y, 'k--', linewidth=1.5)
    plt.show()
    def __init__(self, ax, collection, mmc, img):
        self.colornormalizer = Normalize(vmin=0, vmax=1, clip=False)
        self.scat = plt.scatter(img[:, 0], img[:, 1], c=mmc.classvec)
        plt.gray()
        plt.setp(ax.get_yticklabels(), visible=False)
        ax.yaxis.set_tick_params(size=0)
        plt.setp(ax.get_xticklabels(), visible=False)
        ax.xaxis.set_tick_params(size=0)
        self.img = img
        self.canvas = ax.figure.canvas
        self.collection = collection
        #self.alpha_other = alpha_other
        self.mmc = mmc
        self.prevnewclazz = None

        self.xys = collection
        self.Npts = len(self.xys)
        
        self.lockedset = set([])

        self.lasso = LassoSelector(ax, onselect=self.onselect)#, lineprops = {:'prism'})
        self.lasso.disconnect_events()
        self.lasso.connect_event('button_press_event', self.lasso.onpress)
        self.lasso.connect_event('button_release_event', self.onrelease)
        self.lasso.connect_event('motion_notify_event', self.lasso.onmove)
        self.lasso.connect_event('draw_event', self.lasso.update_background)
        self.lasso.connect_event('key_press_event', self.onkeypressed)
        #self.lasso.connect_event('button_release_event', self.onrelease)
        self.ind = []
        self.slider_axis = plt.axes(slider_coords, visible = False)
        self.slider_axis2 = plt.axes(obj_fun_display_coords, visible = False)
        self.in_selection_slider = None
        newws = list(set(range(len(self.collection))) - self.lockedset)
        self.mmc.new_working_set(newws)
        self.lasso.line.set_visible(False)
Exemple #10
0
def plot_gauss(no):
    seq = 1
    if no==1:
        n = str(no)
        n = n.zfill(3)
        imtype ='IIM'+n
    elif no<1000:
        n = str(no)
        n = n.zfill(3)
        imtype = 'IIM'+n
    else:
        imtype = 'II'+str(no)

    print 'doing '+imtype
    testImg = WAIPSImage('J0528+2200', imtype, 1, seq,43)
    dat = testImg.pixels.flatten()
    end_1, end_2 = np.array([dat.size*0.1,dat.size*0.9],dtype=int)
    mu=np.mean(dat[end_1:end_2])
    sigma=stats.tstd(dat[end_1:end_2])
    peak = np.max(dat)
    print 'peak:', np.max(dat), 'rms: ', sigma, 'snr: ', peak/sigma
    plt.figure()
    n,bins,patches = plt.hist(dat,100,normed=1,histtype='stepfilled')
    plt.setp(patches,'facecolor','g','alpha',0.75)
    y = plt.normpdf(bins,mu,sigma)
    plt.plot(bins,y,'k--',linewidth=1.5)
    plt.show()
Exemple #11
0
def plot_datetime_histogram(times,
                            step,
                            strftime_formatter="%H:%M",
                            density=False,
                            normalizer=1,
                            title="",
                            show=True):
    """
        Plot an histogram of a sequence of datetime.datetime objects

        Parameters
        ----------
            times: list of datetime.datetime objects, non-optional
                List of values on which the histogram is going to be calculates
            step: int, non-optional
                Step of time on wich the histogram is going to be divided.
            strftime_formatter: string, optional. Default:'%H:%M'
                Formatter used to show the time in the x-axes, on default shows time as HH:MM
            densitity: boolean, optional. Default False.
                If the histogram should be normalized or not."""
    def lower_p(a, p):
        return p * math.floor(a / p)

    times.sort()
    t_min, t_max = times[0], times[-1]
    r1, r2 = lower_p(t_min.minute, step), lower_p(t_max.minute, step)
    t_min, t_max = (
        t_min.replace(minute=r1, second=0, microsecond=0),
        t_max.replace(minute=r2, second=0, microsecond=0) +
        dt.timedelta(minutes=step),
    )

    t_min, t_max = t_min.timestamp(), t_max.timestamp()

    times = list(map(lambda date: date.timestamp(), times))
    bins = np.arange(start=t_min, stop=t_max, step=(step * 60))
    counts, _ = np.histogram(times, bins=bins, density=density)
    counts = counts / normalizer

    fig, ax = plt.subplots(figsize=(10, 6.5))
    ax.bar((bins[:-1] + (60 * step) / 2),
           counts,
           step * 60,
           color="salmon",
           edgecolor="black",
           linewidth="2")
    ax.set_xticks(bins)
    _xticks = [dt.datetime.fromtimestamp(stamp) for stamp in bins]
    _xticks = [date.strftime(strftime_formatter) for date in _xticks]
    ax.set_xticklabels(_xticks)
    plt.setp(ax.get_xticklabels(),
             rotation=45,
             ha="right",
             rotation_mode="anchor")
    ax.set_title(title)

    ax.grid("on")
    fig.tight_layout()
    if show: plt.show()
    return
Exemple #12
0
def interev_mag(times, mags):
    r"""Function to plot interevent times against magnitude for given times
    and magnitudes.

    :type times: list of datetime
    :param times: list of the detection times, must be sorted the same as mags
    :type mags: list of float
    :param mags: list of magnitudes
    """
    l = [(times[i], mags[i]) for i in xrange(len(times))]
    l.sort(key=lambda tup: tup[0])
    times = [x[0] for x in l]
    mags = [x[1] for x in l]
    # Make two subplots next to each other of time before and time after
    fig, axes = plt.subplots(1, 2, sharey=True)
    axes = axes.ravel()
    pre_times = []
    post_times = []
    for i in range(len(times)):
        if i > 0:
            pre_times.append((times[i] - times[i - 1]) / 60)
        if i < len(times) - 1:
            post_times.append((times[i + 1] - times[i]) / 60)
    axes[0].scatter(pre_times, mags[1:])
    axes[0].set_title('Pre-event times')
    axes[0].set_ylabel('Magnitude')
    axes[0].set_xlabel('Time (Minutes)')
    plt.setp(axes[0].xaxis.get_majorticklabels(), rotation=30)
    axes[1].scatter(pre_times, mags[:-1])
    axes[1].set_title('Post-event times')
    axes[1].set_xlabel('Time (Minutes)')
    plt.setp(axes[1].xaxis.get_majorticklabels(), rotation=30)
    plt.show()
Exemple #13
0
def render_21_output(
    ax, fig, y_out, M=100, y0range=[-1, 1], y1range=[-1, 1], cmap=None,
):
    img = ax.imshow(
        np.reshape(y_out, [M, M]),
        origin='lower',
        extent=[y0range[0], y0range[1], y1range[0], y1range[1]],
        cmap=cmap,
    )
    ax.set_xlabel(r'$y_1$')
    ax.set_ylabel(r'$y_2$')
    axins1 = inset_axes(
        ax,
        width="40%",  # width = 50% of parent_bbox width
        height="5%",  # height : 5%
        loc='upper right',
    )

    imgmin = np.min(y_out)
    imgmax = np.max(y_out)
    color_bar = fig.colorbar(
        img,
        cax=axins1,
        orientation="horizontal",
        ticks=np.linspace(imgmin, imgmax, 3),
    )
    cbxtick_obj = plt.getp(color_bar.ax.axes, 'xticklabels')
    plt.setp(cbxtick_obj, color="white")
    axins1.xaxis.set_ticks_position("bottom")
Exemple #14
0
    def plot_spectra(self,
                     ax=None,
                     glat=0,
                     glon=(0, 2, -2, 30, -30, 90, -90),
                     erange=None,
                     title=None,
                     label=None):
        """ show spectral for give glat, various glon values """
        from matplotlib import pylab as plt
        if not self.loaded: self.load()
        ee = np.logspace(1.5, 6, 101) if erange is None else erange
        if ax is None:
            fig, ax = plt.subplots(1, 1, figsize=(5, 5))
        else:
            fig = ax.figure
        for x in glon:
            sd = skymaps.SkyDir(glat, x, skymaps.SkyDir.GALACTIC)
            ax.loglog(ee,
                      map(lambda e: e**2 * self(sd, e), ee),
                      label='b=%.0f' % x if label is None else label)
            # if hasattr(self, 'energies'):
            #     et = self.energies
            #     ax.loglog(et, map(lambda e: e**2*self(sd,e), et), '--')

        ax.grid()
        if len(glon) > 1:
            ax.legend(loc='lower left', prop=dict(size=10))
        plt.setp(
            ax,
            xlabel=r'$\mathrm{Energy\ [MeV]}$',
            ylabel=r'$\mathrm{E^2\ df/dE\ [Mev\ cm^{-2}\ s^{-1}\ sr^{-1}]}$')
        ax.set_title('Galactic diffuse at l=%.0f' %
                     glat if title is None else title,
                     size=12)
        return fig
Exemple #15
0
def snIaspec_with_medbands(z = 1.2):
    """ plot a SNIa spectrum at the given z, overlaid with medium bands
    matching the SN Camille obs set.
    :param z:
    :return:
    """
    import stardust
    from demofig import w763,f763,w845,f845,w139,f139
    w1a, f1a = stardust.snsed.getsed( sedfile='/usr/local/SNDATA_ROOT/snsed/Hsiao07.dat', day=0 )

    w1az = w1a * (1+z)
    f1az = f1a / f1a.max() / 2.
    ax18 = pl.gca() # subplot(3,2,1)
    ax18.plot(w1az, f1az, ls='-', lw=0.7, color='0.5', label='_nolegend_')
    ax18.plot(w763, f763, ls='-', color='DarkOrchid',label='F763M')
    ax18.plot(w845, f845, ls='-',color='Teal', label='F845M')
    ax18.plot(w139, f139, ls='-',color='Maroon', label='F139M')
    #ax18.fill_between( w1az, np.where(f763>0.01,f1az,0), color='DarkOrchid', alpha=0.3 )
    #ax18.fill_between( w1az, f1az, where=((w1az>13500) & (w1az<14150)), color='teal', alpha=0.3 )
    #ax18.fill_between( w1az, f1az, where=((w1az>15000) & (w1az<15700)), color='Maroon', alpha=0.3 )
    ax18.text(0.95,0.4, 'SNIa\n@ z=%.1f'%(z), color='k',ha='right',va='bottom',fontweight='bold', transform=ax18.transAxes, fontsize='large')
    ax18.set_xlim( 6500, 16000 )
    pl.setp(ax18.get_xticklabels(), visible=False)
    pl.setp(ax18.get_yticklabels(), visible=False)
    ax18.text( 7630, 0.65, 'F763M', ha='right', va='center', color='DarkOrchid', fontweight='bold')
    ax18.text( 8450, 0.65, 'F845M', ha='center', va='center', color='Teal', fontweight='bold')
    ax18.text( 13900, 0.65, 'F139M', ha='left', va='center', color='Maroon', fontweight='bold')
Exemple #16
0
def plot_flexure(flexfile, plotdir):
    import matplotlib.dates as md

    xfmt = md.DateFormatter('%d %b %H h')

    flexure = np.genfromtxt(flexfile, dtype=None, delimiter=",")

    dateflex = []
    for fl in flexure:
        #Format of the file: ifu20160630_00_08_38
        t = datetime.datetime.strptime(fl["f1"], 'ifu%Y%m%d_%H_%M_%S.pos')
        dateflex.append(t)

    plt.plot(dateflex, flexure["f2"], "o-")
    plt.xlabel("Date")
    plt.ylabel("Median (flexure) [pixels]")
    plt.gca().xaxis.set_major_formatter(xfmt)
    labels = plt.gca().get_xticklabels()
    plt.setp(labels, rotation=30, fontsize=10)

    curdate = datetime.datetime.strftime(dateflex[-1], "%Y%m%d")

    plt.savefig(os.path.join(plotdir, "flexure_%s.png" % curdate),
                bbox_inches='tight')

    plt.clf()
Exemple #17
0
    def _set_legend(self):

        legend = plt.legend(loc=1, fontsize=12, fancybox=True, shadow=True)
        frame = legend.get_frame()
        legend.set_frame_on(True)
        frame.set_facecolor('white')
        plt.setp(legend.get_title(), fontsize=12)
Exemple #18
0
def plotStuff(data, labels, title):
    fig, ax = plt.subplots()
    im = ax.imshow(data)

    # We want to show all ticks...
    ax.set_xticks(np.arange(len(labels)))
    ax.set_yticks(np.arange(len(labels)))
    # ... and label them with the respective list entries
    ax.set_xticklabels(labels, size=14)
    ax.set_yticklabels(labels, size=14)

    # Rotate the tick labels and set their alignment.
    plt.setp(ax.get_xticklabels(),
             rotation=45,
             ha="right",
             rotation_mode="anchor")

    # Loop over data dimensions and create text annotations.
    for i in range(len(labels)):
        for j in range(len(labels)):
            text = ax.text(j,
                           i,
                           data[i, j],
                           ha="center",
                           va="center",
                           color="dimgrey",
                           size=14)
    ax.set_title(title, size=14)
    fig.tight_layout()
    plt.show()
    return ()
Exemple #19
0
def plot_ti_auc(fs, betas, name="", lower_bound=True):
    # colors = cm.rainbow(np.linspace(0, 1, len(betas)))
    colors = cm.viridis(np.linspace(0, 1, len(betas)))
    fig, ax = plt.subplots(figsize=(6, 3))
    patches = ax.bar(betas[:-1],
                     fs,
                     width=betas[1:] - betas[:-1],
                     align="edge")
    for i in range(len(betas) - 1):
        patches[i].set_facecolor(colors[i])

    if lower_bound:
        text = r"$\sum_k F_k = {:.2f}$".format(np.sum(fs))
        ylabel = r"$F_{k}$"
    else:
        text = r"$\sum_k \tilde{{F}}_k = {:.2f}$".format(np.sum(fs))
        ylabel = r"$\tilde{{F}}_{k}$"
    text_box = AnchoredText(
        text,
        frameon=False,
        loc=4,
        pad=0,
        prop={"size": 12},
    )
    plt.setp(text_box.patch, facecolor="white", alpha=0.5)
    plt.gca().add_artist(text_box)

    plt.xlabel(r"$\beta$")
    plt.ylabel(ylabel)
    plt.savefig("/tmp/{}.pdf".format(name), bbox_inches="tight", pad_inches=0)
Exemple #20
0
def startAnim(x, m, th, Tsim, inter=1, Tstart=0, h=0.002):
#    fig, axM = subplo1ts()
#    axX = axM.twinx()
    fig = figure()
    axM = subplot(211)
    axX = subplot(212, sharex=axM)
    anim = MyAnim(x, m, th, Tsim, inter, Tstart/h, h)

    anim.line1, = axM.plot([], [], 'b')
    anim.line2, = axX.plot([], [], 'g')
    setp(axM.get_xticklabels(), visible=False)
    axM.set_xlim([-pi, pi])
    axX.set_xlim([-pi, pi])
#    axM.set_ylim([0., 3])
#    axX.set_ylim([0., 1.])
    axM.set_ylim([amin(m), amax(m)])
    axX.set_ylim([amin(x), amax(x)])

    axM.set_ylabel(r"$m$")
    axX.set_ylabel(r"$x$")
    axX.set_xlabel(r"$\theta$")
    hold(False)
    for tl in axM.get_yticklabels():
        tl.set_color('b')
    for tl in axX.get_yticklabels():
        tl.set_color('g')
    anim.axM = axM
    anim.axX = axX
    fig.canvas.mpl_connect('button_press_event', anim.onClick)
    a = FuncAnimation(fig, anim, frames=anim.dataGen, init_func=anim.init,
                 interval=0, blit=True, repeat=True)
    show()
    return a
Exemple #21
0
def spy(A, linespec='b.', tol=1e-4, Xm=None, Ym=None, ax=None):
    """Return figure showing which elements in array are non-zero"""
    #import pdb
    A = np.asarray(A)

    ax = ax if not ax == None else plt.gca()

    if len(A.shape) != 2:
        raise err.InputError("", "Iinput array must be 2D")

    Ny, Nx = A.shape

    if Xm == None:
        Xm = (np.arange(0, A.shape[1]) + 0.5).reshape(1, Nx) * np.ones((Ny, 1))
    else:
        if not np.all(A.shape == Xm.shape):
            raise err.InputError(
                "", "shape of input array must match shape of Xm")
    if Ym == None:
        Ym = (np.arange(0, Ny) + 0.5)[::-1].reshape(Ny, 1) * np.ones((1, Nx))
    else:
        if not np.all(A.shape == Ym.shape):
            raise err.InputError("",
                                 "shape of input aray must match shape of Ym")
    #pdb.set_trace()
    I = np.logical_not(np.logical_and(A > -tol, A < tol))

    plt.setp(ax, 'xlim', (Xm[0, 0], Xm[0, -1]), 'ylim', (Ym[-1, 0], Ym[0, 0]))

    plt.plot(Xm[I], Ym[I], linespec)
Exemple #22
0
    def PlotConnectivityProperties(self):

        #self._AverageConnectivity.append(nx.average_node_connectivity(self._Network))
        plt.figure(self._FigureNumber)
        self._FigureNumber += 1

        plt.subplot(131)
        self._DegreeDistribution = sorted(nx.degree(self._Network).values(),reverse=True)
        p=plt.loglog(self._DegreeDistribution,'-',marker='o')
        plt.setp(p,color='darkblue')

        plt.title("Degree rank plot")
        plt.ylabel("degree")
        plt.xlabel("rank")

        plt.subplot(132)
        plt.hist([n._SynapseCount for n in self._Neurons], 20,facecolor='lightblue', alpha=0.75, edgecolor='darkblue')
        plt.title('Distribution of number of synapses formed')
        plt.xlabel('Number of synapses')
        plt.ylabel('Count')
        plt.xlim( (0, 1200) )

        plt.subplot(133)
        weights = [self._Network.get_edge_data(n1,n2,default=0)['weight'] for n1,n2 in self._Network.edges()]
        plt.hist(weights, 20, facecolor='lightblue', alpha=0.75, edgecolor='darkblue')
        plt.title('Distribution of edge weights')
        plt.xlabel('Edge weight')
        plt.ylabel('Count')
        plt.xlim( (0, 1200) )
Exemple #23
0
    def plot(self,file):
        cds = CaseDataset(file, 'bson')
        data = cds.data.driver('driver').by_variable().fetch()
        cds2 = CaseDataset('../output/therm_mc_20141110173851.bson', 'bson')
        data2 = cds2.data.driver('driver').by_variable().fetch()
        
        #temp
        temp_boundary_k = data['hyperloop.temp_boundary']
        temp_boundary_k.extend(data2['hyperloop.temp_boundary'])
        temp_boundary = [((x-273.15)*1.8 + 32) for x in temp_boundary_k]
        #histogram
        n, bins, patches = plt.hist(temp_boundary, 100, normed=1, histtype='stepfilled')
        plt.setp(patches, 'facecolor', 'b', 'alpha', 0.75)

        #stats
        mean = np.average(temp_boundary)
        std = np.std(temp_boundary)
        percentile = np.percentile(temp_boundary,99.5)
        print "mean: ", mean, " std: ", std, " 99.5percentile: ", percentile
        x = np.linspace(50,170,150)
        plt.plot(x,mlab.normpdf(x,mean,std), color='black', lw=2)
        plt.xlim([60,160])
        plt.ylabel('Probability', fontsize=18)
        plt.xlabel(u'Equilibrium Temperature, \N{DEGREE SIGN}F', fontsize=18)
        #plt.show()
        plt.tight_layout()
        plt.savefig('../output/histo.pdf', dpi=300)
def axis_settings(subax, info_dict, label=False, region=None):
    subax.set_xlim((-0.5, 3.5))
    subax.set_ylim((-10, 30))
    subax.set_xticks([0, 1, 2, 3])
    subax.set_xticklabels([
        state + '\n' + str(info_dict[state]['excee']) + '-days'
        for state in ['warm', 'dry', 'dry-warm', '5mm']
    ])
    if region == 'mid-lat':
        subax.set_ylabel('rel. change in\nExceedence probability [%]',
                         fontsize=10)
        subax.tick_params(axis='x',
                          labelsize=9,
                          colors='k',
                          size=1,
                          rotation=90)
        subax.tick_params(axis='y', labelsize=10, colors='k', size=1)
        subax.yaxis.get_label().set_backgroundcolor('w')
        bbox = dict(boxstyle="round", ec="w", fc="w", alpha=1)
        plt.setp(subax.get_yticklabels(), bbox=bbox)
    else:
        subax.set_yticklabels([])
        subax.set_xticklabels([])
    subax.locator_params(axis='y', nbins=5)
    subax.grid(True, which="both", ls="--", c='gray', lw=0.35)
    subax.axhline(y=0, c='gray')
    return (subax)
Exemple #25
0
def Build_Type_Graphs(Tweet_Type_Per_File_Dict,File_Name_Map):
    # Calculate Distribution from dict:
    import pandas as pd
    Agg_Type_df = pd.DataFrame(Tweet_Type_Per_File_Dict)
    Agg_Type_df = Agg_Type_df.rename({0:'Monologue', 1:'Reply', 2:'Quote', 3:'Mix'},axis=0)
    Agg_Type_df = Agg_Type_df.rename(File_Name_Map,axis=1)
    Agg_Type_Pct_df = Agg_Type_df.apply(lambda x: x/x.sum(), axis=0)

    import seaborn as sns

    sns.set(style="ticks", palette="pastel")

    data = []
    for row in Agg_Type_Pct_df.iterrows():
        ttype = row[0]
        user = [x for x in row[1].index]
        pct = [x for x in row[1].array]
        for n in range(0,len(row[1])):
            data.append((user[n], ttype, pct[n]))
    flat_df = pd.DataFrame(data, columns=['User', 'Tweet Type', 'Percentage'])

    import matplotlib as plt
    import matplotlib.pylab as pyl
    plt.rc('ytick', labelsize=5.5)
    plt.rc('ytick', labelsize=5.5)

    ax = sns.scatterplot(data=flat_df, x="Percentage", y="User", hue="Tweet Type")
    ax.set_aspect(aspect=0.04)
    pyl.setp(ax.get_legend().get_texts(), fontsize='6') # for legend text
    pyl.setp(ax.get_legend().get_title(), fontsize='8') # for legend title

    pyl.savefig('Tweet Pcts.png')
    return(0)
Exemple #26
0
def plot_cm_results(freqs, locs, train_histories, note=''):
    acc_matrix = np.array([entry[1][1]
                           for scn, entry in train_histories]).reshape((3, 3))

    fig, ax = plt.subplots()
    im = ax.imshow(acc_matrix, vmin=0, vmax=1)

    # We want to show all ticks...
    ax.set_xticks(np.arange(len(freqs)))
    ax.set_yticks(np.arange(len(locs)))
    # ... and label them with the respective list entries
    ax.set_xticklabels(freqs, size=18)
    ax.set_yticklabels(locs, size=18)

    # Rotate the tick labels and set their alignment.
    plt.setp(ax.get_xticklabels(),
             rotation=45,
             ha="right",
             rotation_mode="anchor")

    # Loop over data dimensions and create text annotations.
    for i in range(len(locs)):
        for j in range(len(freqs)):
            text = ax.text(j,
                           i,
                           round(acc_matrix[i, j], 3),
                           ha="center",
                           va="center",
                           color="black",
                           size=20)

    ax.set_title("Three motion classification accuracies " + note, size=15)
    # fig.tight_layout()
    plt.show()
def plot_mnist(X, y, X_embedded, name, min_dist=10.0):
    fig = plt.figure(figsize=(10, 10))
    ax = plt.axes(frameon=False)
    plt.title("\\textbf{MNIST dataset} -- Two-dimensional "
          "embedding of 70,000 handwritten digits with %s" % name)
    plt.setp(ax, xticks=(), yticks=())
    plt.subplots_adjust(left=0.0, bottom=0.0, right=1.0, top=0.9,
                    wspace=0.0, hspace=0.0)
    plt.scatter(X_embedded[:, 0], X_embedded[:, 1],
            c=y, marker="x")

    if min_dist is not None:
        from matplotlib import offsetbox
        shown_images = np.array([[15., 15.]])
        indices = np.arange(X_embedded.shape[0])
        np.random.shuffle(indices)
        for i in indices[:5000]:
            dist = np.sum((X_embedded[i] - shown_images) ** 2, 1)
            if np.min(dist) < min_dist:
                continue
            shown_images = np.r_[shown_images, [X_embedded[i]]]
            imagebox = offsetbox.AnnotationBbox(
                offsetbox.OffsetImage(X[i].reshape(28, 28),
                                      cmap=plt.cm.gray_r), X_embedded[i])
            ax.add_artist(imagebox)
Exemple #28
0
    def OnButtonTidyButton(self, event):
        
        # for easy coding
        T = self.TreeCtrlMain
        s = T.GetSelection()
        f = self.GetTreeItemData(s, "figure") 
        w = self.GetTreeItemData(s, "window")
        
        # set the current figure
        pylab.figure(f.number)
        
        # first set the size of the window
        w.SetSize([500,500])
        
        # now loop over all the data and get the range
        lines = f.axes[0].get_lines()
        
        # we want thick lines
        f.axes[0].get_frame().set_linewidth(3.0)

        # get the tick lines in one big list
        xticklines = f.axes[0].get_xticklines()
        yticklines = f.axes[0].get_yticklines()
        
        # set their marker edge width
        pylab.setp(xticklines+yticklines, mew=2.0)
        
        # set what kind of tickline they are (outside axes)
        for l in xticklines: l.set_marker(matplotlib.lines.TICKDOWN)
        for l in yticklines: l.set_marker(matplotlib.lines.TICKLEFT)
        
        # get rid of the top and right ticks
        f.axes[0].xaxis.tick_bottom()
        f.axes[0].yaxis.tick_left()
        
        # we want bold fonts
        pylab.xticks(fontsize=20, fontweight='bold', fontname='Arial')
        pylab.yticks(fontsize=20, fontweight='bold', fontname='Arial')

        # we want to give the labels some breathing room (1% of the data range)
        for label in pylab.xticks()[1]:
            label.set_y(-0.02)
        for label in pylab.yticks()[1]:
            label.set_x(-0.01)
            
        # set the position/size of the axis in the window
        f.axes[0].set_position([0.1,0.1,0.8,0.8])
        
        # set the axis labels
        f.axes[0].set_title('')
        f.axes[0].set_xlabel('')
        f.axes[0].set_ylabel('')

        # set the position of the legend far away
        f.axes[0].legend(loc=[1.2,0])
        
        f.canvas.Refresh()
        
        # autoscale
        self.OnButtonAutoscaleButton(None)
Exemple #29
0
def generate_time_plot(methods, datasets, runtimes_per_method, colors):
  num_methods = len(methods)
  num_datasets = len(datasets)
  x_ticks = np.linspace(0., 1., num_methods)

  width = 0.6 / num_methods / num_datasets
  spacing = 0.4 / num_methods / num_datasets
  fig, ax1 = plt.subplots()
  ax1.set_ylabel('Time [s]', color='b')
  ax1.tick_params('y', colors='b')
  ax1.set_yscale('log')
  fig.suptitle("Hand-Eye Calibration Method Timings", fontsize='24')
  handles = []
  for i, dataset in enumerate(datasets):
    runtimes = [runtimes_per_method[dataset][method] for method in methods]
    bp = ax1.boxplot(
        runtimes, 0, '',
        positions=(x_ticks + (i - num_datasets / 2. + 0.5) *
                   spacing * 2),
        widths=width)
    plt.setp(bp['boxes'], color=colors[i], linewidth=line_width)
    plt.setp(bp['whiskers'], color=colors[i], linewidth=line_width)
    plt.setp(bp['fliers'], color=colors[i],
             marker='+', linewidth=line_width)
    plt.setp(bp['medians'], color=colors[i],
             marker='+', linewidth=line_width)
    plt.setp(bp['caps'], color=colors[i], linewidth=line_width)
    handles.append(mpatches.Patch(color=colors[i], label=dataset))
  plt.legend(handles=handles, loc=2)

  plt.xticks(x_ticks, methods)
  plt.xlim(x_ticks[0] - 2.5 * spacing * num_datasets,
           x_ticks[-1] + 2.5 * spacing * num_datasets)

  plt.show()
def corr_plot(datum,reef_name,outpath):
    r = 3
    num_blocks = int(np.ceil(np.sqrt(len(datum))))
    fig, ax = plt.subplots(num_blocks,num_blocks, figsize = (20,24))
    xlim = (-r, r)
    ylim = ( -25,0)
    plt.setp(ax, xlim=xlim, ylim=ylim)

    axlist = []
    for axl in ax:
        for axl2 in axl:
            axlist.append(axl2)


    day_keys = list(datum.keys())
    for i,dict_item in enumerate(datum.items()):
        d = dict_item[1][2]
        line = dict_item[1][0]
        meta = dict_item[1][1]

        sns.scatterplot(x = d['diff'], y = d.Height, color = 'blue', ax = axlist[i])
        sns.lineplot(x = [-r,r], y = [line(-r),line(r)], color = 'black', ax = axlist[i])
        axlist[i].set_xlabel('Log(Blue Band) - Log(Green Band)')
        axlist[i].set_ylabel('Depth')
        axlist[i].set_title(str(meta['dt'].date()))
        xt = (list(axlist[i].get_xticks()))[:-1]
        for i,x in enumerate(xt):
            xt[i] = np.round(x,2)

    fn = os.path.join(outpath,'corr_plot.png')
    plt.savefig(fn)
Exemple #31
0
def interev_mag(times, mags):
    r"""Function to plot interevent times against magnitude for given times
    and magnitudes.

    :type times: list of datetime
    :param times: list of the detection times, must be sorted the same as mags
    :type mags: list of float
    :param mags: list of magnitudes
    """
    l = [(times[i], mags[i]) for i in xrange(len(times))]
    l.sort(key=lambda tup: tup[0])
    times = [x[0] for x in l]
    mags = [x[1] for x in l]
    # Make two subplots next to each other of time before and time after
    fig, axes = plt.subplots(1, 2, sharey=True)
    axes = axes.ravel()
    pre_times = []
    post_times = []
    for i in range(len(times)):
        if i > 0:
            pre_times.append((times[i] - times[i - 1]) / 60)
        if i < len(times) - 1:
            post_times.append((times[i + 1] - times[i]) / 60)
    axes[0].scatter(pre_times, mags[1:])
    axes[0].set_title('Pre-event times')
    axes[0].set_ylabel('Magnitude')
    axes[0].set_xlabel('Time (Minutes)')
    plt.setp(axes[0].xaxis.get_majorticklabels(), rotation=30)
    axes[1].scatter(pre_times, mags[:-1])
    axes[1].set_title('Post-event times')
    axes[1].set_xlabel('Time (Minutes)')
    plt.setp(axes[1].xaxis.get_majorticklabels(), rotation=30)
    plt.show()
    def draw(self):
        data_len = len(self.data)
        X = range(data_len)
        data = [float(i) for i in self.data]
        color = self.cp.get("Colors", item_name("Line", self.num))
        line = self.ax.plot(X, data, marker="o", markeredgecolor=color,
            markerfacecolor="white", markersize=13, linewidth=5,
            markeredgewidth=5, color=color, label=self.cp.get("Labels",
            item_name("Legend", self.num)))
        max_ax = max(data)*1.1 if data else 0
        if max_ax <= 10:
            self.ax.set_ylim(-0.1, max_ax)
        else:
            self.ax.set_ylim(-0.5, max_ax)
        self.ax.set_xlim(-1, data_len+1)

        if self.mode == "hourly":
            self.ax.xaxis.set_ticks((0, 8, 16, 24))
        elif self.mode == "daily":
            self.ax.xaxis.set_ticks((0, 15, 30))
        elif self.mode == "monthly":
            self.ax.xaxis.set_ticks((0, 4, 8, 12))
        else:
            raise Exception("Unknown time interval mode.")

        if self.legend:
            legend = self.ax.legend(loc=9, mode="expand",
                bbox_to_anchor=(0.25, 1.02, 1., .102))
            setp(legend.get_frame(), visible=False)
            setp(legend.get_texts(), size=int(self.cp.get("Sizes",
                "LegendSize")))
def plot():

    fig, ax = plt.subplots(figsize=(10, 3))

    df = pd.read_csv("noise_attackRate.csv", header=None)
    toplot = df.values

    index = np.arange(len(eLabels))

    print(toplot)

    ax = plt.axes()

    #For bar
    thisLine = ax.bar(index, toplot[:, 1])

    plt.xlabel(r'$\epsilon(Privacy Loss)$', fontsize=22)
    plt.ylabel("Attack Rate", fontsize=22)

    plt.xticks(index, eLabels)

    plt.yticks(np.arange(0, 1.4, step=0.5))

    plt.setp(ax.get_xticklabels(), fontsize=18)
    plt.setp(ax.get_yticklabels(), fontsize=18)
    plt.tight_layout()
    fig.savefig("fig_noise_krum.pdf")
Exemple #34
0
def plot_inflow(sim, t_f=None, N_profile=5):
    """
    Plot inflow profile at select times


    """
    fig, ax = plt.subplots(1, figsize=(7, 4.5))

    if t_f:
        inds = np.where(sim.t_print < t_f)[0]
    else:
        inds = np.where(np.diff(sim.hc.mean(1).mean(1)) > 1e-6)[0]

    freq = int(len(inds) / N_profile)

    for ind in inds[freq - 1::freq]:
        ax.plot(sim.xc.mean(0),
                sim['hc'].mean(1)[ind],
                next(linecycler),
                label=np.round(sim.t_print[ind] / 60., 1))

    legend = ax.legend(title="time (min)")

    plt.setp(legend.get_title(), fontsize='medium')
    plt.xlabel('x')
    plt.ylabel("h (cm)")
Exemple #35
0
def test2():
    mu = 10.0
    sigma = 2.0

    x = Variable("x", float)
    loggauss = -0.5 * math.log( 2.0 * math.pi * sigma * sigma ) - 0.5 * ((x - mu) ** 2) / (sigma * sigma)

    f = Function(
            name="foo",
            params=(x,),
            rettype=float,
            expr=loggauss)
    engine = create_execution_engine()
    module = f.compile(engine)
    func_ptr = engine.get_pointer_to_function(module.get_function("foo"))

    samples = metropolis_hastings(func_ptr, sigma, 0.0, 1000, 2)
    #plt.plot(np.arange(len(samples)), samples)

    n, bins, patches = plt.hist(samples[500:], 25, normed=1, histtype='stepfilled')
    plt.setp(patches, 'facecolor', 'g', 'alpha', 0.75)

    # add a line showing the expected distribution
    y = plt.normpdf(bins, mu, sigma)
    l = plt.plot(bins, y, 'k--', linewidth=1.5)
    plt.show()
    def draw_plot(self):
        """ Redraws the plot
        """
        # when xmin is on auto, it "follows" xmax to produce a 
        # sliding window effect. therefore, xmin is assigned after
        # xmax.
        #
        xwin_size = 360
        if self.xmax_control.is_auto():
            xmax = len(self.data) if len(self.data) > xwin_size else xwin_size
        else:
            xmax = int(self.xmax_control.manual_value())
            
        if self.xmin_control.is_auto():            
            xmin = xmax - xwin_size
        else:
            xmin = int(self.xmin_control.manual_value())

        # for ymin and ymax, find the minimal and maximal values
        # in the data set and add a mininal margin.
        # 
        # note that it's easy to change this scheme to the 
        # minimal/maximal value in the current display, and not
        # the whole data set.
        # 
        if self.ymin_control.is_auto():
            ymin = round(min(self.data), 0) - 1
        else:
            ymin = int(self.ymin_control.manual_value())
        
        if self.ymax_control.is_auto():
            ymax = round(max(self.data), 0) + 1
        else:
            ymax = int(self.ymax_control.manual_value())

        self.axes.set_xbound(lower=xmin, upper=xmax)
        self.axes.set_ybound(lower=ymin, upper=ymax)
        
        # anecdote: axes.grid assumes b=True if any other flag is
        # given even if b is set to False.
        # so just passing the flag into the first statement won't
        # work.
        #
        if self.cb_grid.IsChecked():
            self.axes.grid(True, color='gray')
        else:
            self.axes.grid(False)

        # Using setp here is convenient, because get_xticklabels
        # returns a list over which one needs to explicitly 
        # iterate, and setp already handles this.
        #  
        pylab.setp(self.axes.get_xticklabels(),
            visible=self.cb_xlab.IsChecked())
        
        self.plot_data.set_xdata(np.arange(len(self.data)))
        self.plot_data.set_ydata(np.array(self.data))
        
        self.canvas.draw()
Exemple #37
0
def heatmap(data, row_labels, col_labels, ax=None,
            cbar_kw={}, cbarlabel="", **kwargs):
  """
  Create a heatmap from a numpy array and two lists of labels.

  Arguments:
      data       : A 2D numpy array of shape (N,M)
      row_labels : A list or array of length N with the labels
                   for the rows
      col_labels : A list or array of length M with the labels
                   for the columns
  Optional arguments:
      ax         : A matplotlib.axes.Axes instance to which the heatmap
                   is plotted. If not provided, use current axes or
                   create a new one.
      cbar_kw    : A dictionary with arguments to
                   :meth:`matplotlib.Figure.colorbar`.
      cbarlabel  : The label for the colorbar
  All other arguments are directly passed on to the imshow call.
  """

  if not ax:
    ax = plt.gca()

  # Plot the heatmap
  im = ax.imshow(data, **kwargs)

  # create an axes on the right side of ax. The width of cax will be 5%
  # of ax and the padding between cax and ax will be fixed at 0.05 inch.
  divider = make_axes_locatable(ax)
  cax = divider.append_axes("right", size="5%", pad=0.05)
  cbar = ax.figure.colorbar(im, ax=ax, cax=cax, **cbar_kw)
  cbar.ax.set_ylabel(cbarlabel, rotation=-90, va="bottom")

  # We want to show all ticks...
  ax.set_xticks(np.arange(data.shape[1]))
  ax.set_yticks(np.arange(data.shape[0]))
  # ... and label them with the respective list entries.
  ax.set_xticklabels(col_labels)
  ax.set_yticklabels(row_labels)

  # Let the horizontal axes labeling appear on top.
  ax.tick_params(top=True, bottom=False,
                 labeltop=True, labelbottom=False)

  # Rotate the tick labels and set their alignment.
  plt.setp(ax.get_xticklabels(), rotation=-30, ha="right",
           rotation_mode="anchor")

  # Turn spines off and create white grid.
  # for edge, spine in ax.spines.items():
  #    spine.set_visible(False)

  ax.set_xticks(np.arange(0 ,data.shape[1 ] +1 ) -0.5, minor=True)
  ax.set_yticks(np.arange(0 ,data.shape[0 ] +1 ) -0.5, minor=True)
  # ax.grid(which="minor", color="w", linestyle='-', linewidth=3)
  # ax.tick_params(which="minor", bottom=False, left=False)

  return im, cbar
Exemple #38
0
def dss(phot, survey='poss1_red', subplot_args=()):
    """
    Grab DSS finder chart and overplot axis
    """

    # Create Figure
    fig = plt.gcf()
    if subplot_args == ():
        subplot_args = (111, )

    try:
        # Download DSS image
        hduL_dss = read_fits_dss(phot, survey=survey)
        header_dss = hduL_dss[0].header
        wcs_dss = astropy.wcs.find_all_wcs(header_dss)[0]
        dss = hduL_dss[0].data

        # Compute verticies of the medframe image used to set limits
        ny, nx = phot.medframe.shape  # row is y, col is x
        wcs_medframe = astropy.wcs.find_all_wcs(phot.header_medframe,
                                                keysel=['binary'])
        wcs_medframe = wcs_medframe[0]
        verts_medframe_pix = np.array([[0, 0], [nx, 0], [nx, ny], [0, ny],
                                       [0, 0]])
        verts_medframe_pix = verts_medframe_pix - 0.5
        verts_medframe_world = wcs_medframe.all_pix2world(
            verts_medframe_pix, 0)
        verts_dss_pix = wcs_dss.all_world2pix(verts_medframe_world, 0)
        mm = lambda x: (np.min(x), np.max(x))
        xl = mm(verts_dss_pix[:, 0])
        yl = mm(verts_dss_pix[:, 1])

        # Make the plot
        ax = fig.add_subplot(*subplot_args, projection=wcs_dss)
        tr_fk5 = ax.get_transform('fk5')
        overlay = ax.get_coords_overlay('fk5')
        overlay['ra'].set_ticks(color='white')
        overlay['dec'].set_ticks(color='white')
        overlay.grid(color='white', linestyle='solid', alpha=0.5)
        plt.plot(phot.ap_verts['ra'],
                 phot.ap_verts['dec'],
                 transform=tr_fk5,
                 color='LimeGreen',
                 lw=2)
        im = plt.imshow(dss, cmap='gray')
        plt.plot(verts_medframe_world[:, 0],
                 verts_medframe_world[:, 1],
                 transform=tr_fk5,
                 color='LightSalmon',
                 lw=2)

        title = '{}, {}\n'.format(survey, header_dss['DATE-OBS'][:4])
        plt.setp(ax, xlim=xl, ylim=yl, title=title, xlabel='RA', ylabel='Dec')

    except:
        ax = fig.add_subplot(*subplot_args)
        error = str(sys.exc_info())
        error = textwrap.fill(error, 50)
        ax.text(0, 1, error, transform=ax.transAxes, va='top')
Exemple #39
0
def show_histogram(values):
    n, bins, patches = plt.hist(values.reshape(-1), 50, normed=1)
    bin_centers = 0.5 * (bins[:-1] + bins[1:])

    for c, p in zip(normalize(bin_centers), patches):
        plt.setp(p, 'facecolor', plt.cm.viridis(c))

    plt.show()
Exemple #40
0
def showGraph(df, decision):
    columns = st.slider('Columns', 5, 40, 10)
    asc = st.checkbox('Lowest to Highest')
    df = df.groupby('state').mean().reset_index()
    df = df.sort_values(by=decision, ascending = asc).head(columns)
    plot = sns.barplot(data=df, x = df['state'], y = df[decision], palette = sns.color_palette(n_colors=1))
    plt.setp(plot.get_xticklabels(), rotation=90)
    st.pyplot()
Exemple #41
0
def dateticks(fmt='%Y-%m', **kwargs):
    '''setup the date ticks'''
    dateticker = ticker.FuncFormatter(lambda numdate, _: num2date(numdate).strftime(fmt))
    pylab.gca().xaxis.set_major_formatter(dateticker)
    # pylab.gcf().autofmt_xdate()
    tmp = dict(rotation=30, ha='right')
    tmp.update(kwargs)
    pylab.setp(pylab.xticks()[1], **tmp)
Exemple #42
0
def heatmap(data, row_labels, col_labels, ax=None,
            cbar_kw={}, cbarlabel="", title = "",  **kwargs):
    """
    Create a heatmap from a numpy array and two lists of labels.
    Arguments:
        data       : A 2D numpy array of shape (N,M)
        row_labels : A list or array of length N with the labels
                     for the rows
        col_labels : A list or array of length M with the labels
                     for the columns
    Optional arguments:
        ax         : A matplotlib.axes.Axes instance to which the heatmap
                     is plotted. If not provided, use current axes or
                     create a new one.
        cbar_kw    : A dictionary with arguments to
                     :meth:`matplotlib.Figure.colorbar`.
        cbarlabel  : The label for the colorbar
    All other arguments are directly passed on to the imshow call.
    """

    if not ax:
        ax = plt.gca()

    # Plot the heatmap
    im = ax.imshow(data, **kwargs)
    ax.set_title(title, pad =50.0)
    # create an axes on the right side of ax. The width of cax will be 5%
    # of ax and the padding between cax and ax will be fixed at 0.05 inch.
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    cbar = ax.figure.colorbar(im, ax=ax, cax=cax, **cbar_kw)
    cbar.ax.set_ylabel(cbarlabel, rotation=-90, va="bottom")

    # We want to show all ticks...
    ax.set_xticks(np.arange(data.shape[1]))
    ax.set_yticks(np.arange(data.shape[0]))
    # ... and label them with the respective list entries.
    ax.set_xticklabels(col_labels)
    ax.set_yticklabels(row_labels)

    # Let the horizontal axes labeling appear on top.
    ax.tick_params(top=True, bottom=False,
                   labeltop=True, labelbottom=False)

    # Rotate the tick labels and set their alignment.
    plt.setp(ax.get_xticklabels(), rotation=-30, ha="right",
             rotation_mode="anchor")

    # Turn spines off and create white grid.
    # for edge, spine in ax.spines.items():
    #    spine.set_visible(False)

    ax.set_xticks(np.arange(0, data.shape[1] + 1) - 0.5, minor=True)
    ax.set_yticks(np.arange(0, data.shape[0] + 1) - 0.5, minor=True)
    # ax.grid(which="minor", color="w", linestyle='-', linewidth=3)
    # ax.tick_params(which="minor", bottom=False, left=False)

    return im, cbar
Exemple #43
0
def plot_data(hist):
    X = np.arange(len(hist))
    plt.bar(X, hist.values(), align='center', width=0.5)
    plt.xticks(X, hist.keys())
    locs, labels = plt.xticks()
    plt.setp(labels, rotation=90)
    ymax = max(hist.values()) + 0.1
    plt.ylim(0, ymax)
    plt.show()
Exemple #44
0
    def create(self, images, x, y, mag, plot=False):
        """Using some input images and a catalog entry, define the pixel aperture for a star."""

        # keep track of the basics of this aperture
        self.x, self.y, self.mag = x, y, mag

        # figure out which label in the labeled image is relevant to this star
        label = images['labeled'][np.round(y), np.round(x)]
        if label == 0:
            self.row, self.col = np.array([np.round(y).astype(np.int)]), np.array([np.round(x).astype(np.int)])
        else:

            # identify and sort the pixels that might contribute
            ok = images['labeled'] == label
            okr, okc = ok.nonzero()
            sorted = np.argsort(images['stars'][ok]/images['noise'][ok])[::-1]

            signal = np.cumsum(images['stars'][ok][sorted])
            noise = np.sqrt(np.cumsum(images['noise'][ok][sorted]**2))
            snr = signal/noise
            mask = ok*0
            toinclude = sorted[:np.argmax(snr)+1]
            mask[okr[toinclude], okc[toinclude]] = 1

            self.row, self.col = okr[toinclude], okc[toinclude]

            if plot:
                fi = plt.figure('selecting an aperture', figsize=(10,3), dpi=100)
                fi.clf()
                gs = gridspec.GridSpec(3,2,width_ratios=[1,.1], wspace=0.1, hspace=0.01, top=0.9, bottom=0.2)
                ax_line = plt.subplot(gs[:,0])
                ax_image = plt.subplot(gs[0,1])
                ax_ok = plt.subplot(gs[1,1])
                ax_mask = plt.subplot(gs[2,1])

                shape = ok.shape
                row, col = ok.nonzero()
                left, right = np.maximum(np.min(col)-1, 0), np.minimum(np.max(col)+2, shape[1])
                bottom, top = np.maximum(np.min(row)-1, 0),  np.minimum(np.max(row)+2, shape[1])

                kwargs = dict( extent=[left, right, bottom, top],  interpolation='nearest')
                ax_image.imshow(np.log(images['median'][bottom:top, left:right]), cmap='gray_r', **kwargs)
                ax_ok.imshow(ok[bottom:top, left:right], cmap='Blues', **kwargs)
                ax_mask.imshow(mask[bottom:top, left:right], cmap='YlOrRd', **kwargs)

                for a in [ax_ok, ax_mask, ax_image]:
                    plt.setp(a.get_xticklabels(), visible=False)
                    plt.setp(a.get_yticklabels(), visible=False)

                ax_line.plot(signal.flatten(), signal.flatten()/noise.flatten(), marker='o', linewidth=1, color='black',alpha=0.5, markersize=10)
                ax_line.set_xlabel('Total Star Flux in Aperture')
                ax_line.set_ylabel('Total Signal-to-Noise Ratio')
                ax_line.set_title('{0:.1f} magnitude star'.format(mag))
                plt.draw()
                self.input('hmmm?')
        self.n = len(self.row)
        logger.info('created {0}'.format(self))
Exemple #45
0
def print_histogram(y, num_bins):   
    # Prints a histogram of input array with equally spaced bins
    
    # Input
    # y: array
    # num_bins: number of bins in histogram
    
    _, _, patches = py.hist(y, num_bins, histtype='stepfilled')
    py.setp(patches, 'facecolor', 'g', 'alpha', 0.75)
    py.show()
 def make_chart(self,data=np.zeros(1),bins=np.arange(10)+1,polar=False):
     self.polar_chart = polar
     self.hist_bins = []
     self.hist_patches = []
     self.x = np.arange(17)
     self.means = np.zeros(self.x.size)
     self.stds = np.zeros(self.x.size)
     
     self.fitting_x = np.linspace(self.x[0], self.x[-1], 100, endpoint=True)
     self.fitting_y = np.zeros(self.fitting_x.size)
     self.fig.clear()
     
     grid = 18
     height = grid // 9
     gs = gridspec.GridSpec(grid, grid)
     # make tuning curve plot
     axes = self.fig.add_subplot(gs[:-height*2,height//2:-height//2],polar=polar)
     if polar:
         self.curve_data = axes.plot(self.x, self.means, 'ko-')[0]
     else:
         adjust_spines(axes,spines=['left','bottom','right'],spine_outward=['left','right','bottom'],xoutward=10,youtward=30,\
                       xticks='bottom',yticks='both',tick_label=['x','y'],xaxis_loc=5,xminor_auto_loc=2,yminor_auto_loc=2)
         axes.set_ylabel('Response(spikes/sec)',fontsize=12)
         self.curve_data = axes.plot(self.x, self.means, self.data_point_styles[0])[0]
     self.errbars = axes.errorbar(self.x, self.means, yerr=self.stds, fmt='k.') if self.showing_errbar else None
     self.curve_axes = axes
     
     self.fitting_data = axes.plot(self.fitting_x, self.fitting_y, self.fitting_curve_styles[0])[0]
     
     axes.set_ylim(0,100)
     axes.relim()
     axes.autoscale_view(scalex=True, scaley=False)
     axes.grid(b=True, which='major',axis='both',linestyle='-.')
     # make histgrams plot
     rows,cols = (grid-height,grid)
     for row in range(rows,cols)[::height]:
         for col in range(cols)[::height]:
             axes = self.fig.add_subplot(gs[row:row+height,col:col+height])
             axes.set_axis_bgcolor('white')
             #axes.set_title('PSTH', size=8)
             axes.set_ylim(0,100)
             if col == 0:
                 adjust_spines(axes,spines=['left','bottom'],xticks='bottom',yticks='left',tick_label=['y'],xaxis_loc=4,yaxis_loc=3)
                 axes.set_ylabel('Spikes',fontsize=11)
             elif col == cols-height:
                 adjust_spines(axes,spines=['right','bottom'],xticks='bottom',yticks='right',tick_label=['y'],xaxis_loc=4,yaxis_loc=3)
             else:
                 adjust_spines(axes,spines=['bottom'],xticks='bottom',yticks='none',tick_label=[],xaxis_loc=4,yaxis_loc=3)
             pylab.setp(axes.get_xticklabels(), fontsize=8)
             pylab.setp(axes.get_yticklabels(), fontsize=8)
             _n, bins, patches = axes.hist(data, bins, facecolor='black', alpha=1.0)
             self.hist_bins.append(bins)
             self.hist_patches.append(patches)
             
     self.fig.canvas.draw()
Exemple #47
0
  def plotCorrEnh(self, parsList=None, **plotArgs):
    """
      Produces enhanced correlation plots.
      
      Parameters
      ----------
      parsList : list of string,  optional
          If not given, all available traces are used.
          Otherwise a list of at least two parameters
          has to be specified.
      plotArgs : dict, optional
          Keyword arguments handed to plot procedures of
          pylab. The following keywords are available:
          contour,bins,cmap,origin,interpolation,colors
    """
    if not ic.check["matplotlib"]:
      PE.warn(PE.PyARequiredImport("To use 'plotCorr', matplotlib has to be installed.", \
                                   solution="Install matplotlib."))
      return
    tracesDic = {}
    if parsList is not None:
      for parm in parsList:
        self._parmCheck(parm)
        tracesDic[parm] = self[parm]
      if len(tracesDic) < 2:
        raise(PE.PyAValError("For plotting correlations, at least two valid parameters are needed.", \
                             where="TraceAnalysis::plotCorr"))
    else:
      # Use all available traces
      for parm in self.availableParameters():
        tracesDic[parm] = self[parm]

    pars = tracesDic.keys()
    traces = tracesDic.values()

    fontmap = {1:10, 2:9, 3:8, 4:8, 5:8}
    if not len(tracesDic)-1 in fontmap:
      fontmap[len(tracesDic)-1] = 8

    k = 1
    for j in range(len(tracesDic)):
      for i in range(len(tracesDic)):
        if i>j:
          plt.subplot(len(tracesDic)-1,len(tracesDic)-1,k)
#          plt.title("Pearson's R: %1.5f" % self.pearsonr(pars[j],pars[i])[0], fontsize='x-small')
          plt.xlabel(pars[j], fontsize=fontmap[len(tracesDic)-1])
          plt.ylabel(pars[i], fontsize=fontmap[len(tracesDic)-1])
          tlabels = plt.gca().get_xticklabels()
          plt.setp(tlabels, 'fontsize', fontmap[len(tracesDic)-1])
          tlabels = plt.gca().get_yticklabels()
          plt.setp(tlabels, 'fontsize', fontmap[len(tracesDic)-1])
#          plt.plot(traces[j],traces[i],'.',**plotArgs)
          self.__hist2d(traces[j],traces[i],**plotArgs)
        if i!=j:
          k+=1
Exemple #48
0
 def modifValZone(self, nameVar, ind, val):
     """modifier dans la zone nameVar la valeur
     ou liste valeur, attention le texte de la zone contient nom et valeur"""
     obj = self.listeZoneText[nameVar][ind].getObject()
     if type(obj) == type([2, 3]):
         for i in range(len(obj)):
             pl.setp(obj[i], text=str(val[i]))
     else:
         nom = pl.getp(obj, "text").split("\n")[0]
         pl.setp(obj, text=nom + "\n" + str(val)[:16])
     self.redraw()
def test_geometric_mechanism(alpha, n_bins=10):  
    X = geometric_mechanism(alpha, 10000) 
    # plot geometric distribution
    n, bins, patches = P.hist(X, 2*n_bins, range=(-n_bins,n_bins), normed=1, histtype='stepfilled')   # bins: ndarray of 51 elements
    P.setp(patches, 'facecolor', 'g', 'alpha', 0.75)
    print bins
    # add a line showing the expected distribution
    x = np.array(range(-n_bins, n_bins+1))          # x: -n_bins -> n_bins
    y = np.power(alpha, abs(x))*(1-alpha)/(1+alpha)    # y = (1-alpha)/(1+alpha)*alpha^|x|
    l = P.plot(x, y, 'k--', linewidth=1.5)

    P.show()
Exemple #50
0
def scatter(x,y):
    from matplotlib.pylab import figure,show, setp
    fig=figure()
    ax1 = fig.add_subplot(1,1,1)
    xmax=np.max(x)+0.5
    markerline, stemline, baseline = ax1.stem(x,y,'-.')
    setp(markerline, 'markerfacecolor', 'b')
    setp(baseline, 'color', 'r', 'linewidth', 2)
    ax1.set_xlabel('Evento')
    ax1.set_ylabel('Residuo (s)')
    ax1.set_xlim([0.5,xmax])
    show()
Exemple #51
0
def plot_model(galaxy, sect = [x1, x2, y1, y2], directory = '/Volumes/VINCE/dwarfs/combined_VCC/figures/'):
    '''
    A wrapper to plot galfit results, bad pixel mask and other info
    
    INPUT
    'galaxy': Single row of the dataframe produced by the procedure the for loop
              below
    'sect'  : Image sector produced by sector(header). It is the same for all 
              galaxies. Do not need to call sector(header) every time.
    'directory': Where to save the results. Directory needs to be created
    '''
    plt.ioff()
    fig, axarr = plt.subplots(2,3)
    #fig.suptitle('{}'.format(f))

    hdu = fits.open(galaxy['MODEL'])
    image = ndimage.gaussian_filter(hdu[1].data, 1)
    axarr[0, 0].imshow(image, cmap='gray', norm=LogNorm(), vmin=1, vmax = 50)
    axarr[0, 0].set_title('Image')

    model = hdu[2].data
    axarr[0, 1].imshow(model, cmap='Blues', norm=LogNorm(), vmin=0.01, vmax = 6)
    axarr[0, 1].set_title('Model')

    residuals = ndimage.gaussian_filter(hdu[3].data, 1)
    axarr[1, 0].imshow(residuals, cmap='gray', norm=LogNorm(), vmin=1, vmax = 50)
    axarr[1, 0].set_title('Residuals')

    x1, x2, y1, y2 = sect[0], sect[1], sect[2], sect[3]
    themask = themask = getdata(galaxy['MASK'])[x1:x2,y1:y2]
    axarr[1, 1].imshow(themask, cmap='gray', vmin=0, vmax = 1)
    axarr[1, 1].set_title('Mask')
    
    axarr[0, 2].text(0.2, 1.0,r'Galaxy: VCC{}'.format(galaxy['ID']), va="center", ha="left")
    axarr[0, 2].text(0.2, 0.9,r'mtot $=$ {}'.format(galaxy['mtot']), va="center", ha="left")
    axarr[0, 2].text(0.2, 0.8,r'Re $=$ {} pc'.format(galaxy['Re']), va="center", ha="left")
    axarr[0, 2].text(0.2, 0.7,r'n $=$ {}'.format(galaxy['n']), va="center", ha="left")
    axarr[0, 2].text(0.2, 0.6,r'PA $=$ {}'.format(galaxy['PA']), va="center", ha="left")
    axarr[0, 2].text(0.2, 0.5,r'chi2nu $=$ {}'.format(galaxy['chi2nu']), va="center", ha="left")
    
    axarr[0, 2].set_aspect('equal')
    axarr[0, 2].axis('off')

    axarr[1, 2].set_aspect('equal')
    axarr[1, 2].axis('off')

    fig.subplots_adjust(hspace=0., wspace = 0.)
    plt.setp([a.get_xticklabels() for a in axarr.flatten()], visible=False);
    plt.setp([a.get_yticklabels() for a in axarr.flatten()], visible=False);

    fig.savefig(directory + '{}.png'.format(f.split('/')[-1]), dpi= 200)
    plt.close(fig)
def violin_plot(ax, values_list, measure_name, group_names, fontsize, color='blue',  ttest=False):
    '''
    This is a little wrapper around the statsmodels violinplot code
    so that it looks nice :)    
    '''    
    
    # IMPORTS
    import matplotlib.pylab as plt
    import statsmodels.api as sm
    import numpy as np
    
    # Make your violin plot from the values_list
    # Don't show the box plot because it looks a mess to be honest
    # we're going to overlay a boxplot on top afterwards
    plt.sca(ax)
    
    # Adjust the font size
    font = { 'size'   : fontsize}
    plt.rc('font', **font)

    max_value = np.max(np.concatenate(values_list))
    min_value = np.min(np.concatenate(values_list))
    
    vp = sm.graphics.violinplot(values_list,
                            ax = ax,
                            labels = group_names,
                            show_boxplot=False,
                            plot_opts = { 'violin_fc':color ,
                                          'cutoff': True,
                                          'cutoff_val': max_value,
                                          'cutoff_type': 'abs'})
    
    # Now plot the boxplot on top
    bp = plt.boxplot(values_list, sym='x')
    
    for key in bp.keys():
        plt.setp(bp[key], color='black', lw=fontsize/10)
        
    # Adjust the power limits so that you use scientific notation on the y axis
    plt.ticklabel_format(style='sci', axis='y')
    ax.yaxis.major.formatter.set_powerlimits((-3,3))
    plt.tick_params(axis='both', which='major', labelsize=fontsize)

    # Add the y label
    plt.ylabel(measure_name, fontsize=fontsize)
    
    # And now turn off the major ticks on the y-axis
    for t in ax.yaxis.get_major_ticks(): 
        t.tick1On = False 
        t.tick2On = False

    return ax
def PlotCheckMuseBias(filename):
    '''
    
    '''
    #fig = plt.figure()
    #fig.subplots_adjust(wspace=0.3, hspace=0.01)


    datos=open(filename,'r').read().splitlines()
    datos=[x.split() for x in datos]
    for ifu in range(1,25):
        f,axarr = plt.subplots(2,2)
        #read RON for Q1, Q2, Q3 and Q4
        q1ron=[float(x[Q1]) for x in datos[1:] if x[CH]=='CHAN%02d'%ifu]
        q2ron=[float(x[Q2]) for x in datos[1:] if x[CH]=='CHAN%02d'%ifu]
        q3ron=[float(x[Q3]) for x in datos[1:] if x[CH]=='CHAN%02d'%ifu]
        q4ron=[float(x[Q4]) for x in datos[1:] if x[CH]=='CHAN%02d'%ifu]

        #TODO: Add red line at 3 e of RON
        #TODO: use dots i the graphs
        #TODO: save files with CHANXX.jpg

        axarr[1,0].set_ylim([1.5,5]) 
        axarr[1,0].set_xlim([0,120])
        axarr[1,0].set_ylabel('RON [e]')
        axarr[1,0].plot(q1ron)
        axarr[1,0].hlines(3.0,0,120,color="red")
        axarr[1,0].grid()      
        axarr[1,0].set_title('CHAN%02d Q1'%ifu)
        axarr[1,1].set_ylim([1.5,5])
        axarr[1,1].set_xlim([0,120])
        axarr[1,1].plot(q2ron)
        axarr[1,1].hlines(3.0,0,120,color="red")
        axarr[1,1].grid()  
        axarr[1,1].set_title('CHAN%02d Q2'%ifu)
        axarr[0,1].set_ylim([1.5,5])
        axarr[0,1].set_xlim([0,120])
        axarr[0,1].plot(q3ron)
        axarr[0,1].hlines(3.0,0,120,color="red")
        axarr[0,1].grid()  
        axarr[0,1].set_title('CHAN%02d Q3'%ifu)
        axarr[0,0].set_ylim([1.5,5])
        axarr[0,0].set_xlim([0,120])
        axarr[0,0].set_ylabel('RON [e]')
        axarr[0,0].plot(q4ron)
        axarr[0,0].hlines(3.0,0,120,color="red")
        axarr[0,0].grid()  
        axarr[0,0].set_title('CHAN%02d Q4'%ifu)
        #hide x ticks for top plots
        plt.setp([a.get_xticklabels() for a in axarr[0,:]], visible=False)
        plt.savefig('CHAN%02d_RON.jpg'%ifu)
        plt.close()
Exemple #54
0
def threehists(x1,x2,x3,xmin,xmax,x1leg='$x_1$',x2leg='$x_2$',x3leg='$x_3$',xlabel='',fig=1,sharey=False,fontsize=12):
	"""
Script that plots three histograms of quantities x1, x2 and x3 
sharing the same X-axis.

Arguments:
- x1,x2,x3: arrays with data to be plotted
- xmin,xmax: lower and upper range of plotted values, will be used to set a consistent x-range for both histograms.
- x1leg, x2leg, x3leg: legends for each histogram	
- xlabel: self-explanatory.
- sharey: sharing the Y-axis among the histograms?
- fig: which plot window should I use?

Example:
x1=Lbol(AD), x2=Lbol(JD), x3=Lbol(EHF10)

>>> threehists(x1,x2,x3,38,44,'AD','JD','EHF10','$\log L_{\\rm bol}$ (erg s$^{-1}$)',sharey=True)

Inspired by `Scipy <http://www.scipy.org/Cookbook/Matplotlib/Multiple_Subplots_with_One_Axis_Label>`_.
	"""
	pylab.rcParams.update({'font.size': fontsize})
	fig=pylab.figure(fig)
	pylab.clf()
	
	a=fig.add_subplot(3,1,1)
	if sharey==True:
		b=fig.add_subplot(3,1,2, sharex=a, sharey=a)
		c=fig.add_subplot(3,1,3, sharex=a, sharey=a)
	else:
		b=fig.add_subplot(3,1,2, sharex=a)
		c=fig.add_subplot(3,1,3, sharex=a)		
	
	a.hist(x1,label=x1leg,color='b',histtype='stepfilled')
	a.legend(loc='best',frameon=False)
	a.set_xlim(xmin,xmax)
	
	b.hist(x2,label=x2leg,color='r',histtype='stepfilled')
	b.legend(loc='best',frameon=False)

	c.hist(x3,label=x3leg,color='y',histtype='stepfilled')
	c.legend(loc='best',frameon=False)
	
	pylab.setp(a.get_xticklabels(), visible=False)
	pylab.setp(b.get_xticklabels(), visible=False)

	c.set_xlabel(xlabel)
	b.set_ylabel('Number')
	pylab.minorticks_on()
	pylab.subplots_adjust(hspace=0.15)
	pylab.draw()
	pylab.show()
def plot_method_pairs_and_matrix(case_studies,fileappend=''):
    case_cov=np.cov(case_studies.transpose())
    case_corr=np.corrcoef(case_studies.transpose())
    cmatrix= case_corr
    fig = plt.figure(figsize=(twocol,twocol),dpi=figdpi,tight_layout=True)
    ax = fig.add_subplot(111)
    ppl.pcolormesh(fig,ax,cmatrix[inds][:,inds],#-np.diag([.99]*len(meths)),
                   yticklabels=np.array(mindex)[inds].tolist(),
                   xticklabels=np.array(mindex)[inds].tolist(),
                   cmap=ppl.mpl.cm.RdBu,vmax=0.4,vmin= -0.4)
    ax.tick_params(axis='both', which='major', labelsize=8)
    plt.setp(ax.get_xticklabels(), rotation='vertical')
    cm=dark2
    [l.set_color(cm[m_codes[mindex.index(l.get_text())]]) for i,l in enumerate(ax.get_yticklabels())]
    [l.set_color(cm[m_codes[mindex.index(l.get_text())]]) for i,l in enumerate(ax.get_xticklabels())]
    fig.show()
    fig.savefig(figure_path+('method_matrix%s.pdf'%fileappend))
    
    #Show the highly correlated methods
    pq=PQ()
    pq_cross=PQ()
    for i in range(len(meths)):
        for j in range(i+1,len(meths)):
            m1text='(%s) %s'%(meths[i,1],meths[i,0])
            m2text='(%s) %s'%(meths[j,1],meths[j,0])
            pq.put((-cmatrix[i,j],(m1text,m2text)))
            if meths[i,1]!= meths[j,1]:
                pq_cross.put((-cmatrix[i,j],(m1text,m2text)))
    
    # Output the method correlations
    # Sets how many highly correlated methods should be displayed
    print_cap = 20
    moutfile = open(results_path+('method_corrs%s.csv'%fileappend),'w')
    print 'All methods:'
    for i in range(pq.qsize()):
        v,(m1,m2)=pq.get()
        if i < print_cap:
            print '%.2f & %s & %s\\\\'%(-v,m1,m2)
        moutfile.write('%.9f | %s | %s\n'%(-v,m1,m2))
    moutfile.close()
    
    moutfile = open(results_path+('method_corrs_cross%s.csv'%fileappend),'w')
    print 'Just cross methods:'
    for i in range(pq_cross.qsize()):
        v,(m1,m2)=pq_cross.get()
        if i < print_cap:
            print '%.2f & %s & %s\\\\'%(-v,m1,m2)
        moutfile.write('%.9f | %s | %s\n'%(-v,m1,m2))
    moutfile.close()
def drawPieChart(data, labels, title):
    fig = plt.figure(dpi=100, figsize=(8,8))
    # first axes
    ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])
    patches, texts, autotexts = ax1.pie(data, labels=labels, autopct='%1.1f%%', colors=['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'])
    plt.setp(autotexts, fontproperties=myFont, size=tipSize)
    plt.setp(texts, fontproperties=myFont, size=tipSize)
    ax1.set_title(title,fontproperties=myFont, size=titleSize)
    ax1.set_aspect(1)
    #plt.show()
    plt.savefig(sv_file_dir+'/'+title+'.png', format='png')
    plt.cla()
    plt.clf()
    plt.close()
    print 'drawPieChart',title,'over'
Exemple #57
0
 def drawMain(self):
          #--------- Load image with current index --------- 
     self.imageData = mpimg.imread(os.path.join(self.imageFolder.get(),self.imageNames[self.currentIndex.get()]))
          #--------- Delete old image and plot new ---------             
     plt.figure('Main')
     self.ax['Main'].cla()
     self.rect = []
     self.flowRegion = []
     self.mainImage = plt.imshow(self.imageData,cmap=cMaps[self.colorMap.get()])
     self.ax['Main'].set_aspect('equal', 'datalim')
     plt.setp(self.ax['Main'].get_xticklabels(), visible=False)
     plt.setp(self.ax['Main'].get_yticklabels(), visible=False)
     self.canvas['Main'].draw()
     self.ax['Main'].autoscale(False)
     return
def test_geom_distr(alpha):
    # GEOMETRIC DISTR
    X = np.random.geometric(alpha, 10000)
    
    # plot geometric distribution
    n_bins = 10
    n, bins, patches = P.hist(X, n_bins, range=(1,n_bins+1), normed=1, histtype='stepfilled')   # bins: ndarray of 51 elements
    P.setp(patches, 'facecolor', 'g', 'alpha', 0.75)
    print bins
    # add a line showing the expected distribution
    x = np.array(range(1, n_bins+1))    # x: 1 -> n_bins
    y = np.power(1-alpha, x-1)*alpha    # y = (1-alpha)^(x-1)*alpha
    l = P.plot(bins[0:n_bins], y, 'k--', linewidth=1.5)

    P.show()
Exemple #59
0
    def hide(self, objs='xticklabels', ax=None):
        """
        Hide `objs` on all axes of this group * except* for those
        specified in `ax`.

        Parameters
        ----------
        objs :
            str {'xticklabels', 'yticklabels', 'minorxticks', 'minoryticks'}
          or a list of these.
        ax   :
            axes, optional (default: hide all)
               The axes(or list of axes) on which these items should
               not be hidden.

        Examples
        --------
        Hide the xticklabels on all axes except ax0:
            :
            hide('xticklabels', self.ax0)

        To hide all xticklabels, simply do:
           hide('xticklabels')

        See also
        --------
        antiset

        """
        if objs.__class__ is str:
            objs = [objs]
        types = {'x': ['xticklabels', 'minorxticks'],
                 'y': ['yticklabels', 'minoryticks']}
        for obj in objs:
            if ax.__class__ is str and ax == 'all':
                axs = self.flat
            else:
                if ax is None:
                    if obj in types['x'] and hasattr(self, '_xlabel_ax'):
                        ax = self._xlabel_ax
                    elif obj in types['y'] and hasattr(self, '_ylabel_ax'):
                        ax = self._ylabel_ax
                    else:  # This gives default behavior?
                        ax = []
                if not hasattr(ax, '__len__'):
                    ax = [ax]
                axs = list(self.to_set() - set(ax))
            for axn in axs:
                if obj == 'xticklabels':
                    pylab.setp(axn.get_xticklabels(), visible=False)
                elif obj == 'yticklabels':
                    pylab.setp(axn.get_yticklabels(), visible=False)
                elif obj == 'minorxticks':
                    pylab.setp(axn.xaxis.get_minorticklines(), visible=False)
                elif obj == 'minoryticks':
                    pylab.setp(axn.yaxis.get_minorticklines(), visible=False)
                else:
                    error