Ejemplo n.º 1
0
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import ascii
import matplotlib.colors as mcolors

inputdir = "sample/girardi/"

# kepler data
data = np.load("sample/obs/nike_samples.npy")
xobso, yobso, feho = data[:, 0], data[:, 1], data[:, 2]
zs = feho  #np.concatenate((feh))
min_, max_ = zs.min(), zs.max()
n = mcolors.PowerNorm(vmin=min_, vmax=max_, gamma=1.8)

feh_limits = np.percentile(feho, np.linspace(0., 100., 7))

for j in range(len(feh_limits) - 1):
    idx = (feho >= feh_limits[j]) & (feho <= feh_limits[j + 1])
    xobs, yobs, feh = xobso[idx], yobso[idx], feho[idx]

    fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(12, 6), squeeze=False)
    axes = axes.reshape(-1)

    inputfiles = ["feh_m149.csv", "feh_p007.csv"]
    colors = ["purple", "red"]
    labels = ["[M/H]=-1.49", "[M/H]=+0.07"]
    for i in range(len(inputfiles)):
        data = ascii.read(inputdir + inputfiles[i])
        m, L, T = data["mass"], 10.**data["logL"], 10.**data["logT"]
        numax = m * L**-1. * (T / 5777)**3.5 * 3090
        dnu = m**0.5 * L**-0.75 * (T / 5777)**3.0 * 135.1
Ejemplo n.º 2
0
pcm = ax[1].pcolor(X, Y, Z, cmap='PuBu_r', shading='nearest')
fig.colorbar(pcm, ax=ax[1], extend='max')

###############################################################################
# PowerNorm: Here a power-law trend in X partially obscures a rectified
# sine wave in Y. We can remove the power law using a PowerNorm.

X, Y = np.mgrid[0:3:complex(0, N), 0:2:complex(0, N)]
Z1 = (1 + np.sin(Y * 10.)) * X**2

fig, ax = plt.subplots(2, 1)

pcm = ax[0].pcolormesh(X,
                       Y,
                       Z1,
                       norm=colors.PowerNorm(gamma=1. / 2.),
                       cmap='PuBu_r',
                       shading='nearest')
fig.colorbar(pcm, ax=ax[0], extend='max')

pcm = ax[1].pcolormesh(X, Y, Z1, cmap='PuBu_r', shading='nearest')
fig.colorbar(pcm, ax=ax[1], extend='max')

###############################################################################
# SymLogNorm: two humps, one negative and one positive, The positive
# with 5-times the amplitude. Linearly, you cannot see detail in the
# negative hump.  Here we logarithmically scale the positive and
# negative data separately.
#
# Note that colorbar labels do not come out looking very good.
Ejemplo n.º 3
0
    def plot_hist(self):
        print("Starting plot: histogram")

        # set up figure and its panels
        fig = plt.figure(figsize=(self.figwidth, self.figwidth))
        gs = GridSpec(4, 4)
        gs.update(left=0.1,
                  right=1.,
                  top=1.,
                  bottom=0.1,
                  hspace=0.0,
                  wspace=0.0)
        ax_t = plt.subplot(gs[0, :-1])
        ax_tco = plt.subplot(gs[1:, :-1], sharex=ax_t)
        ax_co = plt.subplot(gs[1:, -1], sharey=ax_tco)
        ax_t.spines['left'].set_visible(False)
        ax_t.spines['right'].set_visible(False)
        ax_t.spines['top'].set_visible(False)
        ax_co.spines['right'].set_visible(False)
        ax_co.spines['top'].set_visible(False)
        ax_co.spines['bottom'].set_visible(False)
        ax_t.tick_params(axis='both',
                         which='both',
                         bottom=True,
                         top=False,
                         left=False,
                         right=False,
                         labelbottom=False,
                         labeltop=False,
                         labelleft=False,
                         labelright=False)
        ax_co.tick_params(axis='both',
                          which='both',
                          bottom=False,
                          top=False,
                          left=True,
                          right=False,
                          labelbottom=False,
                          labeltop=False,
                          labelleft=False,
                          labelright=False)

        # plot 2D histogram as hexbin
        ax_tco.hexbin(self.data['temp'],
                      self.data['co2'],
                      gridsize=50,
                      cmap='Blues',
                      mincnt=1,
                      norm=colors.PowerNorm(gamma=0.5))

        # plot marginalizations
        hist_temp1 = ax_t.hist(self.data['temp'],
                               bins=50,
                               histtype='stepfilled',
                               color='black',
                               label='all time')
        hist_co21 = ax_co.hist(self.data['co2'],
                               bins=50,
                               histtype='stepfilled',
                               color='black',
                               label='all time',
                               orientation='horizontal')

        # get date of last week and last month
        today = datetime.now()
        last_week = today - timedelta(days=7)
        last_week = last_week.strftime('%Y-%m-%d %H:%M:%S')
        last_month = today - timedelta(days=30)
        last_month = last_month.strftime('%Y-%m-%d %H:%M:%S')
        last_3month = today - timedelta(days=90)
        last_3month = last_3month.strftime('%Y-%m-%d %H:%M:%S')

        # get data index of last week and last month
        self.idx_3month = 0
        self.idx_month = 0
        self.idx_week = 0
        for i in np.arange(len(self.data) - 1, 0, -1):
            if (self.data['date'][i] > last_week):
                self.idx_week = i
            if (self.data['date'][i] > last_month):
                self.idx_month = i
            if (self.data['date'][i] > last_3month):
                self.idx_3month = i
            else:
                break

        # plot historic marginalizations
        ax_t.hist(self.data['temp'][self.idx_3month:-1],
                  bins=hist_temp1[1],
                  histtype='stepfilled',
                  color='midnightblue',
                  label='last 3 months')
        ax_co.hist(self.data['co2'][self.idx_3month:-1],
                   bins=hist_co21[1],
                   histtype='stepfilled',
                   color='midnightblue',
                   orientation='horizontal',
                   label='last 3 months')
        ax_t.hist(self.data['temp'][self.idx_month:-1],
                  bins=hist_temp1[1],
                  histtype='stepfilled',
                  color='dodgerblue',
                  label='last month')
        ax_co.hist(self.data['co2'][self.idx_month:-1],
                   bins=hist_co21[1],
                   histtype='stepfilled',
                   color='dodgerblue',
                   orientation='horizontal',
                   label='last month')
        ax_t.hist(self.data['temp'][self.idx_week:-1],
                  bins=hist_temp1[1],
                  histtype='stepfilled',
                  color='aqua',
                  label='last week')
        ax_co.hist(self.data['co2'][self.idx_week:-1],
                   bins=hist_co21[1],
                   histtype='stepfilled',
                   color='aqua',
                   orientation='horizontal',
                   label='last week')

        # finish figure
        ax_t.set_title("Last updated " +
                       datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                       fontsize=self.fontsize)
        ax_tco.grid(True)
        ax_t.xaxis.grid(True)
        ax_co.yaxis.grid(True)
        ax_tco.set_xlabel(r"temperature [$^\circ$C]", fontsize=self.fontsize)
        ax_tco.set_ylabel(r"CO concentration [ppm]", fontsize=self.fontsize)
        ax_tco.tick_params(axis='both', which='major', labelsize=self.fontsize)
        ax_tco.set_xscale('linear')
        ax_tco.set_yscale('linear')
        ax_tco.set_xlim(self.templim)
        ax_tco.set_ylim(self.co2lim)
        ax_t.legend(loc='lower left',
                    numpoints=1,
                    bbox_to_anchor=(1.0, 0.0, 0.33, 1.0),
                    ncol=1,
                    mode="expand",
                    borderaxespad=0.,
                    fontsize=self.fontsize,
                    frameon=False)
        fig.savefig(os.path.join(self.plotdir, self.logname + '.hist.svg'),
                    bbox_inches='tight')

        # store figure for later use
        self.hist_plot = fig

        print("Finished plot: histogram")
Ejemplo n.º 4
0
fig, ((ax1, ax2), (ax3, ax4), (ax5, ax6)) = plt.subplots(3, 2)

fig.suptitle('PMT{}'.format(pmt))

ax1.hist(rec['blw'], bins=100, range=[0, 60], label='blw')
ax1.axvline(blw_cut, ymin=0, ymax=1)
ax1.set_yscale('log')
ax1.legend()

rec = rec[rec['blw'] < blw_cut]

ax2.hist2d(rec['height'],
           rec['dh3'],
           bins=[100, 100],
           range=[[0, 200], [0, 1.5]],
           norm=mcolors.PowerNorm(0.3))
ax2.axhline(dh3_cut, xmin=0, xmax=1, color='k')
ax2.axvline(height_cut, ymin=0, ymax=1, color='k')
ax2.axvline(spk_cut, ymin=0, ymax=1, color='k')

rec = rec[rec['dh3'] < dh3_cut]

h_heights, bins, pat = ax3.hist(rec['height'],
                                bins=100,
                                label='height',
                                range=[0, 500],
                                histtype='step')
heights = 0.5 * (bins[1:] + bins[:-1])
ax3.axvline(height_cut, ymin=0, ymax=1)
ax3.set_yscale('log')
ax3.legend()
Ejemplo n.º 5
0
              colors[0],
              capital=False)
        hist1(evalue1,
              200,
              data_label,
              'evalue_reciprocal',
              'log10(E-value)',
              labels[1],
              colors[1],
              capital=False)

        # 1.2.1.3 Scatters of E-value with other metrics
        plt.hist2d(df0['logevalue'],
                   df0['fqa'],
                   bins=50,
                   norm=mpl_colors.PowerNorm(0.3))
        plt.xlabel('log10(E-value)')
        plt.ylabel('Fraction of query aligned')
        plt.colorbar()
        plt.savefig(f'out/blast_{data_label}/hist2d_fqa-evalue_all.png')
        plt.close()

        plt.hist2d(df1['logevalue'],
                   df1['fqa'],
                   bins=50,
                   norm=mpl_colors.PowerNorm(0.3))
        plt.xlabel('log10(E-value)')
        plt.ylabel('Fraction of query aligned')
        plt.colorbar()
        plt.savefig(f'out/blast_{data_label}/hist2d_fqa-evalue_reciprocal.png')
        plt.close()
Ejemplo n.º 6
0
Colormap Normalizations Power
=============================

Demonstration of using norm to map colormaps onto data in non-linear ways.
"""

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors

N = 100
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]

'''
PowerNorm: Here a power-law trend in X partially obscures a rectified
sine wave in Y. We can remove the power law using a PowerNorm.
'''
X, Y = np.mgrid[0:3:complex(0, N), 0:2:complex(0, N)]
Z1 = (1 + np.sin(Y * 10.)) * X**2

fig, ax = plt.subplots(2, 1)

pcm = ax[0].pcolormesh(X, Y, Z1, norm=colors.PowerNorm(gamma=1./2.),
                       cmap='PuBu_r')
fig.colorbar(pcm, ax=ax[0], extend='max')

pcm = ax[1].pcolormesh(X, Y, Z1, cmap='PuBu_r')
fig.colorbar(pcm, ax=ax[1], extend='max')

plt.show()
Ejemplo n.º 7
0
        plt.xlim((-0.75, 1.75))
        plt.ylabel(f'Fraction of total {data_label} HSPs')
        plt.title(f'Fraction of {data_label} HSPs with zero and non-zero E-values')
        plt.legend(bbox_to_anchor=(0.5, -0.1875), loc='lower center', ncol=2)
        plt.subplots_adjust(bottom=0.15)
        plt.savefig(f'out/blast_{data_label}/bar_evalue_zero.png')
        plt.close()

        # 1.2.1.2 Histograms of non-zero E-values
        hist2_1([evalue0, evalue1], 200, data_label, 'evalue', 'log10(E-value)', labels, colors, capital=False)
        hist2_2([evalue0, evalue1], 200, data_label, 'evalue', 'log10(E-value)', labels, colors, capital=False)
        hist1(evalue0, 200, data_label, 'evalue_all', 'log10(E-value)', labels[0], colors[0], capital=False)
        hist1(evalue1, 200, data_label, 'evalue_reciprocal', 'log10(E-value)', labels[1], colors[1], capital=False)

        # 1.2.1.3 Scatters of E-value with other metrics
        plt.hist2d(df0['logevalue'], df0['fqa'], bins=50, norm=mpl_colors.PowerNorm(0.3))
        plt.xlabel('log10(E-value)')
        plt.ylabel('Fraction of query aligned')
        plt.colorbar()
        plt.savefig(f'out/blast_{data_label}/hist2d_fqa-evalue_all.png')
        plt.close()

        plt.hist2d(df1['logevalue'], df1['fqa'], bins=50, norm=mpl_colors.PowerNorm(0.3))
        plt.xlabel('log10(E-value)')
        plt.ylabel('Fraction of query aligned')
        plt.colorbar()
        plt.savefig(f'out/blast_{data_label}/hist2d_fqa-evalue_reciprocal.png')
        plt.close()

        g0 = df0.groupby('logevalue')
        x = g0['nqa'].min()
Ejemplo n.º 8
0
def traj_scatter(data,
                 lons,
                 lats,
                 hymap,
                 zorder=19,
                 colormap=plt.cm.viridis,
                 edgecolor='none',
                 size=25,
                 sizedata=None,
                 cnormalize=None,
                 snormalize=None,
                 vmin=None,
                 vmax=None,
                 levels=11,
                 suppress_printmsg=False,
                 **kwargs):
    """
    Scatter-plot of ``Trajectory``, ``TrajectoryGroup``, or ``Cluster`` data.

    Parameters
    ----------
    data : 1D ndarray of floats, ints
        The information to plot as color change.
    lons : 1D ndarray of floats, ints
        X-coordinates of ``data`` in decimal degrees
    lats : 1D ndarray of floats, ints
        Y-coordinates of ``data`` in decimal degrees
    hymap : ``Basemap`` instance
        Any ``Basemap`` instance.  For easy map creation, see ``MapDesign``
        class
    zorder : int
        Default 19.  Data zorder.
    colormap : colormap
        Default ``plt.cm.viridis``.  Any ``matplotlib`` colormap.
    edgecolor : string, tuple
        Default 'none'.  Any ``matplotlib``-accepted color
    size : int
        Default 25.  Point size of data unless ``sizedata`` specified.  Then,
        will be multiplied with ``sizedata``.
    sizedata : 1D ndarray of floats
        Default ``None``.  The data to plot as a change in marker size.
    cnormalize : string or float
        Default ``None``.  [None|'boundary'|'log'|'ln'|'sqrt'|float]
        Normalization of color scale.  If 'boundary', will create a discrete
        color map with ``levels`` number of colors.  For other norms, colorbar
        ticklabels will be updated with 'log' but not 'ln', 'sqrt', because
        no corresponding ``matplotlib colors Normalize`` classes are available.
        If a float is provided, a ``PowerNorm`` will be performed.
    snormalize : string
        Default ``None``.  [None|'log'|'ln'|'sqrt'].  Similar to cnormalize,
        except 'boundary' not available and does not use ``Normalize``.
    vmin : int or float
        Default ``None``.  Used to scale/normalize ``data``.
        If ``None``, then set to ``data`` min
    vmax : int or float
        Default ``None``.  Used to scale/normalize ``data``.
        If ``None``, then set to ``data`` max
    levels : int
        Only used in BoundaryNorm
    **kwargs
        passed to ``Basemap.scatter()`` and ``Axes.scatter()``

    Returns
    -------
    cm : ``matplotlib PathCollection`` instance
        Mappable for use in creating colorbars.  Colorbars may be created
        in ``PySPLIT`` using ``make_cbar()`` or ``make_cax_cbar()``

    """
    # cnormalize = str.lower(cnormalize)
    norm = None
    msg = ('Use `cbar.ax.set_yticklabels()` ' +
           'or cbar.ax.set_xticklabels()` to change tick labels')

    transform_dict = {'sqrt': np.sqrt, 'log': np.log10, 'ln': np.log}

    if cnormalize is 'boundary':
        if vmin is None:
            vmin = data.min()
        if vmax is None:
            vmax = data.max()
        bounds = np.linspace(vmin, vmax, levels)
        norm = clr.BoundaryNorm(bounds, colormap.N)
    elif cnormalize is 'log':
        norm = clr.LogNorm(vmin=vmin, vmax=vmax)
    elif cnormalize is 'ln':
        data = np.log(data)
        if not suppress_printmsg:
            print(msg, '\nnatural log normalization')
    elif cnormalize is 'sqrt':
        data = np.sqrt(data)
        if not suppress_printmsg:
            print(msg, '\nsqrt normalization')
    elif cnormalize is not None:
        try:
            norm = clr.PowerNorm(cnormalize, vmin=vmin, vmax=vmax)
        except:
            pass

    if sizedata is not None:
        if snormalize is not None:
            sizedata = transform_dict[snormalize](sizedata)
        size = sizedata * size

    cm = hymap.scatter(lons,
                       lats,
                       c=data,
                       s=size,
                       cmap=colormap,
                       vmin=vmin,
                       vmax=vmax,
                       zorder=zorder,
                       edgecolor=edgecolor,
                       norm=norm,
                       latlon=True,
                       **kwargs)

    return cm
Ejemplo n.º 9
0
# %%
result = match_template(im_full, im_crop)
ij = np.unravel_index(np.argmax(result), result.shape)
x, y = ij[::-1]

# %%
result.max()

# %%
fig = plt.figure(figsize=(8, 3))
ax1 = plt.subplot(1, 4, 1)
ax2 = plt.subplot(1, 4, 2)
ax4 = plt.subplot(1, 4, 3)
ax3 = plt.subplot(1, 4, 4, sharex=ax2, sharey=ax2)

ax1.imshow(im_crop, cmap=plt.cm.gray,norm=colors.PowerNorm(gamma=1/2))
ax1.set_axis_off()
ax1.set_title('template')

ax2.imshow(im_full, cmap=plt.cm.gray, norm=colors.PowerNorm(gamma=1/2))
#ax2.set_axis_off()
ax2.set_title('image')
# highlight matched region
hcoin, wcoin = im_crop.shape
rect = plt.Rectangle((x, y), wcoin, hcoin, edgecolor='r', facecolor='none')
ax2.add_patch(rect)


ax4.imshow(im_full[y:(y+hcoin), x:(x+wcoin)], cmap=plt.cm.gray, norm=colors.PowerNorm(gamma=1/2))
ax4.set_axis_off()
ax4.set_title('image')
Ejemplo n.º 10
0
    a = np.array(
        struct.unpack(
            (etype + '{}' + dtype).format(int(fin.tell() / sizeofdata)), raw))
    a = a.reshape((nx2, nx1))
    fin.close()

    # do translation
    x1t = np.remainder(x1e - Utrans * t, scale)
    for j in range(nx2):
        y1e[0:nx1] = a[j, :]
        y1e[nx1] = a[j, 0]
        f = interpolate.interp1d(x1e, y1e)
        a[j, :] = f(x1t)[0:nx1]

    fig = plt.figure(figsize=[x1[-1], x2[-1]])
    #    plt.pcolormesh(x1,x2,a,vmin=-0.537284965,vmax=0.537284965)
    plt.pcolormesh(x1,
                   x2,
                   a,
                   cmap='magma_r',
                   norm=colors.PowerNorm(0.5, np.amin(a), 6.0),
                   shading='auto')
    # plt.imshow(a,origin='lower',cmap='magma_r',norm=colors.PowerNorm(0.5,np.amin(a),6.0))
    plt.axis('equal')
    plt.gca().set_axis_off()

    plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
    plt.margins(0, 0)
    plt.savefig("{}.jpg".format(file), dpi=1920. / x1[-1])
    plt.close(fig)
Ejemplo n.º 11
0
def data_density_filter(x,
                        y,
                        conv_matrix=None,
                        min_count=5,
                        return_figures=True):
    """
    Use the 2D density cloud of observations to find outliers for any variables

    The data density filter needs tuning to work well.
    This uses convolution to create the density cloud - you can specify
    the exact convolution matrix, or its shape

    Parameters
    ----------
    x : np.array / pd.Series, shape=[n, ]
        e.g. temperature
    y : np.array / pd.Series, shape=[n, ]
        e.g. salinity
    conv_matrix : int, list, np.array, optional
        int = size of the isotropic round convolution window.
        [int, int] = anisotropic (oval) convoltion window.
        2d array is a weighted convolution window;
        rectangle = np.ones([int, int]);
        more advanced anisotropic windows can also be created
    min_count : int, default=5, optional
        masks the 2d histogram counts smaller than this limit when performing
        the convolution
    return_figures : bool, default=True, optional
        returns figures of the data plotted for blob detection...

    Returns
    -------
    mask : np.array, shape=[n, ]
        a mask that returns only values
    figure :
        only returned if return_figure is True

    """
    from numpy import array, c_, inf, isnan, linspace, where
    from pandas import Series, cut
    from scipy.signal import convolve2d

    def gaussian_kernel(*shape):
        """
        Returns a 2D array with gaussian values to be used in the blob_outliers
        detection function. Can be anisotripic (oblong). Scaling is determined
        automatically.

        Parameters
        ----------
        shape : int, int
            if one integer is passed the kernel will be isotropic
            if two integers are passed the kernel will be anisotropic

        Returns
        -------
        array  (float)
            The 2D representation of the kernel
        """
        from matplotlib.cbook import flatten
        from numpy import exp, mgrid

        # make shape a list regardless of input
        shape = [int(a // 2) for a in flatten([shape])]
        # anisotropic if len(2) else isotropic
        if len(shape) == 1:
            sx, sy = shape[0], shape[0]
        elif len(shape) == 2:
            sx, sy = shape

        # create the x and y grid
        x, y = mgrid[-sx:sx + 1, -sy:sy + 1]
        sigma = [sx / 8, sy / 8]  # sigma scaled by shape
        c = tuple([sx, sy])  # centre index of x and y
        g = 1 * exp(-((x - x[c])**2 / (2 * sigma[0])**2 + (y - y[c])**2 /
                      (2 * sigma[1])**2))
        return g

    # turning input into pandas.Series
    x = Series(x, name="X" if not isinstance(x, Series) else x.name)
    y = Series(y, name="Y" if not isinstance(y, Series) else y.name)

    ###############
    #   BINNING   #
    ###############
    # create bins for the data - equal bins
    xbins = linspace(x.min(), x.max(), 250)
    ybins = linspace(y.min(), y.max(), 250)
    # binning the data with pandas. This is quick to find outliers at the end
    xcut = cut(x, xbins, labels=c_[xbins[:-1], xbins[1:]].mean(1), right=False)
    ycut = cut(y, ybins, labels=c_[ybins[:-1], ybins[1:]].mean(1), right=False)

    # binning the data and returning as a 2D array (pandas.DataFrame)
    count = x.groupby([xcut, ycut]).count()
    count.name = "count"  # to avoid an error when unstacking
    count = count.unstack()
    count = count.sort_index().sort_index(axis=1)

    ###################
    #   CONVOLUTION   #
    ###################
    # make convolution matrix if not given
    if conv_matrix is None:
        conv_matrix = (gaussian_kernel(21) > 1e-5).astype(int)
    elif isinstance(conv_matrix, (list, int, float)):
        conv_matrix = (gaussian_kernel(conv_matrix) > 1e-5).astype(int)
    else:
        ndim = array(conv_matrix).ndim
        if ndim != 2:
            raise UserWarning("conv_matrix must have 2 dimensions")
    # An array with which the convolution is done
    # use a threshold to mask out bins with low counts
    # thus only dense regions of data are considered
    count0 = count.fillna(0).values
    count0[count0 < min_count] = 0
    # 2d convolution with the input matrix
    convolved_count = convolve2d(count0, conv_matrix, mode="same")
    outliers = (convolved_count == 0) & ~isnan(count)

    cols = count.index
    rows = count.columns

    ########################################
    #   FINDING OUTLIERS AND CREATE MASK   #
    ########################################
    # find indicies of of the where there is no convolution,
    # but there are data. Then get the x and y values of these
    # points. Turn these into pairs for pandas multi-indexing.
    i, j = where(outliers)
    xi = cols[i].values
    yj = rows[j].values
    ij = list(zip(xi, yj))
    # Create a pandas dataframe with the pd.cut data as indicies
    # with a column for a numerical index.
    if len(ij) > 0:
        idx = x.to_frame().reset_index().drop(x.name, axis=1)
        idx = idx.set_axis([xcut, ycut], inplace=False)
        idx = idx.loc[ij]["index"].values
    else:
        idx = None
    # create a placeholder mask and fill outliers with True
    mask = (x > inf).values
    mask[idx] = True

    ###############
    #   FIGURES   #
    ###############
    if return_figures:
        from matplotlib import cm, colors
        from matplotlib import pyplot as plt
        from numpy import ma, r_

        # x and y plotting coordinates
        xp = cols.values.astype(float)
        yp = rows.values.astype(float)
        # plotting variables a, b, c
        a = ma.masked_invalid(count.T, 0)
        b = convolved_count.T
        c = ma.masked_where(a.mask, ~outliers.T)

        # create the figure
        fig, ax = plt.subplots(1, 2, figsize=[10, 5], dpi=90, sharey=True)
        # properties for the pcolormesh and contours
        pn = colors.PowerNorm(0.3)
        mesh_props = dict(cmap=cm.Spectral_r, norm=pn)
        # create the pcolormesh plots
        im = (
            ax[0].pcolormesh(xp, yp, a, vmax=a.max() / 2, **mesh_props),
            ax[1].pcolormesh(xp, yp, c, vmin=0, vmax=1),
        )
        ax[1].contour(xp,
                      yp,
                      b,
                      levels=[0.5],
                      linestyles="-",
                      colors="r",
                      linewidths=2)

        # change figure parameters
        ax[0].set_title("Histogram of data (min_count = {})".format(min_count))
        ax[1].set_title(
            "{} Outliers found using\n{} convolution decision boundary".format(
                mask.sum(), str(conv_matrix.shape)))
        ax[0].set_xticks([])
        ax[0].set_ylabel(y.name)
        ax[1].set_xlabel(x.name)

        # tight layout before creating the axes for pcolomesh plots
        fig.tight_layout()

        # make colorbar axes based on axes [0, 1]
        p = ax[0].get_position()
        cax = fig.add_axes([p.x0, p.y0 - 0.05, p.width, 0.04])
        cb = plt.colorbar(im[0], cax=cax, orientation="horizontal")
        cb.set_label("Count")
        cb.set_ticks([1, 2, 3, 5, 10, 30, 80, 200])
        # plot the min_count on the colorbar
        cx = pn(r_[cb.get_clim(), min_count])[-1]
        cb.ax.plot(cx, 0, marker="^", color="k", markersize=8)
        cb.ax.plot(cx, 1, marker="v", color="k", markersize=8)
        return mask, fig

    return mask
Ejemplo n.º 12
0
def pcolormesh(variable,x=None,y=None,projection=None,cmap="viridis",
         shading='Gouraud',norm=None,vmin=None,vmax=None,invertx=False,
         inverty=False,linthresh=1.0e-3,linscale=1.0,gamma=1.0,bounds=None,
         symmetric=False,ncolors=256,**kwargs):
    
    if symmetric==True: #assumes zero is the midpoint
        if vmin and vmax:
            vmin=-max(abs(vmin),abs(vmax))
            vmax= max(abs(vmin),abs(vmax))
        elif vmin:
            vmax=-vmin
        elif vmax:
            vmin=-vmax
        else:
            vmax = np.nanmax(abs(variable))
            vmin = -vmax
            
    elif type(symmetric)!=type(None) and type(symmetric)!=type(False): # a midpoint is specified
        if vmin and vmax:
            vmin = symmetric - max(abs(vmin-symmetric),abs(vmax-symmetric))
            vmax = 2*symmetric - vmin
        elif vmin:
            vmax = 2*symmetric - vmin
        elif vmax:
            vmin = 2*symmetric - vmax
        else:
            vmax = symmetric + np.nanmax(abs(variable-symmetric))
            vmin = 2*symmetric - vmax
    
    else:
        if not vmin:
            vmin = np.nanmin(variable)
        if not vmax:
            vmax = np.nanmax(variable)
    
    if norm=="Log":
        normalization=colors.LogNorm(vmin=vmin,vmax=vmax)
    elif norm=="SymLog":
        normalization=colors.SymLogNorm(vmin=vmin,vmax=vmax,linthresh=linthresh,linscale=linscale)
    elif norm=="PowerLog":
        normalization=colors.PowerNorm(gamma,vmin=vmin,vmax=vmax)
    elif norm=="Bounds":
        if type(bounds)==type(None):
            bounds = np.linspace(vmin,vmax,num=ncolors+1)
        normalization=colors.BoundaryNorm(bounds,ncolors)
    else:
        normalization=colors.Normalize(vmin=vmin,vmax=vmax)
    
    if len(variable.shape)>2:
        variable=make2d(variable)
    
    if type(x)==type(None) or type(y)==type(None):
        im = plt.pcolormesh(variable,norm=normalization,shading=shading,cmap=cmap)
        if inverty:
            plt.gca().invert_yaxis()
        if invertx:
            plt.gca().invert_xaxis()
        return im
    
    if projection:
        
        if len(x.shape)==1:
            x,y = np.meshgrid(x,y)
            x = wrap2d(x)
            x[:,-1] = x[:,0]+360.0
            y = wrap2d(y)
        variable=wrap2d(variable)
        m=_xBasemap(projection=projection,**kwargs)
        im=m.pcolormesh(x,y,variable,cmap=cmap,shading=shading,norm=normalization,latlon=True)
        return m,im
    
    im=plt.pcolormesh(x,y,variable,cmap=cmap,shading=shading,norm=normalization,**kwargs)
    if inverty:
        plt.gca().invert_yaxis()
    if invertx:
        plt.gca().invert_xaxis()
    return im
Ejemplo n.º 13
0
from matplotlib import pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
from numpy.random import multivariate_normal

data = np.vstack([
    multivariate_normal([10, 10], [[3, 2], [2, 3]], size=100000),
    multivariate_normal([30, 20], [[2, 3], [1, 3]], size=1000)
])

gammas = [0.8, 0.5, 0.3]

fig, axes = plt.subplots(nrows=2, ncols=2)

axes[0, 0].set_title('Linear normalization')
axes[0, 0].hist2d(data[:, 0], data[:, 1], bins=100)

for ax, gamma in zip(axes.flat[1:], gammas):
    ax.set_title('Power law $(\gamma=%1.1f)$' % gamma)
    ax.hist2d(data[:, 0], data[:, 1],
              bins=100, norm=mcolors.PowerNorm(gamma))

fig.tight_layout()

plt.show()
Ejemplo n.º 14
0
lat.set_axislabel('Galactic Latitude (deg)', minpad=1., size=fsize)
lon.set_ticks(spacing=0.2 * u.deg, color='black', exclude_overlapping=True, size=5, width=1.1)
lat.set_ticks(spacing=0.2 * u.deg, color='black', exclude_overlapping=True, size=5, width=1.1)
lon.set_ticklabel(size=fsize)
lat.set_ticklabel(size=fsize)
lon.display_minor_ticks(True)
lat.display_minor_ticks(True)
lon.set_minor_frequency(4)
lat.set_minor_frequency(4)
lon.set_major_formatter('d.d')
lat.set_major_formatter('d.d')

minval = np.nanmin(data)
maxval = np.nanmax(data)

im = ax.imshow(data, interpolation='nearest', cmap='Blues_r', origin='lower', norm=colors.PowerNorm(gamma=1./4.0))

d = Dendrogram.load_from(dendrofile)

leaf_mask = np.zeros(data.shape)
count=0
for leaf in d.leaves:
    foundleaf = (leaf.idx == catalog['index'].data)
    if np.any(foundleaf):
        arr = leaf.get_mask()
        leaf_mask[(arr==True)] = table['index'].data[count]
        count+=1

ax.contour(leaf_mask, transform=ax.get_transform(wcs), cmap='Reds', linewidths=0.25)

plt.savefig(figure_name, dpi=800, bbox_inches='tight')
Ejemplo n.º 15
0
from matplotlib import pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
from numpy.random import multivariate_normal

data = np.vstack([
    multivariate_normal([10, 10], [[3, 2], [2, 3]], size=100000),
    multivariate_normal([30, 20], [[2, 3], [1, 3]], size=1000)
])

gammas = [0.8, 0.5, 0.3]
xgrid = np.floor((len(gammas) + 1.) / 2)
ygrid = np.ceil((len(gammas) + 1.) / 2)

plt.subplot(xgrid, ygrid, 1)
plt.title('Linear normalization')
plt.hist2d(data[:, 0], data[:, 1], bins=100)

for i, gamma in enumerate(gammas):
    plt.subplot(xgrid, ygrid, i + 2)
    plt.title('Power law\n$(\gamma=%1.1f)$' % gamma)
    plt.hist2d(data[:, 0], data[:, 1], bins=100, norm=mcolors.PowerNorm(gamma))

plt.tight_layout()

plt.show()
# Create a figure with 2 plot areas
fig, axes = plt.subplots(ncols=2, nrows=1, figsize=(21, 5))

# Everything sarts with a Scatterplot
axes[0].set_title('Scatterplot')
axes[0].plot(x, y, 'ko')

### 2D Histogram ###
nbins = 150  # number of bins, adjustable
gmma = 0.3  # Gamma, changes the normalization for datapnts in 2D Histogram
# Smaller values reveal the lighter tracks where less time was
# spent; see:
# https://matplotlib.org/gallery/scales/power_norm.html#sphx-glr-gallery-scales-power-norm-py
axes[1].set_title('2D Histogram')
plt.xlabel("Distance, Pixels")

counts, xedges, yedges, im = axes[1].hist2d(x,
                                            y,
                                            bins=nbins,
                                            cmap=plt.cm.YlGnBu_r,
                                            norm=mcolors.PowerNorm(gmma))
# hist2d gives multiple things; im needed for colorbar
cbar = plt.colorbar(im, ax=axes[1])
#cbar.mappable.set_clim(0,100) # comment this out to set cbar to auto range
# or chnage to alter the range of the colorbar
cbar.ax.set_yticklabels(['Never', '', '', '', 'Most Often'])
# Change labels above to alter labels on colorbar

### Save Figure ###
# Make sure to name it something identifyable
plt.savefig("Testing_2DHistogram.pdf")
Ejemplo n.º 17
0
#Coloring in final graph: Green = low, Red = high
cground = colors.LinearSegmentedColormap.from_list('my_colormap',
                                                   ['green', 'yellow', 'red'],
                                                   256)
cwater = colors.LinearSegmentedColormap.from_list(
    'my_colormap', [[0, 1, 1, 0], [0, 1, 1, 1], 'blue'])
# tell imshow about color areaMap so that only set colors are used
vectGroundFunc = np.vectorize(attrgetter('groundLevel'))
groundMap = plot.imshow(vectGroundFunc(areaMap), cmap=cground, origin='lower')

vectWaterFunc = np.vectorize(attrgetter('waterLevel'))
vectIncWaterFunc = np.vectorize(attrgetter('incomingWater'))
waterMap = plot.imshow(vectWaterFunc(areaMap),
                       cmap=cwater,
                       origin='lower',
                       norm=colors.PowerNorm(gamma=gammaLevel * 1.0,
                                             vmax=colourBarvmax / 1000.0),
                       animated=True)

colourbar = fig.colorbar(waterMap, ax=ax, extend='max')

#show areaMap and update in loop

print("Starting simluation")
print("Total Water = " +
      str(np.sum(vectWaterFunc(areaMap)) + np.sum(rainFall)))


def runSimulation(self):

    for (x, y), movingWater in np.ndenumerate(areaMap):
        if not (movingWater.visted):
Ejemplo n.º 18
0
    if i != 0:
        h, xedges, yedges, img = ax2.hist2d(x,
                                            y,
                                            bins=[bins, bins],
                                            range=[[-xlim, xlim],
                                                   [-xlim, xlim]],
                                            cmap=cmap,
                                            density=True)
    else:
        h, xedges, yedges, img = ax2.hist2d(x,
                                            y,
                                            bins=[bins - 15, bins - 15],
                                            range=[[-xlim, xlim],
                                                   [-xlim, xlim]],
                                            cmap=cmap,
                                            norm=mcolors.PowerNorm(0.6),
                                            density=True)
    # colorbar: uncomment this section for individual colorbar
    # norm = colors.Normalize(vmin=np.min(h), vmax=np.max(h))
    # cb = fig2.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax = ax2)
    # cb.set_label('Probability', fontsize = fontsize, rotation = -90, horizontalalignment = 'center', verticalalignment = 'bottom')
    sfntmp = sfname[i]
    np.savetxt(sfntmp + "x.txt", xedges)
    np.savetxt(sfntmp + "y.txt", yedges)
    np.savetxt(sfntmp + "h.txt", h)
    # axes label
    ax2.set_xlabel(r'Position($\mu$m)', fontsize=fontsize)
    ax2.set_ylabel(r'Position($\mu$m)', fontsize=fontsize)

    # tick location and tick label
    xtick_temp = np.arange(0, xlim, step=6.25)
Ejemplo n.º 19
0
def beamvstime(configfile,
               maindir,
               params=['Ne'],
               filetemplate='AltvTime',
               suptitle='Alt vs Time'):
    """ This will create a altitude time image for the data for ionocontainer files
        that are in sphereical coordinates.
        Inputs
            Times - A list of times that will be plotted.
            configfile - The INI file with the simulation parameters that will be useds.
            maindir - The directory the images will be saved in.
            params - List of Parameter names that will be ploted. These need to match
                in the ionocontainer names.
            filetemplate - The first part of a the file names.
            suptitle - The supertitle for the plots.
    """
    sns.set_style("whitegrid")
    sns.set_context("notebook")
    #    rc('text', usetex=True)
    (sensdict, simparams) = readconfigfile(configfile)

    paramslower = [ip.lower() for ip in params]
    Np = len(params)
    maindir = Path(maindir)
    inputfile = str(maindir.joinpath('Fitted', 'fitteddata.h5'))

    Ionofit = IonoContainer.readh5(inputfile)
    times = Ionofit.Time_Vector
    Nt = len(times)
    dataloc = Ionofit.Sphere_Coords
    pnames = Ionofit.Param_Names
    pnameslower = sp.array([ip.lower() for ip in pnames.flatten()])
    p2fit = [
        sp.argwhere(ip == pnameslower)[0][0] if ip in pnameslower else None
        for ip in paramslower
    ]

    angles = dataloc[:, 1:]
    b = np.ascontiguousarray(angles).view(
        np.dtype((np.void, angles.dtype.itemsize * angles.shape[1])))
    _, idx, invidx = np.unique(b, return_index=True, return_inverse=True)

    beamlist = angles[idx]

    Nb = beamlist.shape[0]

    newfig = True
    imcount = 0
    ifig = -1
    for iparam in range(Np):
        for ibeam in range(Nb):

            if newfig:
                (figmplf, axmat) = plt.subplots(3,
                                                3,
                                                figsize=(20, 15),
                                                facecolor='w',
                                                sharex=True,
                                                sharey=True)
                axvec = axmat.flatten()
                newfig = False
                ix = 0
                ifig += 1

            ax = axvec[ix]

            curbeam = beamlist[ibeam]
            curparm = paramslower[iparam]
            if curparm == 'nepow':
                curparm = 'ne'

            indxkep = np.argwhere(invidx == ibeam)[:, 0]
            rng_fit = dataloc[indxkep, 0]
            rngargs = np.argsort(rng_fit)
            rng_fit = rng_fit[rngargs]
            alt_fit = rng_fit * sp.sin(curbeam[1] * sp.pi / 180.)
            curfit = Ionofit.Param_List[indxkep, :, p2fit[iparam]]

            curfit = curfit[rngargs]
            Tmat, Amat = np.meshgrid(times[:, 0], alt_fit)
            image = ax.pcolor(Tmat, Amat, curfit.real, cmap='viridis')
            if curparm == 'ne':
                image.set_norm(colors.LogNorm(vmin=1e9, vmax=5e12))
                cbarstr = params[iparam] + ' m-3'
            else:
                image.set_norm(colors.PowerNorm(gamma=1., vmin=500, vmax=3e3))
                cbarstr = params[iparam] + ' K'

            if ix > 5:
                ax.set_xlabel("Time in s")
            if sp.mod(ix, 3) == 0:
                ax.set_ylabel('Alt km')
            ax.set_title('{0} vs Altitude, Az: {1}$^o$ El: {2}$^o$'.format(
                params[iparam], *curbeam))
            imcount = imcount + 1

            ix += 1
            if ix == 9 or ibeam + 1 == Nb:
                cbar_ax = figmplf.add_axes([.91, .3, .06, .4])
                cbar = plt.colorbar(image, cax=cbar_ax)
                cbar.set_label(cbarstr)
                figmplf.suptitle(suptitle, fontsize=20)
                figmplf.tight_layout(rect=[0, .05, .9, .95])
                fname = filetemplate + '_{0:0>3}.png'.format(ifig)
                plt.savefig(fname)
                plt.close(figmplf)
                newfig = True
Ejemplo n.º 20
0
    'color': '0.8'
}
cfont_titl = {
    'fontname': 'Open Sans',
    'fontweight': 'light',
    'fontsize': int(14. * fontr),
    'color': color_top
}

# Colormaps for fields:
pal_fld = cp.chose_colmap(cpal_fld)
if l_log_field:
    norm_fld = colors.LogNorm(vmin=tmin, vmax=tmax, clip=False)
elif l_pow_field:
    norm_fld = colors.PowerNorm(gamma=pow_field,
                                vmin=tmin,
                                vmax=tmax,
                                clip=False)
else:
    norm_fld = colors.Normalize(vmin=tmin, vmax=tmax, clip=False)

if l_show_lsm or l_add_topo_land:
    if l_add_topo_land:
        xtopo = nmp.log10(xtopo + rof_log)
        pal_lsm = cp.chose_colmap('gray_r')
        #norm_lsm = colors.Normalize(vmin = nmp.log10(min(-100.+rof_dpt/3.,0.) + rof_log), vmax = nmp.log10(4000.+rof_dpt + rof_log), clip = False)
        norm_lsm = colors.Normalize(vmin=nmp.log10(-100. + rof_log),
                                    vmax=nmp.log10(4000. + rof_dpt + rof_log),
                                    clip=False)
    else:
        pal_lsm = cp.chose_colmap('land_dark')
        norm_lsm = colors.Normalize(vmin=0., vmax=1., clip=False)
Ejemplo n.º 21
0
    def draw_figures(self, history, color_p_axis=False):
        from matplotlib import colors

        color = 'black'
        fontsize = self.font_size
        markersize = fontsize * 1.5
        beachballsize_small = markersize * 0.5
        beachball_type = self.beachball_type

        problem = history.problem
        sp = SectionPlot(config=self)
        self._to_be_closed.append(sp)

        fig = sp.fig
        axes_en = sp.axes_xy
        axes_dn = sp.axes_zy
        axes_ed = sp.axes_xz

        bounds = problem.get_combined_bounds()

        models = history.get_sorted_primary_models()[::-1]

        iorder = num.arange(history.nmodels)

        for parname, set_label, set_lim in [
                ['east_shift', sp.set_xlabel, sp.set_xlim],
                ['north_shift', sp.set_ylabel, sp.set_ylim],
                ['depth', sp.set_zlabel, sp.set_zlim]]:

            ipar = problem.name_to_index(parname)
            par = problem.combined[ipar]
            set_label(par.get_label())
            xmin, xmax = fixlim(*par.scaled(bounds[ipar]))
            set_lim(xmin, xmax)

        if 'volume_change' in problem.parameter_names:
            volumes = models[:, problem.name_to_index('volume_change')]
            volume_max = volumes.max()
            volume_min = volumes.min()

        def scale_size(source):
            if not hasattr(source, 'volume_change'):
                return beachballsize_small

            volume_change = source.volume_change
            fac = (volume_change - volume_min) / (volume_max - volume_min)
            return markersize * .25 + markersize * .5 * fac

        for axes, xparname, yparname in [
                (axes_en, 'east_shift', 'north_shift'),
                (axes_dn, 'depth', 'north_shift'),
                (axes_ed, 'east_shift', 'depth')]:

            ixpar = problem.name_to_index(xparname)
            iypar = problem.name_to_index(yparname)

            xpar = problem.combined[ixpar]
            ypar = problem.combined[iypar]

            xmin, xmax = fixlim(*xpar.scaled(bounds[ixpar]))
            ymin, ymax = fixlim(*ypar.scaled(bounds[iypar]))

            try:
                axes.set_facecolor(mpl_color('aluminium1'))
            except AttributeError:
                axes.patch.set_facecolor(mpl_color('aluminium1'))

            rect = patches.Rectangle(
                (xmin, ymin), xmax-xmin, ymax-ymin,
                facecolor=mpl_color('white'),
                edgecolor=mpl_color('aluminium2'))

            axes.add_patch(rect)

            # fxs = xpar.scaled(problem.extract(models, ixpar))
            # fys = ypar.scaled(problem.extract(models, iypar))

            # axes.set_xlim(*fixlim(num.min(fxs), num.max(fxs)))
            # axes.set_ylim(*fixlim(num.min(fys), num.max(fys)))

            cmap = cm.ScalarMappable(
                norm=colors.PowerNorm(
                    gamma=self.normalisation_gamma,
                    vmin=iorder.min(),
                    vmax=iorder.max()),

                cmap=plt.get_cmap('coolwarm'))

            for ix, x in enumerate(models):

                source = problem.get_source(x)
                mt = source.pyrocko_moment_tensor(
                    store=problem.get_gf_store(problem.targets[0]),
                    target=problem.targets[0])
                fx = problem.extract(x, ixpar)
                fy = problem.extract(x, iypar)
                sx, sy = xpar.scaled(fx), ypar.scaled(fy)

                # TODO: Add rotation in cross-sections
                color = cmap.to_rgba(iorder[ix])

                alpha = (iorder[ix] - iorder.min()) / \
                    float(iorder.max() - iorder.min())
                alpha = alpha**self.normalisation_gamma

                try:
                    beachball.plot_beachball_mpl(
                        mt, axes,
                        beachball_type=beachball_type,
                        position=(sx, sy),
                        size=scale_size(source),
                        color_t=color,
                        color_p=color if color_p_axis else 'white',
                        alpha=alpha,
                        zorder=1,
                        linewidth=0.25)

                except beachball.BeachballError as e:
                    logger.warn(str(e))

        item = PlotItem(name='main')
        return [[item, fig]]
Ejemplo n.º 22
0
try:
    gama
except:
    gama = 1.0

fig = plt.figure()
ax = plt.subplot('111', projection=wcs_cut)

x, y = wcs_cut.wcs_world2pix(testra, testdec, 1)
props = dict(facecolor='white', alpha=0.5, edgecolor='None')
plt.text(x, y, galaxy + ' ' + linelabel, fontsize=15, bbox=props)

ax.tick_params(labelsize=8, direction='in')

im = plt.imshow(mom0_cut,
                norm=colors.PowerNorm(gamma=gama),
                vmax=vmax,
                vmin=vmin,
                origin='lower',
                cmap='gist_ncar_r')
plt.xlabel('J2000 Right Ascension')
plt.ylabel('J2000 Declination')

beamellipse_pix.plot(color='black')
cbar = plt.colorbar(im)
cbar.set_label('$Jy\ beam^{-1}\ km\ s^{-1} $', fontsize=15)

south_sky = read_ds9(regionDir + 'south_SFR.reg')[0]
south_pix = south_sky.to_pixel(wcs_cut)
south_pix.plot(color='black', linewidth=2.0)
Ejemplo n.º 23
0
    # process them afterwards using the nan_to_num
    with np.errstate(invalid='ignore'):
        M = np.nan_to_num(N + 1 - np.log2(np.log(abs(Z))) + log_horizon)

    dpi = 72
    width = 10
    height = 10 * yn / xn
    fig = plt.figure(figsize=(width, height), dpi=dpi)
    ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect=1)

    # Shaded rendering
    light = colors.LightSource(azdeg=315, altdeg=10)
    M = light.shade(M,
                    cmap=plt.cm.hot,
                    vert_exag=1.5,
                    norm=colors.PowerNorm(0.3),
                    blend_mode='hsv')
    ax.imshow(M, extent=[xmin, xmax, ymin, ymax], interpolation="bicubic")
    ax.set_xticks([])
    ax.set_yticks([])

    # Some advertisement for matplotlib
    year = time.strftime("%Y")
    text = ("The Mandelbrot fractal set\n"
            "Rendered with matplotlib %s, %s - https://matplotlib.org" %
            (matplotlib.__version__, year))
    ax.text(xmin + .025,
            ymin + .025,
            text,
            color="white",
            fontsize=12,
Ejemplo n.º 24
0
fig = plt.figure(figsize=(20,15))
ax2 = fig.add_subplot(421)
#ax2.set_title("Yield (t/ha)",fontsize=20)


map = Basemap(projection ='cyl', llcrnrlat=-65, urcrnrlat=90,llcrnrlon=-180, urcrnrlon=180, resolution='c')
#map.drawcoastlines()
x,y = map(lon2,lat2)


map.drawcoastlines()
map.drawcountries()
map.drawmapboundary()
#print iyield2
cs = map.pcolormesh(x,y,iyield1,cmap=plt.cm.jet,norm=colors.PowerNorm(gamma=1./2.),vmin=0,vmax=16)

#cbar = map.colorbar(cs,location='bottom',size="5%",pad="2%")
#cbar.ax.tick_params(labelsize=15)
plt.axis('off')
cmap = plt.cm.bwr
bounds=[-30,-25,-20,-15,-10,-5,0,20,40,60,80,100,120]
#bounds=[-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6]
norm = colors.BoundaryNorm(bounds, cmap.N)
#norm = colors.Normalize(vmin=-150, vmax=150)  
#norm=colors.SymLogNorm(linthresh=2, linscale=1,vmin=-200,vmax=200)

ax2 = fig.add_subplot(422)
#ax2.set_title("CESM-ISAM Maize Yield (t/ha)",fontsize=20)
map = Basemap(projection ='cyl', llcrnrlat=-65, urcrnrlat=90,llcrnrlon=-180, urcrnrlon=180, resolution='c')
map.drawcoastlines()
Ejemplo n.º 25
0
#    There should probably be a good reason for plotting the data using
#    this type of transformation.  Technical viewers are used to linear
#    and logarithmic axes and data transformations.  Power laws are less
#    common, and viewers should explicitly be made aware that they have
#    been used.

N = 100
X, Y = np.mgrid[0:3:complex(0, N), 0:2:complex(0, N)]
Z1 = (1 + np.sin(Y * 10.)) * X**2

fig, ax = plt.subplots(2, 1)

pcm = ax[0].pcolormesh(X,
                       Y,
                       Z1,
                       norm=colors.PowerNorm(gamma=0.5),
                       cmap='PuBu_r',
                       shading='auto')
fig.colorbar(pcm, ax=ax[0], extend='max')

pcm = ax[1].pcolormesh(X, Y, Z1, cmap='PuBu_r', shading='auto')
fig.colorbar(pcm, ax=ax[1], extend='max')
plt.show()

###############################################################################
# Discrete bounds
# ---------------
#
# Another normalization that comes with Matplotlib is `.colors.BoundaryNorm`.
# In addition to *vmin* and *vmax*, this takes as arguments boundaries between
# which data is to be mapped.  The colors are then linearly distributed between
Ejemplo n.º 26
0
def plot_result(img_array, ret_img_array):
    std = float(cp.std(ret_img_array))
    gamma = [0.5]
    v_max = [8 * std]
    frac = ret_img_array.shape[0] / 128
    thumbnail_shape = [int(each / frac) for each in ret_img_array.shape]
    thumbnail = np.array(
        Image.fromarray(ret_img_array).resize(thumbnail_shape,
                                              Image.ANTIALIAS))
    # first select proper vmax and gamma
    fig = plt.figure()
    ima = plt.axes((0.1, 0.20, 0.8, 0.7))
    ima.set_title("Please select proper Vmax and Gamma for result")
    ima.imshow(thumbnail,
               cmap="gray",
               norm=colors.PowerNorm(gamma=gamma[0]),
               vmin=0,
               vmax=v_max[0])
    # plot slider
    om1 = plt.axes((0.25, 0.05, 0.65, 0.03))
    om2 = plt.axes((0.25, 0.10, 0.65, 0.03))
    som1 = Slider(om1,
                  r"$max value$",
                  0,
                  16 * std,
                  valinit=v_max[0],
                  dragging=True)  # generate the first slider
    som2 = Slider(om2, r"$Gamma$", 0, 4.0, valinit=gamma[0],
                  dragging=True)  # generate the second slider

    # define update function for slides
    def update(val):
        s1 = som1.val
        s2 = som2.val
        v_max[0] = s1
        gamma[0] = s2
        ima.imshow(thumbnail,
                   cmap="gray",
                   norm=colors.PowerNorm(gamma=gamma[0]),
                   vmin=0,
                   vmax=v_max[0])
        fig.canvas.draw_idle()

    # bind update function to slides
    som1.on_changed(update)
    som2.on_changed(update)
    plt.show()
    del thumbnail

    # then print the final compared images
    fig, (ax1, ax2) = plt.subplots(1, 2)
    # plot original image sequence
    ax1.set_title("Original image sequence")
    ims = []
    for frame in img_array[:200]:
        im = ax1.imshow(frame, cmap="gray", animated=True)
        ims.append([im])
    ani = animation.ArtistAnimation(fig,
                                    ims,
                                    interval=50,
                                    blit=True,
                                    repeat_delay=0)
    # animation.ArtistAnimation(fig, ims, interval=50, blit=True, repeat_delay=0)
    # plot result
    ax2.imshow(ret_img_array,
               cmap="gray",
               norm=colors.PowerNorm(gamma=gamma[0]),
               vmin=0,
               vmax=v_max[0])
    ax2.set_title("srrf image")

    plt.show()
Ejemplo n.º 27
0
@image_comparison(['imshow_bignumbers_real.png'],
                  remove_text=True,
                  style='mpl20')
def test_imshow_bignumbers_real():
    rcParams['image.interpolation'] = 'nearest'
    # putting a big number in an array of integers shouldn't
    # ruin the dynamic range of the resolved bits.
    fig, ax = plt.subplots()
    img = np.array([[2., 1., 1.e22], [4., 1., 3.]])
    pc = ax.imshow(img)
    pc.set_clim(0, 5)


@pytest.mark.parametrize("make_norm", [
    colors.Normalize, colors.LogNorm, lambda: colors.SymLogNorm(1),
    lambda: colors.PowerNorm(1)
])
def test_empty_imshow(make_norm):
    fig, ax = plt.subplots()
    with pytest.warns(UserWarning,
                      match="Attempting to set identical left == right"):
        im = ax.imshow([[]], norm=make_norm())
    im.set_extent([-5, 5, -5, 5])
    fig.canvas.draw()

    with pytest.raises(RuntimeError):
        im.make_image(fig._cachedRenderer)


def test_imshow_float128():
    fig, ax = plt.subplots()
Ejemplo n.º 28
0
    def no_nightglow_uncertainty(self):
        ind = np.squeeze(np.where(self.__features == 'no_nightglow'))
        return self.__uncertainties[:, :, ind]

    @property
    def aurora_radiance(self):
        ind = np.squeeze(np.where((self.__features == 'co_cameron_bands') |
                                  (self.__features == 'co2p_uvd') |
                                  (self.__features == 'o2972') |
                                  (self.__features == 'co2p_fdb')))
        return np.sum(self.__radiances[:, :, ind], axis=2)

    @property
    def aurora_uncertainty(self):
        ind = np.squeeze(np.where((self.__features == 'co_cameron_bands') |
                                  (self.__features == 'co2p_uvd') |
                                  (self.__features == 'o2972') |
                                  (self.__features == 'co2p_fdb')))
        return np.sum(self.__uncertainties[:, :, ind], axis=2)


if __name__ == '__main__':
    df = DataFilename(files[7])
    l1b = L1bDataContents(df)
    img = PipelineMLR(l1b).aurora_radiance
    img = plt.imshow(img, norm=colors.PowerNorm(gamma=1 / 2, vmin=0, vmax=10))
    plt.colorbar()
    plt.show()


Ejemplo n.º 29
0
    def plot_day(self):
        print("Starting plot: 24h")

        # set up figure
        fig = plt.figure(figsize=(self.figwidth, 0.75 * self.figwidth))
        gs = GridSpec(2, 1)
        gs.update(left=0.1,
                  right=0.95,
                  top=0.9,
                  bottom=0.1,
                  hspace=0.05,
                  wspace=0.0)
        ax_t = plt.subplot(gs[0, 0:])
        ax_co = plt.subplot(gs[1, 0:], sharex=ax_t)

        # plot 2D histograms over time as hexbin
        ax_t.hexbin([
            int(h) + int(m) / 60. + int(s) / 3600
            for h, m, s in [x[11:19].split(':') for x in self.data['date']]
        ],
                    self.data['temp'],
                    gridsize=100,
                    cmap='Reds',
                    mincnt=1,
                    extent=(0, 24, self.templim[0], self.templim[1]),
                    norm=colors.PowerNorm(gamma=0.5))
        ax_co.hexbin([
            int(h) + int(m) / 60. + int(s) / 3600
            for h, m, s in [x[11:19].split(':') for x in self.data['date']]
        ],
                     self.data['co2'],
                     gridsize=100,
                     cmap='Blues',
                     mincnt=1,
                     extent=(0, 24, self.co2lim[0], self.co2lim[1]),
                     norm=colors.PowerNorm(gamma=0.5))

        # format figure, labels, ticks
        ax_t.set_title("Last updated " +
                       datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                       fontsize=self.fontsize)
        ax_t.grid(True)
        ax_co.grid(True)
        ax_t.xaxis.tick_top()
        ax_t.xaxis.set_label_position('top')
        ax_t.set_xlabel(r"Hour of the day", fontsize=self.fontsize)
        ax_co.set_xlabel(r"Hour of the day", fontsize=self.fontsize)
        ax_t.set_ylabel(r"temperature [$^\circ$C]", fontsize=self.fontsize)
        ax_co.set_ylabel(r"CO2 concentration [ppm]", fontsize=self.fontsize)
        ax_t.tick_params(axis='both', which='major', labelsize=self.fontsize)
        ax_co.tick_params(axis='both', which='major', labelsize=self.fontsize)
        ax_t.set_xscale('linear')
        ax_t.set_yscale('linear')
        ax_co.set_yscale('linear')
        ax_t.set_xlim(-0.5, 24.5)
        ax_t.set_ylim(self.templim)
        ax_co.set_ylim(self.co2lim)
        ax_t.xaxis.set_major_locator(MultipleLocator(1))
        ax_t.yaxis.set_major_locator(MultipleLocator(2.5))
        ax_co.yaxis.set_major_locator(MultipleLocator(500))
        fig.savefig(os.path.join(self.plotdir, self.logname + '.24h.svg'),
                    bbox_inches='tight')

        # store figure for later use
        self.day_plot = fig

        print("Finished plot: 24h")
Ejemplo n.º 30
0
                                         facecolor='none',
                                         linewidths=0.3))
        ax.add_feature(
            cfeature.NaturalEarthFeature(category='physical',
                                         name='rivers_north_america',
                                         scale='10m',
                                         edgecolor='navy',
                                         facecolor='none',
                                         linewidths=0.3))

        ### plot salinity
        mp = ax.pcolormesh(ds["lon_rho"][:, :],
                           ds["lat_rho"][:, :],
                           ds["salt"][ind, 29, :, :],
                           transform=ccrs.PlateCarree(),
                           norm=colors.PowerNorm(gamma=2),
                           alpha=1,
                           cmap=cmo.cm.haline,
                           vmax=38,
                           vmin=0)

        ### colorbar
        cax = fig.add_axes([0.38, 0.25, 0.415, 0.025])  #colorbar axes
        cb = fig.colorbar(mp, cax=cax, orientation='horizontal')
        cb.ax.set_xticks(np.linspace(0, 35, 8))
        cb.ax.set_xticklabels(["0", "", "10", "15", "20", "25", "30", "35"],
                              fontsize=7)
        cb.ax.tick_params(labelsize=10,
                          length=0,
                          color='0.2',
                          labelcolor='0.2')