Python matplotlib.pyplot.suptitle() Examples

The following are code examples for showing how to use matplotlib.pyplot.suptitle(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: Attention-Gated-Networks   Author: ozan-oktay   File: visualise_attention.py    MIT License 6 votes vote down vote up
def plotNNFilter(units, figure_id, interp='bilinear', colormap=cm.jet, colormap_lim=None, title=''):
    plt.ion()
    filters = units.shape[2]
    n_columns = round(math.sqrt(filters))
    n_rows = math.ceil(filters / n_columns) + 1
    fig = plt.figure(figure_id, figsize=(n_rows*3,n_columns*3))
    fig.clf()

    for i in range(filters):
        ax1 = plt.subplot(n_rows, n_columns, i+1)
        plt.imshow(units[:,:,i].T, interpolation=interp, cmap=colormap)
        plt.axis('on')
        ax1.set_xticklabels([])
        ax1.set_yticklabels([])
        plt.colorbar()
        if colormap_lim:
            plt.clim(colormap_lim[0],colormap_lim[1])

    plt.subplots_adjust(wspace=0, hspace=0)
    plt.tight_layout()
    plt.suptitle(title) 
Example 2
Project: it-net   Author: wentaoyuan   File: visu_util.py    MIT License 6 votes vote down vote up
def plot_iters(figpath, pcd, transforms, titles, lim, size, suptitle=None, axis_on=False):
    fig = plt.figure(figsize=(len(transforms) * 4, 3 * 4))
    if not isinstance(lim, list):
        lim = [lim] * len(transforms)
    for i in range(3):
        azim = 80 * i - 30
        elev = 15 * (i+1)
        for j in range(len(transforms)):
            ax = fig.add_subplot(3, len(transforms), i*len(transforms)+j+1, projection='3d')
            pcd_trans = np.dot(np.concatenate([pcd, np.ones((pcd.shape[0], 1))], axis=1), transforms[j].T)
            plot_pcd(ax, pcd_trans, size, azim, elev, lim[j])
            if axis_on:
                for axis in 'xyz':
                    getattr(ax, 'set_{}ticks'.format(axis))([-lim[j], 0, lim[j]])
                ax.tick_params(labelsize='large')
            else:
                ax.set_axis_off()
            if i == 0:
                ax.set_title(titles[j], fontsize=20)
    if suptitle is not None:
        plt.suptitle(suptitle)
    plt.subplots_adjust(left=0, right=1, bottom=0, top=0.9, wspace=0, hspace=0)
    fig.savefig(figpath)
    plt.close(fig) 
Example 3
Project: it-net   Author: wentaoyuan   File: visu_util.py    MIT License 6 votes vote down vote up
def plot_iters_seg(figpath, pcd, transforms, part_ids, titles, lim, size, suptitle=None, axis_on=False):
    fig = plt.figure(figsize=(len(transforms) * 4, 3 * 4))
    if not isinstance(lim, list):
        lim = [lim] * len(transforms)
    for i in range(3):
        azim = 80 * i - 30
        elev = 15 * (i+1)
        for j in range(len(transforms)):
            ax = fig.add_subplot(3, len(transforms), i*len(transforms)+j+1, projection='3d')
            pcd_trans = np.dot(np.concatenate([pcd, np.ones((pcd.shape[0], 1))], axis=1), transforms[j].T)
            plot_pcd(ax, pcd_trans, size, azim, elev, lim[j], part_colormap[part_ids[j]])
            if axis_on:
                for axis in 'xyz':
                    getattr(ax, 'set_{}ticks'.format(axis))([-lim[j], 0, lim[j]])
                ax.tick_params(labelsize='large')
            else:
                ax.set_axis_off()
            if i == 0:
                ax.set_title(titles[j], fontsize=20)
    if suptitle is not None:
        plt.suptitle(suptitle)
    plt.subplots_adjust(left=0, right=1, bottom=0, top=0.95, wspace=0, hspace=0)
    fig.savefig(figpath)
    plt.close(fig) 
Example 4
Project: POET   Author: kevin218   File: poet_denoise.py    GNU General Public License v3.0 6 votes vote down vote up
def plotlc(event, pos=0, length=200, denoised=True):
    # Obtain frames at pixel srcest
    ipix0, ipix1  = int(event.srcest[0,pos]),int(event.srcest[1,pos])
    frames = (event.data[:,ipix0,ipix1,pos])[np.where(event.mask[:,ipix0,ipix1,pos])]
    plt.figure(302 + 10*pos)
    if denoised == False:
        plt.clf()
        #label  = "None"
        plt.plot(frames[:length], 'bo', label="None")
    else:
        #label  = "L"+str(event.numlvls)
        plt.plot(frames[:length], 'sg-', ms=4, lw=2, label="L"+str(event.numlvls))
        plt.suptitle(event.denoisedir + ' Lightcurve at Pixel ' + str(ipix0) +','+ str(ipix1))
        plt.xlabel('Frame Number')
        plt.ylabel('Flux ($\mu$Jy)')
        plt.legend(loc='best')
        plt.savefig("fig" + str(302+10*pos) + ".png")

    return 
Example 5
Project: POET   Author: kevin218   File: plots.py    GNU General Public License v3.0 6 votes vote down vote up
def rmsplot(event, fit, fignum, savefile=None, istitle=True, stderr=None, normfactor=None):
    if stderr == None:
        stderr = fit.stderr
    if normfactor == None:
        normfactor = 1e-6
    plt.rcParams.update({'legend.fontsize':11})
    plt.figure(fignum, figsize=(8,6))
    plt.clf()
    if istitle:
        a = plt.suptitle(event.eventname + ' Correlated Noise', size=16)
    plt.loglog(fit.binsz, fit.rms/normfactor, color='black', lw=1.5, label='Fit RMS', zorder=3)    # our noise
    plt.loglog(fit.binsz, stderr/normfactor, color='red', ls='-', lw=2, label='Std. Err.', zorder=1) # expected noise
    plt.xlim(0, fit.binsz[-1]*2)
    plt.ylim(stderr[-1]/normfactor/2., stderr[0]/normfactor*2.)
    plt.xlabel("Bin Size", fontsize=14)
    plt.ylabel("RMS (ppm)", fontsize=14)
    plt.xticks(size=12)
    plt.yticks(size=12)
    plt.legend()
    if savefile != None:
        plt.savefig(savefile)
    return

# Plot RMS vs. bin size (with RMS uncertainties) looking for time-correlated noise 
Example 6
Project: POET   Author: kevin218   File: plots.py    GNU General Public License v3.0 6 votes vote down vote up
def rmsploterr(event, fit, fignum, savefile=None, istitle=True, stderr=None, normfactor=None):
    if stderr == None:
        stderr = fit.stderr
    if normfactor == None:
        normfactor = stderr[0]
    plt.rcParams.update({'legend.fontsize':11})
    plt.figure(fignum, figsize=(8,6))
    plt.clf()
    if istitle:
        a = plt.suptitle(event.eventname + ' Correlated Noise', size=16)
    plt.loglog(fit.binsz, fit.rms/normfactor, color='black', lw=1.5, label='Fit RMS')    # our noise
    plt.loglog(fit.binsz, stderr/normfactor, color='red', ls='-', lw=2, label='Std. Err.') # expected noise
    plt.xlim(0, fit.binsz[-1]*2)
    plt.ylim(stderr[-1]/normfactor/2., stderr[0]/normfactor*2.)
    plt.xlabel("Bin Size", fontsize=14)
    plt.ylabel("Normalized RMS", fontsize=14)
    plt.xticks(size=12)
    plt.yticks(size=12)
    plt.legend()
    if savefile != None:
        plt.savefig(savefile)
    return 
Example 7
Project: QFiPy   Author: kouzapo   File: equities.py    MIT License 6 votes vote down vote up
def plot_price(self):
		closeDF, dates = self.get_prices(return_dates = True)
		rolling_mean = pd.DataFrame(closeDF).rolling(window = 60, min_periods = 0).mean()
		dates = pd.to_datetime(dates)
		volume = self.get_volume()

		fig, (ax1, ax2) = plt.subplots(2, sharex = True, gridspec_kw = {'height_ratios': [4, 1]})
		fig.autofmt_xdate()

		ax1.plot(dates, closeDF, color = 'blue', linewidth = 1.8, label = "Price")
		ax1.plot(dates, rolling_mean, color = 'red', linewidth = 1.0, label = "Rolling Mean")

		ax2.bar(dates, volume, width = 2, color = 'blue', label = "Volume")

		plt.suptitle(str(self.quote) + " value movement and Volume", fontsize = 20)
		ax1.set_ylabel("Price", fontsize = 12)
		ax2.set_ylabel("Volume", fontsize = 12)
		ax1.legend(loc = 2)
		xfmt = mdates.DateFormatter('%Y-%m-%d')
		ax1.xaxis.set_major_formatter(xfmt)

		plt.show() 
Example 8
Project: pypopgen   Author: feilchenfeldt   File: genomeplot.py    MIT License 6 votes vote down vote up
def plot_along_chrom(df,chrom,quantile,window_size):
    chr_len = chrom_length.ix[chrom]
    n_subplot = len(pops)
    #print round(window_size/1000)
    fig = plt.figure(1, figsize=(15./(1-log(10000./window_size))\
                           *chr_len/chrom_length.ix["CAE1"],1.5*n_subplot))
    plt.suptitle("Akey's d, "+str(int(window_size/1000))+"kb windows",fontsize="15") 
    hspace = 0.3
    fig.subplots_adjust(hspace=hspace)
    for i,pop in enumerate(pops):
        qt = quantile[pop]
        ax = fig.add_subplot(n_subplot,1,i+1)
        ax.set_frame_on(False)
        ax.set_yticks([0,round(qt)])
        if i < len(pops)-1:
            ax.set_xticks([])
            ax.get_xaxis().set_visible(False)
        else:
            ax.set_xlabel(chrom)
        #total_3window_d[idx][pop].plot(style=".",markersize=5,color=colors[i],ax=ax)
        ax.plot(window_d.ix[chrom][pop].index,window_d.ix[chrom][pop].values,".",markersize=5,color=colors[i])
        ax.set_title(pop,position=(0.5,0.95))
        ax.set_xlim([0,chr_len+1000])
    return fig 
Example 9
Project: rattlesnake   Author: loehnertz   File: rattlesnake.py    MIT License 6 votes vote down vote up
def plot_results(data, nth_iteration):
    """
    Plots the list it receives and cuts off the first ten entries to circumvent the plotting of initial silence

    :param data: A list of data to be plotted
    :param nth_iteration: Used for the label of the x axis
    """

    # Plot the data
    plt.plot(data[10:])

    # Label the axes
    plt.xlabel('Time (every {}th {} byte)'.format(nth_iteration, CHUNK))
    plt.ylabel('Volume level difference (in dB)')

    # Calculate and output the absolute median difference level
    plt.suptitle('Difference - Median (in dB): {}'.format(np.round(np.fabs(np.median(data)), decimals=5)), fontsize=14)

    # Display the plotted graph
    plt.show() 
Example 10
Project: MarkovModels   Author: pmontalb   File: COneFactorModel.py    MIT License 6 votes vote down vote up
def plot_probability_distribution_function(self, initial_point=None, title=""):
        if initial_point is None:
            initial_point = self.x0

        fig = plt.figure()
        n_plots = 1 if self.total_cumulative_stochastic_kernels == {} else 2

        ax1 = fig.add_subplot(1, n_plots, 1)
        if n_plots > 1:
            ax2 = fig.add_subplot(1, n_plots, 2)
        for t in sorted(self.total_stochastic_kernels):
            ax1.plot(self.grid, self.total_stochastic_kernels[t][initial_point, :], label=str(t))
            if n_plots > 1:
                ax2.plot(self.grid, self.total_cumulative_stochastic_kernels[t][initial_point, :],
                         label=str(t))

        ax1.set_title("Probability Distribution Function")
        if n_plots > 1:
            ax2.set_title("Cumulative Distribution Function")

        if n_plots > 1:
            ax2.legend()

        plt.suptitle(title)
        plt.show() 
Example 11
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 6 votes vote down vote up
def HistogramImage(data):
        print 'entered HistogramImage'
        #http://www.saltycrane.com/blog/2011/12/creating-histogram-plot-python/
        x = [int(dbyte[0]) for dbyte in data]

        binsize = 100
        totalrangeofhisto = 20000
        bins = [i * binsize for i in range(totalrangeofhisto/binsize)]

        pyplot.hist(x, bins=bins, facecolor='green', alpha=0.75)
        pyplot.xlabel('dbytes')
        pyplot.ylabel('Count')
        pyplot.suptitle(r'histogram of dbytes')
        pyplot.title(r'distribution for matt->smarsh')
        pyplot.grid(True)
        filename='histo.png'
        try:
                pyplot.savefig(filename)
                print 'saved to %s' %filename
        except:
                print 'unable to save to %s' %filename 
Example 12
Project: kappa   Author: ajkerr0   File: plot.py    MIT License 6 votes vote down vote up
def participation(mol):
    """Plot the participation ratios of each normal mode as a function of their frequencies."""
    
    fig = plt.figure()
    
    from .operation import hessian, evecs
    hess = hessian(mol)
    val, vec = evecs(hess)
    
    num = np.sum((vec**2), axis=0)**2
    den = len(vec)*np.sum(vec**4, axis=0)
    
    plt.scatter(val, num/den)
    
    fig.suptitle("Participation ratios of %s" % mol.name)
    
    plt.show() 
Example 13
Project: matplotlib   Author: DaveL17   File: plugin.py    MIT License 6 votes vote down vote up
def format_title(self, p_dict, k_dict, log, loc, align='center'):
        """
        Plot the figure's title

        -----

        :param p_dict:
        :param k_dict:
        :param log:
        :param loc:
        :param str align:
        :return:
        """
        try:
            plt.suptitle(p_dict['chartTitle'], position=loc, ha=align, **k_dict['k_title_font'])

        except KeyError as sub_error:
            log['Warning'].append(u"Title Error: {0}".format(sub_error))

    # ============================================================================= 
Example 14
Project: MiaSeg   Author: jajenQin   File: Miaimshow.py    GNU General Public License v3.0 6 votes vote down vote up
def discrete_matshow(data, labels_names=[], title=""):
    # get discrete colormap
    cmap = plt.get_cmap('Paired', np.max(data) - np.min(data) + 1)
    # set limits .5 outside true range
    mat = plt.matshow(data,
                      cmap=cmap,
                      vmin=np.min(data) - .5,
                      vmax=np.max(data) + .5)
    # tell the colorbar to tick at integers
    cax = plt.colorbar(mat,
                       ticks=np.arange(np.min(data), np.max(data) + 1))

    # The names to be printed aside the colorbar
    if labels_names:
        cax.ax.set_yticklabels(labels_names)

    if title:
        plt.suptitle(title, fontsize=14, fontweight='bold') 
Example 15
Project: vnpy_crypto   Author: birforce   File: test_mosaicplot.py    MIT License 6 votes vote down vote up
def test_axes_labeling():
    from numpy.random import rand
    key_set = (['male', 'female'], ['old', 'adult', 'young'],
               ['worker', 'unemployed'], ['yes', 'no'])
    # the cartesian product of all the categories is
    # the complete set of categories
    keys = list(product(*key_set))
    data = OrderedDict(zip(keys, rand(len(keys))))
    lab = lambda k: ''.join(s[0] for s in k)
    fig, (ax1, ax2) = pylab.subplots(1, 2, figsize=(16, 8))
    mosaic(data, ax=ax1, labelizer=lab, horizontal=True, label_rotation=45)
    mosaic(data, ax=ax2, labelizer=lab, horizontal=False,
        label_rotation=[0, 45, 90, 0])
    #fig.tight_layout()
    fig.suptitle("correct alignment of the axes labels")
    #pylab.show()
    pylab.close('all') 
Example 16
Project: mfanalysis   Author: neurospin   File: mfspectrum.py    MIT License 6 votes vote down vote up
def plot(self, figlabel=None):
        """
        Plot the multifractal spectrum

        figlabel: figure number or name
        """
        if figlabel is None:
            figlabel = 'Multifractal Spectrum'

        plt.figure(figlabel)
        plt.plot(self.hq, self.Dq, 'ko-')
        plt.grid()
        plt.xlabel('h(q)')
        plt.ylabel('D(q)')
        plt.suptitle(self.name + ' - multifractal spectrum')
        plt.draw() 
Example 17
Project: ReinforcementLearningBookExamples   Author: Shawn-Guo-CN   File: 2GridWorld_Ch3.py    GNU General Public License v3.0 5 votes vote down vote up
def draw_image(title, image):
    fig, ax = plt.subplots()
    ax.set_axis_off()
    tb = Table(ax, bbox=[0,0,1,1])

    nrows, ncols = image.shape
    width, height = 1.0 / ncols, 1.0 / nrows

    # Add cells
    for (i,j), val in np.ndenumerate(image):
        # Index either the first or second item of bkg_colors based on
        # a checker board pattern
        idx = [j % 2, (j + 1) % 2][i % 2]
        color = 'white'

        tb.add_cell(i, j, width, height, text=val,
                    loc='center', facecolor=color)

    # Row Labels...
    for i, label in enumerate(range(len(image))):
        tb.add_cell(i, -1, width, height, text=label+1, loc='right',
                    edgecolor='none', facecolor='none')
    # Column Labels...
    for j, label in enumerate(range(len(image))):
        tb.add_cell(-1, j, width, height/2, text=label+1, loc='center',
                           edgecolor='none', facecolor='none')
    ax.add_table(tb)
    plt.suptitle(title)
    plt.show() 
Example 18
Project: TopoMetricUncertainty   Author: UP-RS-ESP   File: optimize_grid_spacing.py    MIT License 5 votes vote down vote up
def plot_fields(var, xb, yb, title, fname, paperwidth = 10):
    """
    Produces a DIN paper PNG figure with all six fields.

    """
    label = (r'Mean elevation [m]', r'Elevation STD [m]',
             r'Aspect PEU [deg]', r'Slope PEU [deg]',
             r'Aspect truncation error [deg]', r'Slope truncation error [deg]')
    cmaps = (pl.cm.viridis, pl.cm.magma_r,
             pl.cm.Purples, pl.cm.Purples,
             pl.cm.seismic, pl.cm.seismic)

    fg, ax = pl.subplots(3, 2,
        figsize = (paperwidth, paperwidth*np.sqrt(2)))
    pl.suptitle(title)
    j = 0
    for i in range(3):
        for k in range(2):
            v = np.ma.masked_invalid(var[j])
            if 0 > v.min():
                vmin = np.nanpercentile(v, 2)
                vmax = -vmin
            else:
                vmin = v.min()
                vmax = np.nanpercentile(v, 98)
            im = ax[i, k].pcolormesh(xb, yb, v,
                    vmin = vmin,
                    vmax = vmax,
                    cmap = cmaps[j])
            cb = fg.colorbar(im, ax = ax[i, k], shrink = 0.75)
            cb.set_label(label[j])
            ax[i, k].set_aspect('equal')
            j += 1

    fg.tight_layout()
    pl.savefig(fname) 
Example 19
Project: TopoMetricUncertainty   Author: UP-RS-ESP   File: lidar_example.py    MIT License 5 votes vote down vote up
def plot_fields(var, xb, yb, title, fname, paperwidth = 10):
    """
    Produces a DIN paper PNG figure with all six fields.

    """
    label = (r'Mean elevation [m]', r'Elevation STD [m]',
             r'Aspect PEU [deg]', r'Slope PEU [deg]',
             r'Aspect truncation error [deg]', r'Slope truncation error [deg]')
    cmaps = (pl.cm.viridis, pl.cm.magma_r,
             pl.cm.Purples, pl.cm.Purples,
             pl.cm.seismic, pl.cm.seismic)

    fg, ax = pl.subplots(3, 2,
        figsize = (paperwidth, paperwidth*np.sqrt(2)))
    pl.suptitle(title)
    j = 0
    for i in range(3):
        for k in range(2):
            v = np.ma.masked_invalid(var[j])
            if 0 > v.min():
                vmin = np.nanpercentile(v, 2)
                vmax = -vmin
            else:
                vmin = v.min()
                vmax = np.nanpercentile(v, 98)
            im = ax[i, k].pcolormesh(xb, yb, v,
                    vmin = vmin,
                    vmax = vmax,
                    cmap = cmaps[j])
            cb = fg.colorbar(im, ax = ax[i, k], shrink = 0.75)
            cb.set_label(label[j])
            ax[i, k].set_aspect('equal')
            j += 1

    fg.tight_layout()
    pl.savefig(fname) 
Example 20
Project: Aegis   Author: jlillywh   File: table.py    GNU General Public License v3.0 5 votes vote down vote up
def plot(self):
        plt.scatter(self.x, self.y)
        plt.suptitle(self.name)
        plt.xlabel(self.x_name)
        plt.ylabel(self.y_name)
        plt.show() 
Example 21
Project: python-wavelet-transform   Author: bearicc   File: mycwt.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def cwt(x, scales, wname, bplot=False):
    coefs = sp.zeros((len(scales), len(x)))
    for i in range(0, len(scales)):
        if wname == 'bior2.6':
            length = min(13*scales[i], len(x))
            wavelet = bior2_6
        coefs[i-1, :] = convolve(x, wavelet(length, i), mode='same')
    
    if bplot:
        import matplotlib.pyplot as plt
        import matplotlib.gridspec as gridspec
        plt.ion()
        fig = plt.figure(num=None, figsize=(14,5), dpi=100, facecolor='w', edgecolor='k')
        plt.clf()
        gs = gridspec.GridSpec(3, 1)
        ax1 = fig.add_subplot(gs[0,0])
        ax1.plot(x,'b-')
    
        ax2 = fig.add_subplot(gs[1:,0])
        im = ax2.imshow(coefs[::-1,:], extent=[0, len(x), scales[0], scales[-1]], aspect='auto', cmap='jet')
        ax2.invert_yaxis()
        ax2.set_xlabel('t')
        ax2.set_ylabel('scale')
        l, b, w, h = ax2.get_position().bounds
        cax = fig.add_axes([l+w+0.01, b, 0.02, h])
        plt.colorbar(im, cax=cax)
        plt.suptitle('cwt by python')
        plt.draw()
        plt.show(block=True)
            
    return coefs 
Example 22
Project: VRPTW-ga   Author: shayan-ys   File: report.py    MIT License 5 votes vote down vote up
def plot_draw(self, x_axis: list, y_axis: list, latest_result):
        y_axis_parsed = []
        for y in y_axis:
            try:
                y_axis_parsed.append(y['best'])
            except:
                break
        if y_axis_parsed:
            y_axis = y_axis_parsed

        plt.figure(1)
        # self.subplot.set_xlim([self.plot_x_axis[0], self.plot_x_axis[-1]])
        self.subplot.set_ylim([min(y_axis) - 5, max(y_axis) + 5])
        plt.suptitle('Best solution so far: ' + re.sub("(.{64})", "\\1\n", str(latest_result), 0, re.DOTALL),
                     fontsize=10)
        print(latest_result)
        self.subplot.plot(x_axis, y_axis)

        plt.figure(2)
        for route_x, route_y in latest_result.plot_get_route_cords():
            plt.plot(route_x, route_y)

        plt.draw()
        self.fig.savefig("plot-output.png")
        self.fig_node_connector.savefig("plot2-output.png")
        plt.pause(0.000001) 
Example 23
Project: tmatplot   Author: taehoonlee   File: basics.py    MIT License 5 votes vote down vote up
def multiBar(data, xlabel=None, ylabel=None,
             title=None, suptitle=None,
             colors='C0', alphas=None, edgecolors=None,
             savefile=None, close=True,
             grid=(1, None), figsize=(8, 2),
             sharey=False, singleconf=False, tight=True):
    grid, axarr, _ = subplots(len(data), grid, figsize, sharey=sharey)

    if suptitle is not None:
        plt.suptitle(suptitle)

    for (i, d) in enumerate(data):
        ax = axarr[i // grid[1], i % grid[1]]
        kwargs = makeKwargs(idx=i,
                            colors=colors,
                            alphas=alphas,
                            edgecolors=edgecolors,
                            singleconf=singleconf)
        ax.bar(range(len(d)), d, **kwargs)

        if isinstance(xlabel, list):
            ax.set_xlabel(xlabel[i])
        elif (xlabel is not None) and (i == 0):
            ax.set_xticks(range(len(xlabel)))
            ax.set_xticklabels(xlabel, rotation='45')

        if isinstance(ylabel, list):
            ax.set_xlabel(ylabel[i])
        elif (ylabel is not None) and (i == 0):
            ax.set_ylabel(ylabel)

        if isinstance(title, list):
            ax.set_title(title[i])
        elif title is not None:
            ax.set_title(title)

    if tight is True:
        plt.tight_layout() 
Example 24
Project: vo_single_camera_sos   Author: ubuntuslave   File: common_plot.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_catadioptric_spatial_resolution_vs_k(omnistereo_model, fig_size = None, legend_location = None):
    # Plot Camera Resolution
    k_values = [4, 15, 30]
    r_max = 40
    eta_max = 1.6
    mirror1 = omnistereo_model.top_model
    mirror2 = omnistereo_model.bot_model
    in_square_pixels = False
    in_steradians = True
    use_spatial_resolution = True

    # Plot
    font = {'family' : 'serif',
            'color'  : 'darkblue',
            'weight' : 'normal',
            'size'   : 16,
            }
    fig, ax = plt.subplots(nrows = 1, ncols = 2, figsize = fig_size)
    title = r'Effect of $k_{i}$ on Resolution $\eta_{i}$ for the Common vFOV, $\alpha_{SROI}$'
    fig.canvas.set_window_title(title)
    plt.suptitle(title, fontdict = font)
#         fig.tight_layout()
    if isinstance(ax, np.ndarray):
        if ax.ndim == 1:
            ax = ax.reshape(1, 2)
    else:
        ax = np.array([[ax]])

    plot_mirror_profiles(omnistereo_model, k_values, ax[0, 0], font, is_standalone_plot = False, fig_size = None)
    ax_eta, lines = plot_spatial_resolution_vs_k(mirror1, omnistereo_model.common_lowest_elevation_angle, omnistereo_model.common_highest_elevation_angle, k_values, in_square_pixels, in_steradians, use_spatial_resolution, ax[0, 1], font)
    ax_eta, lines = plot_spatial_resolution_vs_k(mirror2, omnistereo_model.common_lowest_elevation_angle, omnistereo_model.common_highest_elevation_angle, k_values, in_square_pixels, in_steradians, use_spatial_resolution, ax_eta, font)
    # Set blue as the text color for the optimal value in the legend (the first line)
    leg = ax_eta.legend(loc = legend_location)
    texts_in_legend = leg.get_texts()
    # this part can be turned into a loop depends on the number of text objects
    texts_in_legend[0].set_color('b')
    leg.draggable()

    plt.show() 
Example 25
Project: LearningX   Author: ankonzoid   File: run_tests.py    MIT License 5 votes vote down vote up
def plot_model_tree_fit(model, X, y):
        output_filename = os.path.join("output", "test_{}_fit.png".format(model.__class__.__name__))
        print("Saving model tree predictions plot y vs x to '{}'...".format(output_filename))

        plt.figure(figsize=(20, 10))
        figure_str = "23"
        for depth in range(6):
            # Form model tree
            print(" -> training model tree depth={}...".format(depth))
            model_tree = ModelTree(model, max_depth=depth, min_samples_leaf=10,
                                   search_type="greedy", n_search_grid=100)

            # Train model tree
            model_tree.fit(X, y, verbose=False)
            y_pred = model_tree.predict(X)

            # Plot predictions
            plt.subplot(int(figure_str + str(depth + 1)))
            plt.plot(X[:, 0], y, '.', markersize=5, color='k')
            plt.plot(X[:, 0], y_pred, '.', markersize=5, color='r')
            plt.legend(['data', 'fit'])
            plt.title("depth = {}".format(depth))
            plt.xlabel("x", fontsize=15)
            plt.ylabel("y", fontsize=15)
            plt.grid()

        plt.suptitle('Model tree (model = {}) fits for different depths'.format(model.__class__.__name__), fontsize=25)
        plt.savefig(output_filename, bbox_inches='tight')
        plt.close() 
Example 26
Project: POET   Author: kevin218   File: plots.py    GNU General Public License v3.0 5 votes vote down vote up
def binlc(event, fit, fignum, savefile=None, istitle=True, j=0):
    plt.rcParams.update({'legend.fontsize':13})
    plt.figure(fignum)
    plt.clf()
    if istitle == True:
        plt.suptitle(event.eventname + ' Binned Data With Best Fit',size=16)
        plt.title(fit.model, size=10)
    elif istitle == False:
        pass
    else:
        plt.suptitle(istitle, size=16)
    plt.errorbar(fit.abscissauc, fit.binfluxuc, fit.binstduc, fmt='ko', 
                     ms=4, linewidth=1, label='Binned Data', zorder=3)
    plt.plot(fit.abscissa, fit.binnoecl, 'k-', label='No Eclipse', zorder=1)
    #plt.plot(fit.abscissa, fit.binmedianfit, pltfmt2[j], label='Median Fit')
    plt.plot(fit.abscissa, fit.binbestfit,    pltfmt[j], label='Best Fit', zorder=5)
    plt.xticks(size=13)
    plt.yticks(size=13)
    plt.xlabel(fit.xlabel,size=14)
    plt.ylabel('Flux',size=14)
    plt.legend(loc='best')
    if savefile != None:
        plt.savefig(savefile)
    return

# Plot normalized data, best fit, and residuals 
Example 27
Project: POET   Author: kevin218   File: plots.py    GNU General Public License v3.0 5 votes vote down vote up
def ipprojections(event, fit, fignum, savefile=None, istitle=True):
    plt.rcParams.update({'legend.fontsize':11})
    plt.figure(fignum, figsize=(8,4))
    plt.clf()
    if istitle:
        a = plt.suptitle(event.eventname + ' Projections of Position Sensitivity', size=16)
    yround = fit.yuc[0] - fit.y[0]
    xround = fit.xuc[0] - fit.x[0]
    plt.subplot(1,2,1)
    plt.errorbar(yround+fit.binyy, fit.binyflux, fit.binyflstd, fmt='ro', label='Binned Flux', zorder=1)
    plt.plot(yround+fit.binyy, fit.binybestip, 'k-', lw=2, label='BLISS Map', zorder=3)
    plt.xlabel('Pixel Postion in y', size=14)
    plt.ylabel('Normalized Flux', size=14)
    plt.xticks(rotation=90)
    plt.legend(loc='best')
    plt.subplot(1,2,2)
    plt.errorbar(xround+fit.binxx, fit.binxflux, fit.binxflstd, fmt='bo', label='Binned Flux', zorder=1)
    plt.plot(xround+fit.binxx, fit.binxbestip, 'k-', lw=2, label='BLISS Map', zorder=3)
    plt.xlabel('Pixel Postion in x', size=14)
    plt.xticks(rotation=90)
    #a = plt.ylabel('Normalized Flux', size=14)
    a = plt.legend(loc='best')
    plt.subplots_adjust(left=0.11,right=0.97,bottom=0.20,top=0.90,wspace=0.20)
    if savefile != None:
        plt.savefig(savefile)
    return

# BLISS map 
Example 28
Project: QFiPy   Author: kouzapo   File: equities.py    MIT License 5 votes vote down vote up
def plot_log_returns(self):
		log_returns = self.calc_log_returns()

		fig, (ax1, ax2) = plt.subplots(1, 2)

		ax1.plot(log_returns, color = 'blue', lw = 0.4)
		ax2.hist(log_returns, bins = 40, color = 'blue')

		ax1.set_ylabel("% Change", fontsize = 12)

		ax2.set_ylabel("Density", fontsize = 12)
		ax2.set_xlabel("% Change", fontsize = 15)
		plt.suptitle(str(self.quote) + " Log Returns", fontsize = 18)
		plt.show() 
Example 29
Project: adversarial-policies   Author: HumanCompatibleAI   File: visualize.py    MIT License 5 votes vote down vote up
def comparative_densities(
    env, victim_id, n_components, covariance, cutoff_point=None, savefile=None, **kwargs
):
    """PDF of different opponents density distribution.
    For unspecified parameters, see get_full_directory.

    :param cutoff_point: (float): left x-limit.
    :param savefile: (None or str) path to save figure to.
    :param kwargs: (dict) passed through to sns.kdeplot."""
    df = load_metadata(env, victim_id, n_components, covariance)
    fig = plt.figure(figsize=(10, 7))

    grped = df.groupby("opponent_id")
    for name, grp in grped:
        # clean up random_none to just random
        name = name.replace("_none", "")
        avg_log_proba = np.mean(grp["log_proba"])
        sns.kdeplot(grp["log_proba"], label=f"{name}: {round(avg_log_proba, 2)}", **kwargs)

    xmin, xmax = plt.xlim()
    xmin = max(xmin, cutoff_point)
    plt.xlim((xmin, xmax))

    plt.suptitle(f"{env} Densities, Victim Zoo {victim_id}: Trained on Zoo 1", y=0.95)
    plt.title("Avg Log Proba* in Legend")

    if savefile is not None:
        fig.savefig(f"{savefile}.pdf") 
Example 30
Project: tensorflow-mle   Author: kyleclo   File: plot.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_canonical_gauss(x, obs_mu, obs_sigma, obs_loss,
                         title, epsilon=0.05, breaks=100):
    # compute grid
    mu_grid = np.linspace(start=min(obs_mu) - epsilon,
                          stop=max(obs_mu) + epsilon,
                          num=breaks)
    sigma_grid = np.linspace(start=max(min(obs_sigma) - epsilon, 0.0),
                             stop=max(obs_sigma) + epsilon,
                             num=breaks)
    mu_grid, sigma_grid = np.meshgrid(mu_grid, sigma_grid)
    loss_grid = -np.sum(
        [sp.norm(loc=mu_grid, scale=sigma_grid).logpdf(x=xi) for xi in x],
        axis=0)

    # plot contours and loss
    fig, ax = plt.subplots(nrows=1, ncols=2)
    ax[0].contour(mu_grid, sigma_grid, loss_grid,
                  levels=np.linspace(np.min(loss_grid),
                                     np.max(loss_grid),
                                     breaks),
                  cmap='terrain')
    ax[0].plot(obs_mu, obs_sigma, color='red', alpha=0.5,
               linestyle='dashed', linewidth=1, marker='.', markersize=3)
    ax[0].set_xlabel('mu')
    ax[0].set_ylabel('sigma')
    ax[1].plot(range(len(obs_loss)), obs_loss)
    ax[1].set_xlabel('iter')
    # ax[1].set_ylabel('loss')
    plt.suptitle('{}'.format(title))
    plt.show() 
Example 31
Project: tensorflow-mle   Author: kyleclo   File: plot.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_natural_gauss(x, obs_eta1, obs_eta2, obs_loss,
                       title, epsilon=0.05, breaks=300):
    # compute grid
    eta1_grid = np.linspace(start=min(obs_eta1) - epsilon,
                            stop=max(obs_eta1) + epsilon,
                            num=breaks)
    eta2_grid = np.linspace(start=min(obs_eta2) - epsilon,
                            stop=min(max(obs_eta2) + epsilon, 0.0),
                            num=breaks)

    eta1_grid, eta2_grid = np.meshgrid(eta1_grid, eta2_grid)

    mu_grid = get_mu(eta1_grid, eta2_grid)
    sigma_grid = get_sigma(eta2_grid)

    loss_grid = -np.sum(
        [sp.norm(loc=mu_grid, scale=sigma_grid).logpdf(x=xi) for xi in x],
        axis=0)

    # plot contours and loss
    fig, ax = plt.subplots(nrows=1, ncols=2)
    ax[0].contour(eta1_grid, eta2_grid, loss_grid,
                  levels=np.linspace(np.min(loss_grid),
                                     np.max(loss_grid),
                                     breaks),
                  cmap='terrain')
    ax[0].plot(obs_eta1, obs_eta2, color='red', alpha=0.5,
               linestyle='dashed', linewidth=1, marker='.', markersize=3)
    ax[0].set_xlabel('eta1')
    ax[0].set_ylabel('eta2')
    ax[1].plot(range(len(obs_loss)), obs_loss)
    ax[1].set_xlabel('iter')
    # ax[1].set_ylabel('loss')
    plt.suptitle('{}'.format(title))
    plt.show() 
Example 32
Project: 20180116-FullStack-Day   Author: PdxCodeGuild   File: l24_rain.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_dates_totals(dict_list):
    dates = []
    totals = []
    for i in range(len(dict_list)):
        dates.append((dict_list[i]['date']))
        totals.append(dict_list[i]['total'])
    plt.plot(dates, totals)
    plt.ylabel('Total collected rainfall in inches')
    plt.xlabel('dates')
    plt.suptitle('Daily rainfall totals: 1998-2018')
    plt.show() 
Example 33
Project: 20180116-FullStack-Day   Author: PdxCodeGuild   File: l24_rain.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_month_averages_all_years(dict_list):
    averages = []
    month_list = []
    for month in range(1, 12):
        averages.append(get_monthly_average_all_years(dict_list, month))
        month_list.append(month)
    plt.plot(month_list, averages)
    plt.ylabel('Average collected rainfall in inches')
    plt.xlabel('Month')
    plt.suptitle('Monthly rainfall averages: 1998-2018')
    plt.show() 
Example 34
Project: 20180116-FullStack-Day   Author: PdxCodeGuild   File: l24_rain.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_year_totals(dict_list):
    totals = []
    year_list = []
    for year in range(1998, 2019):
        totals.append(get_yearly_total(dict_list, year))
        year_list.append(year)
    plt.bar(year_list, totals)
    plt.ylabel('Rainfall in inches')
    plt.xlabel('Year')
    plt.suptitle('Total collected rainfall per year: 1998-2018')
    plt.show()


# Statistical function calls 
Example 35
Project: rankeval   Author: hpclab   File: effectiveness.py    Mozilla Public License 2.0 5 votes vote down vote up
def plot_tree_wise_average_contribution(performance):
    """
    This method plots the results obtained from the
    tree_wise_average_contribution analysis.

    Parameters
    ----------
    performance: xarray
        The xarray obtained after computing tree_wise_average_contribution.

    Returns
    -------
    fig_list : list
        The list of figures.
    """

    fig_list = []

    for dataset in performance.coords['dataset'].values:
        fig, axes = plt.subplots(len(performance.coords['model'].values),
                                 sharex=True, squeeze=False, figsize=(8, 8))
        fig.suptitle(performance.name + " for " + dataset.name)
        
        for i, model in enumerate(performance.coords['model'].values):
            metric_values = performance.sel(dataset=dataset, model=model)
            axes[i, 0].plot( metric_values.values)
            axes[i, 0].legend((model,), loc='upper center')
            axes[i, 0].yaxis.grid(True, zorder=0, ls="--")

        axes[i, 0].set_xlabel("Number of trees")
        axes[i, 0].set_xlim(xmin=0)
   
        fig_list.append(fig)
    
    return fig_list 
Example 36
Project: rattlesnake   Author: loehnertz   File: rattlesnake.py    MIT License 5 votes vote down vote up
def plot_wave_results(total_original, total_inverted, total_difference, nth_iteration):
    """
    Plots the three waves of the original sound, the inverted one and their difference

    :param total_original: A list of the original wave data
    :param total_inverted: A list of the inverted wave data
    :param total_difference: A list of the difference of 'total_original' and 'total_inverted'
    :param nth_iteration: Used for the label of the x axis
    """

    # Plot the three waves
    plt.plot(total_original, 'b')
    plt.plot(total_inverted, 'r')
    plt.plot(total_difference, 'g')

    # Label the axes
    plt.xlabel('Time (per {}th {} byte chunk)'.format(nth_iteration, CHUNK))
    plt.ylabel('Amplitude (integer representation of each {} byte chunk)'.format(nth_iteration, CHUNK))

    # Calculate and output the absolute median difference level
    plt.suptitle('Waves: original (blue), inverted (red), output (green)', fontsize=14)

    # Display the plotted graph
    plt.show()


# Execute the main function to start the script 
Example 37
Project: nistats   Author: nistats   File: glm_reporter.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _add_params_to_plot(table_details, stat_map_plot):
    """
    Inserts thresholding parameters into the stat map plot as figure suptitle.

    Parameters
    ----------
    table_details: Dict[String, Any]
        Dict of parameters and values used in thresholding.

    stat_map_plot: matplotlib.Axes
        Axes object of the stat map plot.

    Returns
    -------
    stat_map_plot: matplotlib.Axes
        Axes object of the stat map plot, with the added suptitle .
    """
    thresholding_params = [':'.join([name, str(val)]) for name, val in
                           table_details[0].items()]
    thresholding_params = '  '.join(thresholding_params)
    suptitle_text = plt.suptitle(thresholding_params,
                                 fontsize=11,
                                 x=.45,
                                 wrap=True,
                                 )
    fig = list(stat_map_plot.axes.values())[0].ax.figure
    fig = _resize_plot_inches(plot=fig,
                              width_change=.2,
                              height_change=1,
                              )
    if stat_map_plot._black_bg:
        suptitle_text.set_color('w')
    return stat_map_plot 
Example 38
Project: MarkovModels   Author: pmontalb   File: CMonteCarloModel.py    MIT License 5 votes vote down vote up
def plot(self, title=""):
        fig = plt.figure()

        t_vector = sorted(self.model.total_cumulative_stochastic_kernels.keys())

        ax = fig.add_subplot(121)
        ax.set_title("Simulation")

        curve = []
        for t in t_vector:
            curve.append(self.model.underlying_curve.spot_rate(t))

        ax.plot(t_vector, curve, 'bo-')

        for s in range(np.shape(self.generated_path)[0]):
            ax.plot(t_vector, self.generated_path[s], 'r--')

        ax = fig.add_subplot(122)
        ax.set_title("PDF")

        for t in t_vector:
            ax.plot(self.model.grid,
                    self.model.total_stochastic_kernels[t][self.model.x0, :], label=str(t))

        ax.legend()

        plt.suptitle(title)

        plt.show() 
Example 39
Project: MarkovModels   Author: pmontalb   File: COneFactorInterestRateMonteCarlo.py    MIT License 5 votes vote down vote up
def plot(self, title=""):
        fig = plt.figure()

        t_vector = sorted(self.model.total_cumulative_stochastic_kernels.keys())

        ax = fig.add_subplot(121)
        ax.set_title("Simulation")

        curve = []
        for t in t_vector:
            curve.append(self.model.underlying_curve.spot_rate(t))

        ax.plot(t_vector, curve, 'bo-')

        for s in range(np.shape(self.generated_rates_path)[0]):
            ax.plot(t_vector, self.generated_rates_path[s], 'r--')

        ax = fig.add_subplot(122)
        ax.set_title("PDF")

        for t in t_vector:
            ax.plot(self.model.grid,
                    self.model.total_stochastic_kernels[t][self.model.x0, :], label=str(t))

        ax.legend()

        plt.suptitle(title)

        plt.show() 
Example 40
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def main():
    import matplotlib as mpl
    mpl.use('Agg')
    import matplotlib.pyplot as plt
    import seaborn as sns
    fig, axs = plt.subplots(2, 1)
    cp = sns.color_palette()

    for shuffled in range(2):
        result = doit(shuffled)
        print(result)

        ax = axs[shuffled]
        ax.set_title(['Correct labels', 'Random labels'][shuffled])
        ax.set_ylabel('Accuracy')
        ax.set_xlabel('Number of trees')
        ax.set_xscale('log', basex=2)
        ax.set_ylim(0, 1)

        for i, row in enumerate(result):
            model_name, score_train, score_test = row
            ax.plot(NS_ITERATIONS, score_train, linestyle='solid', marker='o', color=cp[i], lw=2, label='{}, train'.format(model_name), alpha=0.8)
            ax.plot(NS_ITERATIONS, score_test, linestyle='dashed', marker='s', color=cp[i], lw=2, label='{}, test'.format(model_name), alpha=0.8)
        
        ax.legend(loc="upper right", frameon=False, bbox_to_anchor=(2, 1))

    plt.tight_layout()
    plt.suptitle('Fitting tree-based models to random labels on MNIST', fontsize=20)
    fig.subplots_adjust(right=0.5, top=0.85)
    fig.savefig('out.png', dpi=200) 
Example 41
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def plot_all(freqs, P, name):
    """Plot grid of subplots
    """
    m, N, N = P.shape
    pos_freqs = freqs[freqs >= 0]

    f, axes = plt.subplots(N, N)
    for i in range(N):
        for j in range(N):
            axes[i, j].fill_between(pos_freqs, P[freqs >= 0, i, j], 0)
            axes[i, j].set_xlim([0, np.max(pos_freqs)])
            axes[i, j].set_ylim([0, 1])
    plt.suptitle(name)
    plt.tight_layout() 
Example 42
Project: gaps   Author: nemanja-m   File: plot.py    MIT License 5 votes vote down vote up
def show_fittest(self, image, title):
        plt.suptitle(title, fontsize=20)
        self._current_image.set_data(image)
        plt.draw()

        # Give pyplot 0.05s to draw image
        plt.pause(0.05) 
Example 43
Project: stock-analysis   Author: stefmolin   File: stock_visualizer.py    MIT License 5 votes vote down vote up
def open_to_close(self, figsize=(10, 4)):
        """
        Visualize the daily change from open to close price.

        Parameters:
            - figsize: A tuple of (width, height) for the plot dimensions.

        Returns:
            A matplotlib Figure object.
        """
        is_higher = self.data.close - self.data.open > 0

        fig = plt.figure(figsize=figsize)

        for exclude_mask, color, label in zip(
            (is_higher, np.invert(is_higher)),
            ('g', 'r'),
            ('price rose', 'price fell')
        ):
            plt.fill_between(
                self.data.index,
                self.data.open,
                self.data.close,
                figure=fig,
                where=exclude_mask,
                color=color,
                label=label
            )
        plt.suptitle('Daily price change (open to close)')
        plt.xlabel('date')
        plt.ylabel('price')
        plt.legend()
        plt.close()
        return fig 
Example 44
Project: stock-analysis   Author: stefmolin   File: stock_visualizer.py    MIT License 5 votes vote down vote up
def fill_between_other(self, other_df, figsize=(10, 4)):
        """
        Visualize the difference in closing price between assets.

        Parameters:
            - other_df: The dataframe with the other asset's data.
            - figsize: A tuple of (width, height) for the plot dimensions.

        Returns:
            A matplotlib Figure object.
        """
        is_higher = self.data.close - other_df.close > 0

        fig = plt.figure(figsize=figsize)

        for exclude_mask, color, label in zip(
            (is_higher, np.invert(is_higher)),
            ('g', 'r'),
            ('asset is higher', 'asset is lower')
        ):
            plt.fill_between(
                self.data.index,
                self.data.close,
                other_df.close,
                figure=fig,
                where=exclude_mask,
                color=color,
                label=label
            )
        plt.suptitle(
            'Differential between asset closing price (this - other)'
        )
        plt.legend()
        plt.ylabel('price')
        plt.close()
        return fig 
Example 45
Project: kappa   Author: ajkerr0   File: plot.py    MIT License 5 votes vote down vote up
def face(molecule, facenum):
    """Plot the given interface of the molecule"""
    
    mol = copy.deepcopy(molecule)
    face = mol.faces[facenum]
    
    fig = plt.figure()
    
    #rotate molecule to 'camera' position
    axis = np.cross(face.norm, np.array([0.,0.,1.]))
    mag = np.linalg.norm(axis)
    if mag < 1e-10:
        #check for parallel/anti-parallel
        dot = np.dot(face.norm, np.array([0.,0.,1.]))
        if dot < 0.:
            #don't rotate
            pass
        if dot >0.:
            #flip the molecule
            mol.invert()
    else:
        angle = np.degrees(np.arcsin(mag))
        mol.rotate(axis,angle)
        
    #center interface
    mol.translate(-face.pos)
    
    plt.scatter(mol.posList[face.atoms][:,0], mol.posList[face.atoms][:,1], s=30., c='red')
    ds = .2

#    ds = np.full(len(face.atoms), ds)   
#    plt.text(mol.posList[face.atoms][:,0]+ds, mol.posList[face.atoms][:,1]+ds, str(face.atoms))
    for atom in face.atoms:
        plt.text(mol.posList[atom][0]+ds, mol.posList[atom][1]+ds, str(atom), color='blue')
    
    fig.suptitle("Interface %s of %s" % (facenum, molecule), fontsize=18)
    plt.axis('equal')
    
    plt.show() 
Example 46
Project: MismatchLossStudy   Author: SunPower   File: mismatch_model.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def show_mismatch_best_worst_case(df_stc):
    a = df_stc.loc[df_stc.mismatch_loss.idxmin()] # high mismatch loss
    b = df_stc.loc[df_stc.mismatch_loss.idxmax()] # low mismatch loss
    df_a = [ df_flash_data.loc[a.indices[i]][['imp1','vmp1','pmp1']] for i in range(3)]
    df_b = [ df_flash_data.loc[b.indices[i]][['imp1','vmp1','pmp1']] for i in range(3)]

    pvmods_a = [ df_flash_data.loc[a.indices[i]]['pvmods_obj'] for i in range(3)]
    pvmods_b = [ df_flash_data.loc[b.indices[i]]['pvmods_obj'] for i in range(3)]

    a_pmp = [df_a[i].pmp1.values for i in range(3)]
    b_pmp = [df_b[i].pmp1.values for i in range(3)]

    a_vmp = [df_a[i].vmp1.values for i in range(3)]
    b_vmp = [df_b[i].vmp1.values for i in range(3)]

    a_imp = [df_a[i].imp1.values for i in range(3)]
    b_imp = [df_b[i].imp1.values for i in range(3)]

    pvstrs_list_a,pvstrs_list_b = [],[]
    for i in range(3):
        pvstrs_list_a.append( PVstring(numberMods=8, pvmods=pvmods_a[i].values, pvconst=pvconstants))
        pvstrs_list_b.append( PVstring(numberMods=8, pvmods=pvmods_b[i].values, pvconst=pvconstants))

    pvsys_a = PVsystem(numberStrs=3, pvstrs=pvstrs_list_a, pvconst=pvconstants)
    pvsys_b = PVsystem(numberStrs=3, pvstrs=pvstrs_list_b, pvconst=pvconstants)

    plt.figure()
    fig, ax = plt.subplots(1,2, sharey=True, sharex=True)
    for pstr in pvstrs_list_a:
        ax[0].plot(pstr.Istring, pstr.Pstring, 'o-')
    ax[0].set_ylim([0,3000])
    ax[0].set_title('high mismatch loss PV system %f'%(a['mismatch_loss']))

    for pstr in pvstrs_list_b:
        ax[1].plot(pstr.Istring, pstr.Pstring, 'o-')
    ax[1].set_ylim([0,3000])
    ax[1].set_title('low mismatch loss PV system %f'%(b['mismatch_loss']))
    plt.suptitle('PI curve for PV strings for %s'%tech) 
Example 47
Project: MiaSeg   Author: jajenQin   File: medicalnet_preprocessing.py    GNU General Public License v3.0 5 votes vote down vote up
def preprocess_for_eval(image, output_height, output_width):
  """Preprocesses the given image for evaluation.

  Args:
    image: A `Tensor` representing an image of arbitrary size.
    output_height: The height of the image after preprocessing.
    output_width: The width of the image after preprocessing.

  Returns:
    A preprocessed image.
  """
  tf.summary.image('image', tf.expand_dims(image, 0))
  # Transform the image to floats.
  image = tf.to_float(image)
  image = tf.expand_dims(image, 0)
  image = tf.image.resize_bilinear(image, [output_height, output_width])
  image = tf.squeeze(image, [0])
  # with tf.Session() as sess:
  #   sess.run([image])
  # plt.figure()
  # plt.imshow(image.astype(np.uint8))
  # plt.suptitle("Test image", fontsize=14, fontweight='bold')
  # plt.axis('off')
  # plt.show()
  # Resize and crop if needed.
  resized_image = tf.image.resize_image_with_crop_or_pad(image,
                                                         output_width,
                                                         output_height)
  tf.summary.image('resized_image', tf.expand_dims(resized_image, 0))

  # Subtract off the mean and divide by the variance of the pixels.
  return tf.image.per_image_standardization(resized_image) 
Example 48
Project: vnpy_crypto   Author: birforce   File: test_mosaicplot.py    MIT License 5 votes vote down vote up
def test_data_conversion():
    # It will not reorder the elements
    # so the dictionary will look odd
    # as it key order has the c and b
    # keys swapped
    import pandas
    fig, ax = pylab.subplots(4, 4)
    data = {'ax': 1, 'bx': 2, 'cx': 3}
    mosaic(data, ax=ax[0, 0], title='basic dict', axes_label=False)
    data = pandas.Series(data)
    mosaic(data, ax=ax[0, 1], title='basic series', axes_label=False)
    data = [1, 2, 3]
    mosaic(data, ax=ax[0, 2], title='basic list', axes_label=False)
    data = np.asarray(data)
    mosaic(data, ax=ax[0, 3], title='basic array', axes_label=False)

    data = {('ax', 'cx'): 1, ('bx', 'cx'): 2, ('ax', 'dx'): 3, ('bx', 'dx'): 4}
    mosaic(data, ax=ax[1, 0], title='compound dict', axes_label=False)
    mosaic(data, ax=ax[2, 0], title='inverted keys dict', index=[1, 0], axes_label=False)
    data = pandas.Series(data)
    mosaic(data, ax=ax[1, 1], title='compound series', axes_label=False)
    mosaic(data, ax=ax[2, 1], title='inverted keys series', index=[1, 0])
    data = [[1, 2], [3, 4]]
    mosaic(data, ax=ax[1, 2], title='compound list', axes_label=False)
    mosaic(data, ax=ax[2, 2], title='inverted keys list', index=[1, 0])
    data = np.array([[1, 2], [3, 4]])
    mosaic(data, ax=ax[1, 3], title='compound array', axes_label=False)
    mosaic(data, ax=ax[2, 3], title='inverted keys array', index=[1, 0], axes_label=False)

    gender = ['male', 'male', 'male', 'female', 'female', 'female']
    pet = ['cat', 'dog', 'dog', 'cat', 'dog', 'cat']
    data = pandas.DataFrame({'gender': gender, 'pet': pet})
    mosaic(data, ['gender'], ax=ax[3, 0], title='dataframe by key 1', axes_label=False)
    mosaic(data, ['pet'], ax=ax[3, 1], title='dataframe by key 2', axes_label=False)
    mosaic(data, ['gender', 'pet'], ax=ax[3, 2], title='both keys', axes_label=False)
    mosaic(data, ['pet', 'gender'], ax=ax[3, 3], title='keys inverted', axes_label=False)

    pylab.suptitle('testing data conversion (plot 1 of 4)')
    #pylab.show()
    pylab.close('all') 
Example 49
Project: vnpy_crypto   Author: birforce   File: test_mosaicplot.py    MIT License 5 votes vote down vote up
def test_mosaic_simple():
    # display a simple plot of 4 categories of data, splitted in four
    # levels with increasing size for each group
    # creation of the levels
    key_set = (['male', 'female'], ['old', 'adult', 'young'],
               ['worker', 'unemployed'], ['healty', 'ill'])
    # the cartesian product of all the categories is
    # the complete set of categories
    keys = list(product(*key_set))
    data = OrderedDict(zip(keys, range(1, 1 + len(keys))))
    # which colours should I use for the various categories?
    # put it into a dict
    props = {}
    #males and females in blue and red
    props[('male',)] = {'color': 'b'}
    props[('female',)] = {'color': 'r'}
    # all the groups corresponding to ill groups have a different color
    for key in keys:
        if 'ill' in key:
            if 'male' in key:
                props[key] = {'color': 'BlueViolet' , 'hatch': '+'}
            else:
                props[key] = {'color': 'Crimson' , 'hatch': '+'}
    # mosaic of the data, with given gaps and colors
    mosaic(data, gap=0.05, properties=props, axes_label=False)
    pylab.suptitle('syntetic data, 4 categories (plot 2 of 4)')
    #pylab.show()
    pylab.close('all') 
Example 50
Project: vnpy_crypto   Author: birforce   File: test_mosaicplot.py    MIT License 5 votes vote down vote up
def test_mosaic():
    # make the same analysis on a known dataset

    # load the data and clean it a bit
    affairs = datasets.fair.load_pandas()
    datas = affairs.exog
    # any time greater than 0 is cheating
    datas['cheated'] = affairs.endog > 0
    # sort by the marriage quality and give meaningful name
    # [rate_marriage, age, yrs_married, children,
    # religious, educ, occupation, occupation_husb]
    datas = sort_values(datas, ['rate_marriage', 'religious'])

    num_to_desc = {1: 'awful', 2: 'bad', 3: 'intermediate',
                      4: 'good', 5: 'wonderful'}
    datas['rate_marriage'] = datas['rate_marriage'].map(num_to_desc)
    num_to_faith = {1: 'non religious', 2: 'poorly religious', 3: 'religious',
                      4: 'very religious'}
    datas['religious'] = datas['religious'].map(num_to_faith)
    num_to_cheat = {False: 'faithful', True: 'cheated'}
    datas['cheated'] = datas['cheated'].map(num_to_cheat)
    # finished cleaning
    fig, ax = pylab.subplots(2, 2)
    mosaic(datas, ['rate_marriage', 'cheated'], ax=ax[0, 0],
                title='by marriage happiness')
    mosaic(datas, ['religious', 'cheated'], ax=ax[0, 1],
                title='by religiosity')
    mosaic(datas, ['rate_marriage', 'religious', 'cheated'], ax=ax[1, 0],
                title='by both', labelizer=lambda k:'')
    ax[1, 0].set_xlabel('marriage rating')
    ax[1, 0].set_ylabel('religion status')
    mosaic(datas, ['religious', 'rate_marriage'], ax=ax[1, 1],
                title='inter-dependence', axes_label=False)
    pylab.suptitle("extramarital affairs (plot 3 of 4)")
    #pylab.show()
    pylab.close('all')