コード例 #1
0
def plotimage(imgflux_pl, zminfl, zmaxfl, plmode, row, column,
              xdim, ydim, winx, winy, tlabel, cmap):
    # pixel limits of the subimage
    ymin = row
    ymax = ymin + ydim
    xmin = column
    xmax = xmin + xdim
    # plot limits for flux image
    ymin = float(ymin) - 0.5
    ymax = float(ymax) - 0.5
    xmin = float(xmin) - 0.5
    xmax = float(xmax) - 0.5
    # plot the image window
    ax = plt.axes([winx,winy,0.37,0.45])
    plt.imshow(imgflux_pl,aspect='auto',interpolation='nearest',origin='lower',
           vmin=zminfl,vmax=zmaxfl,extent=(xmin,xmax,ymin,ymax),cmap=cmap)
    plt.gca().set_autoscale_on(False)
    labels = ax.get_yticklabels()
    plt.gca().xaxis.set_major_formatter(plt.ScalarFormatter(useOffset=False))
    plt.gca().yaxis.set_major_formatter(plt.ScalarFormatter(useOffset=False))
    if plmode == 1:
        plt.setp(plt.gca(),xticklabels=[])
    if plmode == 2:
        plt.setp(plt.gca(),xticklabels=[],yticklabels=[])
    if plmode == 4:
        plt.setp(plt.gca(),yticklabels=[])
    if plmode == 3 or plmode == 4:
        plt.xlabel('Pixel Column Number', {'color' : 'k'})
    if plmode == 1 or plmode == 3:
        plt.ylabel('Pixel Row Number', {'color' : 'k'})
    plt.text(0.05, 0.93,tlabel,horizontalalignment='left',verticalalignment='center',
               fontsize=36,fontweight=500,transform=ax.transAxes)
コード例 #2
0
def _setup_msd_plot(ax):
    # Label ticks with plain numbers, not scientific notation:
    ax.xaxis.set_major_formatter(plt.ScalarFormatter(useMathText=True))
    ax.yaxis.set_major_formatter(plt.ScalarFormatter(useMathText=True))
    ax.set_ylim(0.001, 100)
    logger.info('Limits of y range are manually set to %f - %f.', *plt.ylim())
    ax.set_xlabel('lag time [s]')
    ax.set_ylabel('msd [um$^2$]')
コード例 #3
0
ファイル: plotter.py プロジェクト: DamianPereira/metrika
 def __init__(self, configurator, label='', title=''):
     self.configurator = configurator
     self.label = label
     self.title = title
     self.xlabel = ""
     self.ylabel = ""
     self.xscale = "linear"
     self.yscale = "linear"
     self.xformat = plt.ScalarFormatter()
     self.yformat = plt.ScalarFormatter()
コード例 #4
0
def location(shape):
    """shape the window, enforce absolute scaling, rotate the labels"""

    # position first axes inside the plotting window
    ax = plt.axes(shape)
    # force tick labels to be absolute rather than relative
    plt.gca().xaxis.set_major_formatter(plt.ScalarFormatter(useOffset=False))
    plt.gca().yaxis.set_major_formatter(plt.ScalarFormatter(useOffset=False))
    ax.yaxis.set_major_locator(plt.MaxNLocator(5))
    # rotate y labels by 90 deg
    labels = ax.get_yticklabels()

    return ax
コード例 #5
0
    def setup_axis_labels(self):
        """ Function responsible for axies management. """
        self.ax.yaxis.set_major_formatter(plt.ScalarFormatter())
        self.ax.xaxis.set_major_formatter(plt.ScalarFormatter())

        self.ax.set_xticks(range(1, self.amount + 1))
        self.ax.set_xlim(0.5, self.amount + 0.5)

        self.ax.set_xlabel('Device ID', fontsize=13)
        self.ax.set_ylabel(self.ylabel, fontsize=13)
        self.ax.tick_params(axis='both', labelsize=12)

        self.ax.set_xticklabels(self.ids)
コード例 #6
0
def plot_salt(histogram, name, ymaxlimit=None):

    fig, ax = plt.subplots()
    fig.set_size_inches(6, 5)
    #     labels, values = zip(*sorted(hist.items()))
    labels, values = zip(*sorted(histogram.items(), key=lambda x: int(x[0])))

    indexes = np.arange(len(labels))
    width = 1

    plt.bar(indexes, values, width, color=color, alpha=opacity)

    fmt = plt.ScalarFormatter(useOffset=False)
    plt.gca().xaxis.set_major_formatter(fmt)
    ax.set_xlabel('LC Step #', fontproperties=prop32)
    ax.set_ylabel('# high quality PSMs', fontproperties=prop32)
    if ymaxlimit:
        ax.set_ylim(0, ymaxlimit)

    for label in ax.get_yticklabels():
        label.set_fontproperties(prop24)

    plt.title(
        'Peptides identified per Liquid Chromatography Step\n{}'.format(name),
        fontproperties=prop24,
        y=1.1)
    ax.set_xticks(indexes + width / 2)
    ax.set_xticklabels(labels, fontproperties=prop24)
    #plt.tight_layout()
    plt.show()
コード例 #7
0
def setup_figure(width='regular', height=None, aspect='normal', style='sans-serif',
                 tex=False, param_kwargs={}, figure_kwargs={}):
    """
    Create a standardised figure.

    Args:
        width (float, str): width of the figure in cm or a preset string
        height (float): height of the figure in cm
        aspect (float): aspect ratio of the figure (height/width)
        style (str): The font style to use in the figure
        tex (bool): Whether to use LaTeX to render the figure
        **param_kwargs: Arbitrary keyword arguments that are added to or override existing figure
            parameters.
        **figure_kwargs: Arbitrary keyword arguments that are passed to figure creation.

    Returns:
        Figure: a matplotlib figure instance
    """
    # set the figure size
    fig_size = get_figure_size(width, height, aspect)
    # set the figure parameters
    fig_params = get_fig_params(style, tex, **param_kwargs)
    plt.rcParams.update(fig_params)
    formatter = plt.ScalarFormatter(useOffset=False, useMathText=True)
    formatter.set_scientific(True)
    fig = plt.figure(figsize=fig_size, tight_layout=True, **figure_kwargs)
    return fig
コード例 #8
0
def print_performance(cm,fignum):
    if fignum == 20200223:
        fignum = '_DeepSleepNet'
    tp = np.diagonal(cm).astype(np.float)
    tpfp = np.sum(cm, axis=0).astype(np.float) # sum of each col
    tpfn = np.sum(cm, axis=1).astype(np.float) # sum of each row
    acc = np.sum(tp) / np.sum(cm)
    precision = tp / tpfp
    recall = tp / tpfn
    f1 = (2 * precision * recall) / (precision + recall)
    mf1 = np.mean(f1)

    y_formatter = plt.ScalarFormatter(useOffset=False)
    FL_acc.append(acc)
    FL_F1acc.append(mf1)
    sn.heatmap(cm, annot=True, annot_kws={"size": 10}, fmt='d')
    plt.savefig('./results/ConfusionMatrix/subject'+str(fignum)+'.png', dpi=300)
    plt.clf()

    print("Sample: {}".format(np.sum(cm)))
    print("W: {}".format(tpfn[W]))
    print("N1: {}".format(tpfn[N1]))
    print("N2: {}".format(tpfn[N2]))
    print("N3: {}".format(tpfn[N3]))
    print("REM: {}".format(tpfn[REM]))
    print("Confusion matrix:")
    print(cm)
    print("Precision: {}".format(precision))
    print("Recall: {}".format(recall))
    print("F1: {}".format(f1))
    print("Overall accuracy: {}".format(acc))
    print("Macro-F1 accuracy: {}".format(mf1))
コード例 #9
0
ファイル: utils.py プロジェクト: ssimonee/nelpy
def set_scientific(low, high, axis=None, *axes):
    """Set the axes or axis specified by `axis` to use scientific notation for
    ticklabels, if the value is <10**low or >10**high.

    Parameters
    ----------
    low : int
        Lower exponent bound for non-scientific notation
    high : int
        Upper exponent bound for non-scientific notation
    axis : str (default=None)
        Which axis to format ('x', 'y', or None for both)
    ax : axis object (default=pyplot.gca())
        The matplotlib axis object to use

    """
    # get the axis
    if len(axes) == 0:
        axes = [plt.gca()]
    # create the tick label formatter
    fmt = plt.ScalarFormatter()
    fmt.set_scientific(True)
    fmt.set_powerlimits((low, high))
    # format the axis/axes
    for ax in axes:
        if axis is None or axis == 'x':
            ax.get_yaxis().set_major_formatter(fmt)
        if axis is None or axis == 'y':
            ax.get_yaxis().set_major_formatter(fmt)
コード例 #10
0
def set_pressure_axis(ax, **kargs):
    '''
    Adjust the y-axis of a plot to represent pressure levels.
    Parameters
    ----------
    ax : axis object
    Keyword arguments
    -----------------
    limits : (float, float) 
        A tuple of float to indicate the lower and upper limit.
    ticks : list of int 
        A list of int to replace the standard ticks. (20, 50, 100, 200, 500, 1000)
    label : string
        Label text that shall be shown.
    '''
    from met_tools import USstdP
    import matplotlib.pyplot as plt
    import calendar
    limits = sorted(kargs.pop(
        "limits", (1000., USstdP(30 * kilo) / hecto)))[::-1]  # reverse sorted
    ticks = kargs.pop("ticks", [20, 50, 100, 200, 500, 1000])
    label = kargs.pop("label", "Pressure (hPa)")
    ax.set_ylabel(label)
    ax.set_yscale('log')
    ax.yaxis.set_major_formatter(plt.ScalarFormatter())
    ax.set_yticks(ticks)
    ax.invert_yaxis()
    ax.set_ylim(limits)
コード例 #11
0
def display_data(data, x_ax_data, y_ax_data):
    formatter = plt.ScalarFormatter(useOffset=False, useMathText=True)
    formatter.set_scientific(True)
    formatter.set_powerlimits((-3, 3))
    fig = plt.figure()
    ax = fig.add_subplot(111)
    Z = np.nan_to_num(data)
    Xi = x_ax_data
    Yi = np.nan_to_num(y_ax_data)
    minimum = Z.min()
    maximum = Z.max()
    # set colour mapping for all axes #
    c_levels = np.linspace(minimum, 1.05 * maximum, 100)
    # create longitudinal spectral image subplot #
    X, Y = np.meshgrid(Xi, Yi)
    cfax = ax.contourf(X,
                       Y,
                       Z,
                       c_levels,
                       alpha=1.0,
                       cmap=cm.get_cmap(cm.Spectral_r,
                                        len(c_levels) - 1))
    # add colour bar to far right of figure #
    cb = plt.colorbar(cfax, shrink=0.75, extend='both')
    cb.set_label('optical scattering (a.u.)')
    #ax.set_yscale('log')
    ax.xaxis.set_major_formatter(formatter)
コード例 #12
0
 def __init__(self, temporal_data):
     self.data = temporal_data
     # figure setup #
     self.setup_figure()
     self.fig = plt.figure()
     # setup subplots #
     self.gs0 = gridspec.GridSpec(1, 2)
     self.spectra_ax = plt.Subplot(self.fig, self.gs0[0, 1])
     self.gs00 = gridspec.GridSpecFromSubplotSpec(1,
                                                  3,
                                                  subplot_spec=self.gs0[0,
                                                                        0])
     self.conductance_ax = plt.Subplot(self.fig,
                                       self.gs00[0, 1],
                                       sharey=self.spectra_ax)
     self.current_ax = 0
     self.force_ax = plt.Subplot(self.fig,
                                 self.gs00[0, 0],
                                 sharey=self.spectra_ax)
     # set axis formatter #
     self.formatter = plt.ScalarFormatter(useOffset=False, useMathText=True)
     self.formatter.set_scientific(True)
     self.formatter.set_powerlimits((-3, 3))
     # add subplots #
     self.add_spectra_subplot()
     self.add_conductance_subplot()
     self.add_force_subplot()
     #plt.tight_layout()
     self.gs0.tight_layout(self.fig, pad=0.25)  #, w_pad=0.1, h_pad=0.1)
     self.save_figure()
コード例 #13
0
def imshow_logpolars(fig, spectra, log_base, im_shape):
    import matplotlib.pyplot as plt
    import mpl_toolkits.axes_grid1 as axg
    low = 1.0
    high = log_base ** spectra[0].shape[1]
    logpolars_extent = (low, high,
                        0, 180)
    grid = axg.ImageGrid(
        fig, 111, nrows_ncols=(2, 1),
        add_all=True,
        aspect=False,
        axes_pad=0.4, label_mode="L",
    )
    ims = [np.log(np.abs(im)) for im in spectra]
    for ii, im in enumerate(ims):
        vmin = np.percentile(im, 1)
        vmax = np.percentile(im, 99)
        grid[ii].set_xscale("log", basex=log_base)
        grid[ii].get_xaxis().set_major_formatter(plt.ScalarFormatter())
        im = grid[ii].imshow(im, cmap=plt.cm.viridis, vmin=vmin, vmax=vmax,
                             aspect="auto", extent=logpolars_extent)
        grid[ii].set_xlabel(_t("log radius"))
        grid[ii].set_ylabel(_t("azimuth / degrees"))

        xticklabels = ["{:.3g}".format(tick * 2 / im_shape[0])
                       for tick in grid[ii].get_xticks()]

        grid[ii].set_xticklabels(
            xticklabels,
            rotation=40, rotation_mode="anchor", ha="right"
        )

    return fig
コード例 #14
0
ファイル: imputation.py プロジェクト: chunhui1211/MissingData
def barplot(method,new_df): 
    plt.figure()
    g=sns.factorplot(var,data=new_df,aspect=2,kind="count",color="steelblue")
    if len(np.unique(new_df[var]))>=20:
        g.set_xticklabels(step=10,rotation=35)
    plt.title(enmethoden(method),fontsize=24)
    plt.ScalarFormatter()
    plt.savefig('./imputation_photo/'+name[0]+'/'+count+var+'_'+method+'_factor.png',bbox_inches='tight',facecolor="w" )
コード例 #15
0
def main():
    kepler_response = retrieve_kepler_response()
    vmag_response = retrieve_vmag_response()

    planets = build_planet_list()

    xdata, ydata = [], []
    label_point, label_value = [], []
    for spectral_type, temperature in spectral_types():
        spectra = spectra_pickles(spectral_type)
        vmag = spectra.custom_mag(vmag_response)[0]
        kepmag = spectra.custom_mag(kepler_response)[0]

        correction_factor = vmag - kepmag
        print "{spectype}: {teff} - {cf:5.3f}".format(
            spectype=spectral_type.upper(),
            cf=correction_factor,
            teff=temperature)
        xdata.append(temperature)
        ydata.append(correction_factor)

        if '0v' in spectral_type.lower():
            label_point.append(temperature)
            label_value.append(spectral_type.replace('0v', '').upper())

    with open('results/mapping.json', 'w') as outfile:
        json.dump([{
            'teff': teff,
            'correction': correction
        } for (teff, correction) in zip(xdata, ydata)],
                  outfile,
                  indent=2)

    plt.plot(xdata, ydata, 'r.')
    plt.xscale('log')
    errs = np.vstack([planets.TEFFUPPER, planets.TEFFLOWER])
    plt.errorbar(planets.TEFF,
                 planets.correction_factor,
                 xerr=errs,
                 ls='None',
                 color='b')
    plt.scatter(planets.TEFF, planets.correction_factor, color='b')
    plt.xlabel(r'Stellar effective temperature / K')
    plt.ylabel(r'$V - K_{p}$')
    ticks = sorted([base * 10**exp for base in [1, 5] for exp in [3, 4, 5]])
    plt.xticks(ticks, ticks)
    plt.gca().xaxis.set_major_formatter(plt.ScalarFormatter())
    lims = plt.xlim(2000, 50000)

    plt.twiny()
    plt.xscale('log')
    plt.xticks(label_point, label_value)
    plt.xlim(*lims)
    plt.xlabel(r'Approximate spectral type')
    plt.tight_layout()
    plt.savefig('results/plot.png')
コード例 #16
0
ファイル: hash_join_graphs.py プロジェクト: zeroshade/arrow
def plot_1d(test, argname, ax, label=None):
    x_axis = test.args[argname]
    y_axis = test.times
    ax.plot(x_axis, y_axis, label=label)
    if is_multiplicative(x_axis):
        ax.set_xscale('log', base=(x_axis[1] / x_axis[0]))
        ax.xaxis.set_major_formatter(plt.ScalarFormatter())
    ax.legend()
    ax.set_xlabel(argname)
    ax.set_ylabel('rows/sec')
コード例 #17
0
ファイル: extrapolate.py プロジェクト: stknecht/qcmaquis
def plot(flist, sweepnr=None):

    extr = extrapolate_base.energy2y(flist, sweepnr)
    xdata = extr.xdata()
    ydata = extr.ydata()

    fit = extr.linfit()
    xf = np.linspace(1e-16, max(xdata), 100)
    yf = fit(xf)

    print "{:30s} {:13.9f}   {:12.1f}    {:5s}  {:3s}".format(
        "extrapolation", fit(0), 0, "infty", "")
    print "{:30s} {:14.9f}".format("extrapolation error", fit(0) - ydata[0])

    fig = plt.figure()
    ax = fig.add_subplot(111)
    dots = plt.plot(xdata, ydata, 'o', xf, yf, '-')

    plt.ticklabel_format(style='sci',
                         axis='x',
                         scilimits=(3, 4),
                         useOffset=False)
    xfmt = plt.ScalarFormatter(useOffset=False, useMathText=True)
    xfmt.set_scientific(True)
    ax.yaxis.set_major_formatter(xfmt)

    plt.xlabel(r'\textbf{truncation error} $\varepsilon$')
    plt.ylabel(r'\textbf{Energy [Hartree]}')
    #plt.xlabel('truncation error $\\varepsilon$')
    #plt.ylabel('Energy [Hartree]')
    fig.subplots_adjust(left=0.2)

    def autolabel(xd, yd, labels):
        # attach some text labels
        yshift = (max(yd) - min(yd)) * 0.05
        xshift = (max(xd) - min(xd)) * 0.2
        for x, y, l in zip(xd, yd, labels):
            #item = ax.text(x - xshift, y, '$m=%d$'%l,
            #            ha='right', va='center')
            item = ax.text(x, y, '$m=%d$' % l, ha='center', va='bottom')
            item.set_fontsize(18)

    autolabel(xdata, ydata, extr.m())

    # add the extrapolated energy to the plot"
    ext_note = ax.text(max(xf) / 2.0 + (max(xf) - min(xf)) * 0.05,
                       fit(0),
                       'extrapolation:\n$%.6f$' % fit(0),
                       ha='left',
                       va='center')
    # position below is yaxis
    #ext_note = ax.text(0, fit(0), '$%.6f$'%fit(0), ha='right', va='top')

    plt.savefig('e.svg')
コード例 #18
0
 def setup_axes(self):
     self.ax.autoscale(True)
     self.formatter = plt.ScalarFormatter(useOffset=False, useMathText=True)
     self.ax.yaxis.set_major_formatter(self.formatter)
     self.rax.yaxis.set_major_formatter(self.formatter)
     self.ax.minorticks_on()
     self.rax.minorticks_on()
     self.ax.set_xlabel("Time")
     self.ax.set_ylabel("Temperature ($^\circ$C)")
     self.rax.set_ylabel("Humidity (% RH)")
     labels = self.ax.get_xticklabels()
     for label in labels:
         label.set_rotation(30)
コード例 #19
0
	def baseZero(self):
		""" 
		Set baseline of seismograms as zeros (stack all).
		Do not normalize seismogram by setting opts.ynorm<0.
		"""
		self.getZero()
		anorm = 1./np.clip(self.nseis/50, 2, 10)
		self.alphas *= anorm
		self.opts.ynorm = -1
		#self.axss.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
		formatter = plt.ScalarFormatter(useMathText=True)
		formatter.set_powerlimits((0, 0))
		self.axss.yaxis.set_major_formatter(formatter)
コード例 #20
0
    def setup_axis_labels(self, runtime, time, ymin, ymax, xtick_amount=5):
        """
        Setup axis labels based on runtime, time, and ylims. This functions is responsible for dynamically managing
        axises and axises labels.
        """
        xtick_step = round(len(runtime) / xtick_amount)
        self.ax.set_xlim(runtime[0], runtime[-1])
        self.ax.set_xticks(runtime[::-xtick_step])
        self.ax.set_xticklabels(time[::-xtick_step])

        self.ax.yaxis.set_major_formatter(plt.ScalarFormatter())
        self.ax.set_ylim(ymin, ymax)

        self.ax.set_xlabel(self.xlabel, fontsize=13)
        self.ax.set_ylabel(self.ylabel, fontsize=13)
        self.ax.tick_params(axis='both', labelsize=12)
コード例 #21
0
def symticks(ax, linthresh=1, linstep=0.2, axis='x'):
    l, r = ax.get_xlim() if axis == 'x' else ax.get_ylim()
    axis = ax.xaxis if axis == 'x' else ax.yaxis
    m = max(l, r)
    k = min(l, r)
    major = int(np.floor(np.log10(m)))
    lin_pos = np.arange(-linthresh, 0, linstep)[1:]

    major_pos = 10**np.arange(major + 1)
    minor_pos = [np.arange(2, 10) * 10**i for i in range(major)]
    rest = np.arange(np.ceil(m / 10**major)) * 10**major
    minor_pos = np.array(minor_pos).flat

    axis.set_ticks(np.hstack((-lin_pos, lin_pos[lin_pos > k], minor_pos, rest)),
                   minor=True)
    axis.set_ticks(np.hstack((0, major_pos)))
    axis.set_major_formatter(plt.ScalarFormatter())
コード例 #22
0
ファイル: kepdiffim.py プロジェクト: jonnycrunch/PyKE
def plotimage(imgsum_pl, imgvar_pl, imgdev_pl, zminsum, zminvar, zmindev,
              zmaxsum, zmaxvar, zmaxdev, xmin ,xmax, ymin, ymax, colmap,
              plotfile):

    plt.figure(figsize=[15, 6])
    plt.clf()

    # plot the image window
    ax = plt.axes([0.04, 0.11, 0.31, 0.78])
    plt.imshow(imgsum_pl,aspect='auto', interpolation='nearest',
               origin='lower', vmin=zminsum, vmax=zmaxsum,
               extent=(xmin, xmax, ymin, ymax), cmap=colmap)
    plt.gca().set_autoscale_on(False)
    labels = ax.get_yticklabels()
    plt.setp(labels, 'rotation', 90)
    plt.gca().xaxis.set_major_formatter(plt.ScalarFormatter(useOffset=False))
    plt.gca().yaxis.set_major_formatter(plt.ScalarFormatter(useOffset=False))
    plt.xlabel('Pixel Column Number', {'color' : 'k'})
    plt.ylabel('Pixel Row Number', {'color' : 'k'})
    plt.title('Flux', {'color' : 'k', 'fontsize' : '16'})

    # plot the variance window
    plt.axes([0.36, 0.11, 0.31, 0.78])
    plt.imshow(imgvar_pl, aspect='auto', interpolation='nearest',
               origin='lower', vmin=zminvar, vmax=zmaxvar,
               extent=(xmin, xmax, ymin, ymax), cmap=colmap)
    plt.gca().set_autoscale_on(False)
    plt.gca().xaxis.set_major_formatter(plt.ScalarFormatter(useOffset=False))
    plt.gca().yaxis.set_major_formatter(plt.ScalarFormatter(useOffset=False))
    plt.setp(plt.gca(),yticklabels=[])
    plt.xlabel('Pixel Column Number', {'color' : 'k'})
    try:
        plt.title(r'$\chi$ Distribution', {'color' : 'k', 'fontsize' : '16'})
    except:
        plt.title('Chi Distribution', {'color' : 'k', 'fontsize' : '16'})

    # plot the normalized standard deviation window
    plt.axes([0.68, 0.11, 0.31, 0.78])
    plt.imshow(imgdev_pl, aspect='auto', interpolation='nearest',
               origin='lower', vmin=zmindev, vmax=zmaxdev,
               extent=(xmin, xmax, ymin, ymax), cmap=colmap)
    plt.gca().set_autoscale_on(False)
    plt.gca().xaxis.set_major_formatter(plt.ScalarFormatter(useOffset=False))
    plt.gca().yaxis.set_major_formatter(plt.ScalarFormatter(useOffset=False))
    plt.setp(plt.gca(),yticklabels=[])
    plt.xlabel('Pixel Column Number', {'color' : 'k'})
    plt.title('Normalized Standard Deviation', {'color' : 'k', 'fontsize' : '16'})

    # render plot
    plt.show()

    if plotfile is not None:
        plt.savefig(plotfile)
コード例 #23
0
    def __init__(self, spatial_data):
        self.data = spatial_data
        # figure setup #
        self.setup_figure()
        self.fig = plt.figure()
        # setup subplots #
        if self.data.dual_pol:
            self.gs0 = gridspec.GridSpec(1, 3, width_ratios=[0.75, 1, 1])
            self.spectra_long_ax = plt.Subplot(self.fig, self.gs0[0, 1])
            self.spectra_trans_ax = plt.Subplot(self.fig,
                                                self.gs0[0, 2],
                                                sharex=self.spectra_long_ax,
                                                sharey=self.spectra_long_ax)
        else:
            self.gs0 = gridspec.GridSpec(1, 2, width_ratios=[0.75, 1])
            self.spectra_long_ax = plt.Subplot(self.fig, self.gs0[0, 1])
        self.gs00 = gridspec.GridSpecFromSubplotSpec(1,
                                                     3,
                                                     subplot_spec=self.gs0[0,
                                                                           0])
        self.conductance_ax = plt.Subplot(self.fig,
                                          self.gs00[0, 2],
                                          sharey=self.spectra_long_ax)
        self.current_ax = 0
        self.force_y_ax = plt.Subplot(self.fig,
                                      self.gs00[0, 1],
                                      sharey=self.spectra_long_ax)
        self.force_x_ax = 0
        self.displacement_ax = plt.Subplot(self.fig,
                                           self.gs00[0, 0],
                                           sharey=self.spectra_long_ax)
        # set axis formatter #
        self.formatter = plt.ScalarFormatter(useOffset=False, useMathText=True)
        self.formatter.set_scientific(True)
        self.formatter.set_powerlimits((-3, 3))
        # add subplots #
        self.add_spectra_subplot()
        self.add_conductance_subplot()
        self.add_force_subplot()
        self.add_displacement_subplot()
        #plt.tight_layout()
        self.gs0.tight_layout(self.fig, pad=0.25)  #, w_pad=0.1, h_pad=0.1)

        if self.data.analysed: self.annotate_analysis()  # annotate analysis
        self.save_figure()  # save figure
コード例 #24
0
 def on_units_change(self, evnt):
     """
     Event handler for change of x axis units events.
     """
     #get the matplotlib axes object from the subplot
     ax = self.subplot.get_mpl_axes()
     
     #change the axis labels and label formatting based on the choice of
     #units
     if evnt.GetString() == 'Degrees':
         ax.set_xlabel(r'$\theta$ (degrees)')
         ax.xaxis.set_major_formatter(plt.FuncFormatter(rad2deg))
     else:
         ax.set_xlabel(r'$\theta$ (radians)')
         ax.xaxis.set_major_formatter(plt.ScalarFormatter())
     
     #draw our changes in the display
     self.subplot.update()
コード例 #25
0
def plot_monthly_timeseries(spinup_run, var, location):
    """12-panel plot: timeseries of each month from all spinup years

    ARGS:
    spinup_run (CLM_spinup_analyzer): object of class
    CLM_spinup_analyzer describing the spinup run
    var (CLM_var): object of class CLM_var containing the data and
    metadata to be plotted
    location (Location): object of class Location describing the
    location of the data to be plotted
    """
    months = range(1, 13)
    nrows = np.int(np.ceil(len(months) / 2))
    fig, ax = plt.subplots(ncols=2, nrows=nrows, figsize=(8.5, 11))

    if var.depth is not None:
        depth_str = "{:0.2f} m".format(var.depth)
    else:
        depth_str = ""
    fig.text(0.5,
             0.95,
             '{} {} {} ({})'.format(location.name, var.varname_long, depth_str,
                                    var.units),
             verticalalignment='top',
             horizontalalignment='center',
             size='large')
    for i, this_month in enumerate(months):
        ax_idx = np.unravel_index(i, ax.shape)
        idx = np.array([
            this_file.find('{:02d}.nc'.format(this_month))
            for this_file in spinup_run.all_files
        ]) > 0
        ax[ax_idx].plot(var.data[idx, ...].squeeze())
        ax[ax_idx].set_ylabel(var.varname)
        ax[ax_idx].xaxis.set_major_formatter(plt.NullFormatter())
        ax[ax_idx].annotate(calendar.month_abbr[this_month],
                            xycoords='axes fraction',
                            xy=(0, 0),
                            bbox=dict(boxstyle="round", fc="0.8"))
    for this_col in range(2):
        ax[nrows - 1,
           this_col].xaxis.set_major_formatter(plt.ScalarFormatter())
        ax[nrows - 1, this_col].set_xlabel('year of spinup')
    return (fig, ax)
コード例 #26
0
def plot_nullclines(x,
                    y,
                    params=None,
                    which=["h", "i", "t"],
                    fit=False,
                    err=0,
                    legend=0,
                    title=None,
                    legLoc="best"):
    if (params == None and not fit):
        params = np.array(
            (defaultParams("h"), defaultParams("i"), defaultParams("t")))
    if (legend == 0 and not fit):
        legend = "Holling", "Ivlev", "Trigonometric"
    if (title == None and not fit):
        title = "Nullclines of the different systems for K = " + str(K)
    if (fit):
        fparams = params[0]
        dparams = params[1]
        title = "Nullclines: " + which[0] + '-Model fitted to ' + which[1] + "-Model K = " + str(K)\
                + "\n Data-Param: " + str(dparams) + "\n Fitted-Param: " + str(fparams) + " Error: " + str(err)
    ax = plt.subplot()
    ax.set_xscale('log')
    for axis in [ax.xaxis]:
        axis.set_major_formatter(plt.ScalarFormatter())
    i = 0
    for s in which:
        plt.plot(x, nullcl_x(x, params[i], s), color=color(s), zorder=1)
        plt.axvline(nullcl_y(x, params[i], s), color=color(s), zorder=2)
        equilibrium(x, params[i], s)
        i = i + 1
    if (legend != None):
        plt.legend(legend, loc=legLoc)
    plt.xticks([0.01, 0.05, 0.25])
    # plt.xticks([0.01,0.1,1,5,20],[0.01,0.1,1,5,20])
    plt.yticks([0, 0.2, 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.6, 1.8, 2],
               [0, 0.2, 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.6, 1.8, 2])
    plt.ylim(0, 1.1)
    plt.xlim(0.01, 0.25)
    plt.title(title, size=13)
    plt.ylabel("predator concentration, y ", fontsize=12)
    plt.xlabel("prey concentration, x", fontsize=12)
    plt.show()
コード例 #27
0
    def classical_plot_th(cls,Q,fff,tt,acc,yb,rd,n_scale):
        
        
        
        title_string_acc='Acceleration SDOF Response fn= '+ fff +' Hz   Q='+str(Q)
        title_string_rd='Rel Disp  SDOF Response fn= '+ fff +' Hz   Q='+str(Q)        
#
        for i in range(1,200):
            if(Q==float(i)):
                title_string_acc='Acceleration SDOF Response fn= '+ fff +' Hz   Q='+str(i)
                title_string_rd='Rel Disp  SDOF Response fn= '+ fff +' Hz   Q='+str(i)                    
                break
#
        plt.close(1)
        plt.figure(1)
        plt.plot(tt, acc, label="response")
        plt.plot(tt, yb, label="input")
        plt.xlabel('Time (sec)')
        plt.ylabel('Accel (G)')
        plt.grid(True)
        plt.title(title_string_acc)
        plt.legend(loc="upper right") 
        plt.draw()
#
        plt.close(2)
        plt.figure(2)
        plt.plot(tt, rd)
        plt.xlabel('Time (sec)')

        if(n_scale==0): 
            plt.ylabel('Rel Disp (in)')
        else:
            plt.ylabel('Rel Disp (mm)')            
        
        plt.grid(True)
        plt.title(title_string_rd)
        axes = plt.gca()
        myformatter = plt.ScalarFormatter(useMathText=True)
        myformatter.set_powerlimits((-3,3))
        axes.yaxis.set_major_formatter(myformatter)
        plt.draw()
        plt.show()
コード例 #28
0
def setup_figure_rc(width='regular', height=None, aspect=None, style='sans-serif', tex=False,
                    **kwargs):
    """
    Sets the default configuration for all future figures.

    Args:
        width (float, str): width of the figure in cm or a preset string
        height (float): height of the figure in cm
        aspect (float): aspect ratio of the figure (height/width)
        style (str): The font style to use in the figure
        tex (bool): Whether to use LaTeX to render the figure
        **kwargs: Arbitrary keyword arguments that are added to or override existing figure
            parameters.
    """
    fig_size = get_figure_size(width, height, aspect)
    fig_params = get_fig_params(style, tex, **kwargs)
    fig_params['figure.figsize'] = fig_size
    plt.rcParams.update(fig_params)
    formatter = plt.ScalarFormatter(useOffset=False, useMathText=True)
    formatter.set_scientific(True)
コード例 #29
0
def plot_energy_comparison(args):
    """Plot energy trajectories for comparison"""
    outfile = (args.out_params + '.png').format(param='cmp_free_energy',
                                                **args.__dict__)
    pyplot.figure()
    names = args.cmp_energy.keys()
    vals = -sp.array([args.cmp_energy[n] for n in names]).T
    print names
    print vals
    lines = pyplot.plot(vals)
    line_types = ['--', '-.', ':', '-', 'steps'] * 3
    [pyplot.setp(l, linestyle=t) for l, t in zip(lines, line_types)]
    pyplot.legend(names, loc='lower right')
    #pyplot.title('Free energy learning with %s' % args.approx)
    formatter = pyplot.ScalarFormatter(useMathText=True)
    formatter.set_scientific(True)
    formatter.set_powerlimits((-3, 3))
    pyplot.gca().yaxis.set_major_formatter(formatter)
    pyplot.xlabel("Iteration")
    pyplot.ylabel('-Free Energy')
    pyplot.savefig(os.path.join(args.out_dir, outfile))
    pyplot.close('all')
コード例 #30
0
ファイル: obs_dist.py プロジェクト: mbadenas/peerless
def make_plot(ax, x1, x2, rng, nbins, ticks):
    bins = np.exp(np.linspace(np.log(rng[0]), np.log(rng[1]), nbins))

    ax.hist([x2, x1],
            bins,
            histtype="stepfilled",
            stacked=False,
            color=[COLORS["MODEL_1"], COLORS["MODEL_2"]],
            alpha=0.1,
            lw=0)
    n, _, _ = ax.hist(x1, bins, histtype="step", color=COLORS["MODEL_2"], lw=2)
    ax.hist(x2,
            bins,
            histtype="step",
            color=COLORS["MODEL_1"],
            lw=2,
            hatch="/")
    ax.set_ylim(0, np.max(n) + 0.5)
    ax.set_xscale("log")
    ax.set_xticks(ticks)
    ax.get_xaxis().set_major_formatter(pl.ScalarFormatter())
    ax.set_xlim(rng)