Exemplo n.º 1
0
    def set_mappable(self, mappable):
        """
        When a new plot is created this method should be called with the new mappable
        """
        # sanity check the mappable
        mappable = self._validate_mappable(mappable)
        self.ax.clear()
        try:  # Use current cmap
            cmap = get_current_cmap(self.colorbar)
        except AttributeError:
            # else use default
            cmap = ConfigService.getString("plots.images.Colormap")
        self.colorbar = Colorbar(ax=self.ax, mappable=mappable)
        self.cmin_value, self.cmax_value = mappable.get_clim()
        self.update_clim_text()
        self.cmap_changed(cmap, False)

        mappable_cmap = get_current_cmap(mappable)

        if mappable_cmap.name.endswith('_r'):
            self.crev.setChecked(True)
        else:
            self.crev.setChecked(False)
        self.cmap.setCurrentIndex(
            self.cmap_list.index(mappable_cmap.name.replace('_r', '')))

        self.redraw()
Exemplo n.º 2
0
    def colorbar(self, mappable, *, ticks=None, **kwargs):

        if self.orientation in ["top", "bottom"]:
            orientation = "horizontal"
        else:
            orientation = "vertical"

        if mpl.rcParams["mpl_toolkits.legacy_colorbar"]:
            cbook.warn_deprecated(
                "3.2", message="Since %(since)s, mpl_toolkits's own colorbar "
                "implementation is deprecated; it will be removed "
                "%(removal)s.  Set the 'mpl_toolkits.legacy_colorbar' rcParam "
                "to False to use Matplotlib's default colorbar implementation "
                "and suppress this deprecation warning.")
            if ticks is None:
                ticks = ticker.MaxNLocator(5)  # For backcompat.
            from .colorbar import Colorbar
        else:
            from matplotlib.colorbar import Colorbar
        cb = Colorbar(
            self, mappable, orientation=orientation, ticks=ticks, **kwargs)
        self._config_axes()

        self.cbid = mappable.callbacksSM.connect('changed', cb.update_normal)
        mappable.colorbar = cb

        if mpl.rcParams["mpl_toolkits.legacy_colorbar"]:
            self.locator = cb.cbar_axis.get_major_locator()
        else:
            self.locator = cb.locator

        return cb
Exemplo n.º 3
0
def _colorbar_extension_shape(spacing):
    """
    Produce 4 colorbars with rectangular extensions for either uniform
    or proportional spacing.

    Helper function for test_colorbar_extension_shape.
    """
    # Get a colormap and appropriate norms for each extension type.
    cmap, norms = _get_cmap_norms()
    # Create a figure and adjust whitespace for subplots.
    fig = plt.figure()
    fig.subplots_adjust(hspace=4)
    for i, extension_type in enumerate(('neither', 'min', 'max', 'both')):
        # Get the appropriate norm and use it to get colorbar boundaries.
        norm = norms[extension_type]
        boundaries = values = norm.boundaries
        # note that the last value was silently dropped pre 3.3:
        values = values[:-1]
        # Create a subplot.
        cax = fig.add_subplot(4, 1, i + 1)
        # Generate the colorbar.
        Colorbar(cax, cmap=cmap, norm=norm,
                 boundaries=boundaries, values=values,
                 extend=extension_type, extendrect=True,
                 orientation='horizontal', spacing=spacing)
        # Turn off text and ticks.
        cax.tick_params(left=False, labelleft=False,
                        bottom=False, labelbottom=False)
    # Return the figure to the caller.
    return fig
Exemplo n.º 4
0
def _colorbar_extension_length(spacing):
    """
    Produce 12 colorbars with variable length extensions for either
    uniform or proportional spacing.

    Helper function for test_colorbar_extension_length.
    """
    # Get a colormap and appropriate norms for each extension type.
    cmap, norms = _get_cmap_norms()
    # Create a figure and adjust whitespace for subplots.
    fig = plt.figure()
    fig.subplots_adjust(hspace=.6)
    for i, extension_type in enumerate(('neither', 'min', 'max', 'both')):
        # Get the appropriate norm and use it to get colorbar boundaries.
        norm = norms[extension_type]
        boundaries = values = norm.boundaries
        values = values[:-1]
        for j, extendfrac in enumerate((None, 'auto', 0.1)):
            # Create a subplot.
            cax = fig.add_subplot(12, 1, i*3 + j + 1)
            # Generate the colorbar.
            Colorbar(cax, cmap=cmap, norm=norm,
                     boundaries=boundaries, values=values,
                     extend=extension_type, extendfrac=extendfrac,
                     orientation='horizontal', spacing=spacing)
            # Turn off text and ticks.
            cax.tick_params(left=False, labelleft=False,
                              bottom=False, labelbottom=False)
    # Return the figure to the caller.
    return fig
Exemplo n.º 5
0
def test_colorbar_lognorm_extension(extend):
    # Test that colorbar with lognorm is extended correctly
    f, ax = plt.subplots()
    cb = Colorbar(ax,
                  norm=LogNorm(vmin=0.1, vmax=1000.0),
                  orientation='vertical',
                  extend=extend)
    assert cb._values[0] >= 0.0
Exemplo n.º 6
0
def test_colorbar_powernorm_extension():
    # Test that colorbar with powernorm is extended correctly
    f, ax = plt.subplots()
    cb = Colorbar(ax,
                  norm=PowerNorm(gamma=0.5, vmin=0.0, vmax=1.0),
                  orientation='vertical',
                  extend='both')
    assert cb._values[0] >= 0.0
Exemplo n.º 7
0
def make_colorbar(cax, im, dim):
    """
    Function to plot colorbar.

    Args:
        cax (Axes): Axes of colorbar of heatmap, mainly defines the location of the colorbar.
        im (Image): The mapping relationship between data and color.
        dim (str): Unit.
    Returns:
        Axes: Return the axes object of colorbar of heatmap.
    """
    cax.axis('on')
    if dim == 'OnOff' or dim == 'Onoff':
        Colorbar(cax, im, ticks=[0, 1])
    elif '%' in dim or dim == 'percent' or dim == 'percentage':
        Colorbar(cax, im, format='%.0f %%')
    else:
        Colorbar(cax, im, format='%.3g', label='in ' + dim)
    return cax
def plot_scatter_profilesSet(df,
                             profileSet=[],
                             var='CTEMP',
                             wd=7.48,
                             ht=5,
                             varmin=-2,
                             varmax=5,
                             levs=[],
                             show=True,
                             colorunit='$\\theta^{\circ}$C ',
                             save=False,
                             savename="Untitled.png",
                             fontsize=8,
                             zmin=0.0,
                             ticks=[],
                             cline=[],
                             legend_show=True):

    matplotlib.rcParams.update({'font.size': fontsize})
    plt.close(1)
    fig = plt.figure(1, figsize=(wd, ht))
    gs = gridspec.GridSpec(2, 1, height_ratios=[1, 0.05])
    ax = plt.subplot(gs[0, 0])

    if not profileSet:
        raise ValueError('profileSet cannot be null!')
    selectProfiles = df.PROFILE_NUMBER.isin(profileSet)

    cs = ax.scatter(df.loc[selectProfiles, 'DIST_GLINE'],
                    df.loc[selectProfiles, 'DEPTH'],
                    c=df.loc[selectProfiles, 'CTEMP'])
    cs_gamman = ax.tricontour(df.loc[selectProfiles, 'DIST_GLINE'],
                              df.loc[selectProfiles, 'DEPTH'],
                              df.loc[selectProfiles, 'gamman'],
                              colors='0.5')

    distSortedIndices = np.argsort(df.loc[selectProfiles, 'DIST_GLINE'])

    ax.plot(df.loc[selectProfiles, 'DIST_GLINE'].values[distSortedIndices],
            df.loc[selectProfiles, 'ECHODEPTH'].values[distSortedIndices],
            linewidth=4,
            color='k')
    if not cline:
        cline = np.arange(27.8, 28.5, 0.1)
    ax.clabel(cs_gamman, colors='k', fontsize=14, fmt='%3.2f')

    colorax = plt.subplot(gs[1, 0])
    cbar1 = Colorbar(ax=colorax, mappable=cs, orientation='horizontal')
    cbar1.ax.get_children()[0].set_linewidths(5)
    cbar1.set_label(colorunit)

    if save:
        plt.savefig(savename, dpi=300)
    if show:
        plt.show()
Exemplo n.º 9
0
def compare(nx, nz):
    ld = nx / 2
    # load files
    upvert_plot_nl = np.load('upvert_plot_nl.npy')
    upvert_plot_gql3 = np.load('upvert_plot_gql3.npy')
    upvert_plot_ql = np.load('upvert_plot_ql.npy')
    vp_ql = np.load('vp_ql.npy')
    wp_ql = np.load('wp_ql.npy')
    vp_gql3 = np.load('vp_gql3.npy')
    wp_gql3 = np.load('wp_gql3.npy')
    vp_nl = np.load('vp_nl.npy')
    wp_nl = np.load('wp_nl.npy')
# define max/min for colorbar
    combined = np.array([upvert_plot_ql, upvert_plot_gql3, upvert_plot_nl])
    cbarmin, cbarmax = np.amin(combined), np.amax(combined)
    fig = plt.figure(7, figsize=(15,8))
    gs = gridspec.GridSpec(1, 4, width_ratios=[1, 1, 1, 0.05])
    gs.update(left=0.05, right=0.95, bottom=0.2, top=0.6, wspace=0.2, hspace=0.2)
    # set axes (2 rows, 5 columns per row... [ql, colorbar, extra row for spacing, gql, dns, sharedcolorbar]
    ax00 = fig.add_subplot(gs[0, 0])
    ax01 = fig.add_subplot(gs[0, 1], sharey=ax00)
    ax02 = fig.add_subplot(gs[0, 2], sharey=ax00)
    # Define plots
    plt00 = ax00.pcolormesh(Yv[:, 0:nz/2], Z[:, 0:nz/2], upvert_plot_ql, vmax=cbarmax, vmin=cbarmin, cmap=cmap)
    ax00.quiver(Yhalf[::3, ::3], Zhalf[::3, ::3], vp_ql[::3, ::3], wp_ql[::3, ::3])
    plt01 = ax01.pcolormesh(Yv[:, 0:nz/2], Z[:, 0:nz/2], upvert_plot_gql3, vmax=cbarmax, vmin=cbarmin, cmap=cmap)
    ax01.quiver(Yhalf[::3, ::3], Zhalf[::3, ::3], vp_gql3[::3, ::3], wp_gql3[::3, ::3])
    plt02 = ax02.pcolormesh(Yv[:, 0:nz/2], Z[:, 0:nz/2], upvert_plot_nl, vmax=cbarmax, vmin=cbarmin, cmap=cmap)
    ax02.quiver(Yhalf[::3, ::3], Zhalf[::3, ::3], vp_nl[::3, ::3], wp_nl[::3, ::3])
    # Labels
    # fig.suptitle('Streamwise Fluctuations of Time-Averaged Velocity, Near Wall', size=18)
    ax00.set_title('$\Lambda_x$ = 0 (QL)', size=14)
    ax00.set_ylabel('z', size=fsize, rotation=0)
    ax00.tick_params(axis='both', which='major', labelsize=ticksize)
    ax00.set_xlabel('y', size=fsize)
    ax00.yaxis.set_major_locator(plt.MaxNLocator(5))
    ax01.set_title('$\Lambda_x$ = 3 (GQL)', size=fsize)
    ax01.set_xlabel('y', size=fsize)
    ax01.tick_params(axis='both', which='major', labelsize=ticksize)
    ax02.set_title('$\Lambda_x$ = %i (NL)' %ld, size=fsize)
    ax02.set_xlabel('y', size=fsize)
    ax02.tick_params(axis='both', which='major', labelsize=ticksize)
    # Set colorbars
    cbax03 = plt.subplot(gs[0, 3])
    cb03 = Colorbar(ax=cbax03, mappable=plt01, orientation='vertical', ticklocation='right')
    cb03.ax.set_yticklabels(cb03.ax.get_yticklabels(), fontsize=ticksize)
    cb03.ax.yaxis.set_major_locator(plt.MaxNLocator(5))
    # Housekeeping
    plt.setp(ax01.get_yticklabels(), visible=False)      # Turn off ticks for y axes
    plt.setp(ax02.get_yticklabels(), visible=False)
    # plt.setp(ax75.get_yticklabels(), visible=False)
    # plt.setp(ax76.get_yticklabels(), visible=False)
    fig.savefig('vert_structure_compare.png')
    return fig.show()
Exemplo n.º 10
0
Arquivo: plot.py Projeto: sohagb/freud
def pmft_plot(pmft, ax=None):
    """Helper function to draw 2D PMFT diagram.

    .. moduleauthor:: Jin Soo Ihm <*****@*****.**>

    Args:
        pmft (:class:`freud.pmft.PMFTXY2D`):
            PMFTXY2D instance.
        ax (:class:`matplotlib.axes.Axes`): axes object to plot.
            If :code:`None`, make a new axes and figure object.
            (Default value = :code:`None`).

    Returns:
        :class:`matplotlib.axes.Axes`: axes object with the diagram.
    """
    if not MATPLOTLIB:
        return None
    try:
        from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
        from matplotlib.colorbar import Colorbar
    except ImportError:
        return None
    else:
        # Plot figures
        if ax is None:
            fig = Figure()
            ax = fig.subplots()

        pmft_arr = np.copy(pmft.PMFT)
        pmft_arr[np.isinf(pmft_arr)] = np.nan

        xlims = (pmft.X[0], pmft.X[-1])
        ylims = (pmft.Y[0], pmft.Y[-1])
        ax.set_xlim(xlims)
        ax.set_ylim(ylims)
        ax.xaxis.set_ticks([i for i in range(int(xlims[0]), int(xlims[1]+1))])
        ax.yaxis.set_ticks([i for i in range(int(ylims[0]), int(ylims[1]+1))])
        ax.set_xlabel(r'$x$')
        ax.set_ylabel(r'$y$')
        ax.set_title('PMFT')

        ax_divider = make_axes_locatable(ax)
        cax = ax_divider.append_axes("right", size="7%", pad="10%")

        im = ax.imshow(np.flipud(pmft_arr),
                       extent=[xlims[0], xlims[1], ylims[0], ylims[1]],
                       interpolation='nearest', cmap='viridis',
                       vmin=-2.5, vmax=3.0)

        cb = Colorbar(cax, im)
        cb.set_label(r"$k_B T$")

        return ax
Exemplo n.º 11
0
def map_skyobjs(x,
                y,
                n,
                mu,
                label=None,
                n_min=10,
                vmin=None,
                vmax=None,
                y_size=4,
                margin=0.2,
                fontsize=30,
                cbar_label=False):
    """Map the RA, Dec distributions of sky objects."""
    # Only keey the bins with enough sky objects in them
    mu[n <= n_min] = np.nan

    xy_ratio = (x.max() - x.min()) / (y.max() - y.min())

    fig = plt.figure(figsize=(xy_ratio * y_size, y_size))
    ax1 = fig.add_subplot(111)

    ax1.grid(linestyle='--', alpha=0.6)
    im = ax1.imshow(mu.T,
                    origin='lower',
                    extent=[x[0], x[-1], y[0], y[-1]],
                    aspect='equal',
                    interpolation='nearest',
                    cmap=plt.get_cmap('coolwarm'),
                    vmin=vmin,
                    vmax=vmax)

    ax1.set_xlim(x.min() - margin, x.max() + margin)
    ax1.set_ylim(y.min() - margin, y.max() + margin)

    if label is not None:
        plt.text(0.03, 1.05, label, transform=ax1.transAxes, fontsize=38)

    # Color bar
    cb_axes = fig.add_axes([0.48, 0.90, 0.37, 0.06])
    cb = Colorbar(ax=cb_axes,
                  mappable=im,
                  orientation='horizontal',
                  ticklocation='top')
    if cbar_label:
        cb.set_label(r'$\mu{\rm Jy}/\mathrm{arcsec}^2$', fontsize=25)

    _ = ax1.set_xlabel(r'$\mathrm{R.A.\ [deg]}$', fontsize=fontsize)
    _ = ax1.set_ylabel(r'$\mathrm{Dec\ [deg]}$', fontsize=fontsize)

    return fig
Exemplo n.º 12
0
def pmft_plot(pmft, ax=None):
    """Helper function to draw 2D PMFT diagram.

    Args:
        pmft (:class:`freud.pmft.PMFTXY2D`):
            PMFTXY2D instance.
        ax (:class:`matplotlib.axes.Axes`): Axes object to plot.
            If :code:`None`, make a new axes and figure object.
            (Default value = :code:`None`).

    Returns:
        :class:`matplotlib.axes.Axes`: Axes object with the diagram.
    """
    from matplotlib.colorbar import Colorbar
    from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable

    # Plot figures
    if ax is None:
        fig = plt.figure()
        ax = fig.subplots()

    pmft_arr = np.copy(pmft.PMFT)
    pmft_arr[np.isinf(pmft_arr)] = np.nan

    xlims = (pmft.X[0], pmft.X[-1])
    ylims = (pmft.Y[0], pmft.Y[-1])
    ax.set_xlim(xlims)
    ax.set_ylim(ylims)
    ax.xaxis.set_ticks([i for i in range(int(xlims[0]), int(xlims[1] + 1))])
    ax.yaxis.set_ticks([i for i in range(int(ylims[0]), int(ylims[1] + 1))])
    ax.set_xlabel(r"$x$")
    ax.set_ylabel(r"$y$")
    ax.set_title("PMFT")

    ax_divider = make_axes_locatable(ax)
    cax = ax_divider.append_axes("right", size="7%", pad="10%")

    im = ax.imshow(
        np.flipud(pmft_arr),
        extent=[xlims[0], xlims[1], ylims[0], ylims[1]],
        interpolation="nearest",
        cmap="viridis",
        vmin=-2.5,
        vmax=3.0,
    )

    cb = Colorbar(cax, im)
    cb.set_label(r"$k_B T$")

    return ax
Exemplo n.º 13
0
    def colorbar(self, mappable, *, locator=None, **kwargs):

        if locator is None:
            if "ticks" not in kwargs:
                kwargs["ticks"] = ticker.MaxNLocator(5)
        if locator is not None:
            if "ticks" in kwargs:
                raise ValueError("Either *locator* or *ticks* need" +
                                 " to be given, not both")
            else:
                kwargs["ticks"] = locator

        if self.orientation in ["top", "bottom"]:
            orientation = "horizontal"
        else:
            orientation = "vertical"

        if mpl.rcParams["mpl_toolkits.legacy_colorbar"]:
            cbook.warn_deprecated(
                "3.2",
                message="Since %(since)s, mpl_toolkits's own colorbar "
                "implementation is deprecated; it will be removed "
                "%(removal)s.  Set the 'mpl_toolkits.legacy_colorbar' rcParam "
                "to False to use Matplotlib's default colorbar implementation "
                "and suppress this deprecation warning.")
            from .colorbar import Colorbar
        else:
            from matplotlib.colorbar import Colorbar
        cb = Colorbar(self, mappable, orientation=orientation, **kwargs)
        self._config_axes()

        def on_changed(m):
            cb.set_cmap(m.get_cmap())
            cb.set_clim(m.get_clim())
            cb.update_bruteforce(m)

        self.cbid = mappable.callbacksSM.connect('changed', on_changed)
        mappable.colorbar = cb

        if mpl.rcParams["mpl_toolkits.legacy_colorbar"]:
            self.locator = cb.cbar_axis.get_major_locator()
        else:
            self.locator = cb.locator

        return cb
Exemplo n.º 14
0
    def UpdateColorbarPP(stuff):
        v_min = np.int(textbox_pp_min.text)
        v_max = np.int(textbox_pp_max.text)
        my_gamma = np.double(textbox_pp_g.text)

        print("\n v_min = ", v_min)
        print("v_max = ", v_max)
        print("gamma = ", my_gamma)

        pp_image.set_norm(colors.PowerNorm(gamma=my_gamma))
        pp_image.set_clim([v_min, v_max])

        cb_pp = Colorbar(ax=c_ax_pp,
                         mappable=pp_image,
                         orientation='horizontal',
                         ticklocation='top')
        cb_pp.locator = ticker.MaxNLocator(nbins=3)
        cb_pp.update_ticks()
Exemplo n.º 15
0
 def set_mappable(self, mappable):
     """
     When a new plot is created this method should be called with the new mappable
     """
     self.ax.clear()
     try: # Use current cmap
         cmap = self.colorbar.get_cmap()
     except AttributeError:
         try: # else use viridis
             cmap = cm.viridis
         except AttributeError: # else default
             cmap = None
     self.colorbar = Colorbar(ax=self.ax, mappable=mappable)
     self.cmin_value, self.cmax_value = self.colorbar.get_clim()
     self.update_clim_text()
     self.cmap_changed(cmap)
     self.cmap.setCurrentIndex(sorted(cm.cmap_d.keys()).index(self.colorbar.get_cmap().name))
     self.redraw()
Exemplo n.º 16
0
    def set_mappable(self, mappable):
        """
        When a new plot is created this method should be called with the new mappable
        """
        self.ax.clear()
        try:  # Use current cmap
            cmap = get_current_cmap(self.colorbar)
        except AttributeError:
            # else use default
            cmap = ConfigService.getString("plots.images.Colormap")
        self.colorbar = Colorbar(ax=self.ax, mappable=mappable)
        self.cmin_value, self.cmax_value = mappable.get_clim()
        self.update_clim_text()
        self.cmap_changed(cmap)

        mappable_cmap = get_current_cmap(mappable)
        self.cmap.setCurrentIndex(
            sorted(cm.cmap_d.keys()).index(mappable_cmap.name))
        self.redraw()
Exemplo n.º 17
0
Arquivo: plot.py Projeto: sohagb/freud
def plot_density(density, box, ax=None):
    R"""Helper function to plot density diagram.

    Args:
        density (:math:`\left(N_x, N_y\right)` :class:`numpy.ndarray`):
            Array containing density.
        box (:class:`freud.box.Box`):
            Simulation box.
        ax (:class:`matplotlib.axes.Axes`): axes object to plot.
            If :code:`None`, make a new axes and figure object.
            (Default value = :code:`None`).

    Returns:
        :class:`matplotlib.axes.Axes`: axes object with the diagram.
    """
    if not MATPLOTLIB:
        return None
    try:
        from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
        from matplotlib.colorbar import Colorbar
    except ImportError:
        return None

    if ax is None:
        fig = Figure()
        ax = fig.subplots()

    xlims = (-box.Lx/2, box.Lx/2)
    ylims = (-box.Ly/2, box.Ly/2)

    ax.set_title('Gaussian Density')
    ax.set_xlabel(r'$x$')
    ax.set_ylabel(r'$y$')

    ax_divider = make_axes_locatable(ax)
    cax = ax_divider.append_axes("right", size="7%", pad="10%")

    im = ax.imshow(density, extent=[xlims[0], xlims[1], ylims[0], ylims[1]])

    cb = Colorbar(cax, im)
    cb.set_label("Density")

    return ax
Exemplo n.º 18
0
def create_vertical_colorbars(images,
                              labels,
                              subplot_spec,
                              fig=None,
                              n_ticks=3,
                              **kwargs):
    if not isinstance(images, list):
        images = [images]
    if not isinstance(labels, list):
        labels = [labels]
    n_cbars = len(images)
    cbar_gs = gs.GridSpecFromSubplotSpec(n_cbars,
                                         1,
                                         subplot_spec=subplot_spec,
                                         **kwargs)
    if fig is None:
        fig = plt.gcf()
    for image, label, cbar_ss in zip(images, labels, cbar_gs):
        ax = fig.add_subplot(cbar_ss)
        tick_locator = ticker.MaxNLocator(nbins=n_ticks)
        Colorbar(ax, image, ticks=tick_locator, label=label)
Exemplo n.º 19
0
def rate_plot(ax, rate_estimates, rate_windows, N, step=7000, label=''):
    window_x = (rate_windows.start + rate_windows.end) / 2

    rates = [float(rate) for rate in rate_estimates.columns[5:]]
    #log_rates = np.log10(rates)
    #top = log_rates[-1]
    #log_delta = log_rates[2] - log_rates[1]
    #bottom = log_rates[1] - log_delta
    # enable drawing of estimates that overlap 0 (log10(0) = -inf)
    #rates[0] = bottom
    #log_expectation = np.log10(rate_windows.loc[:, 'E'])
    #log_expectation[log_expectation < bottom] = bottom
    expectation = rate_windows.loc[:, 'E']

    # Plot likelihood of rates as heat map
    likelihoods = rate_estimates.loc[:, rate_estimates.
                                     columns[5]:].T  #.loc[::-1, :]
    hm_x = rate_estimates['start'].tolist() + [rate_estimates['end'].max()]
    heatmap = ax.pcolor(hm_x,
                        rates,
                        likelihoods,
                        cmap='viridis',
                        norm=colors.LogNorm(vmin=1e-10, vmax=1))

    legend = label.replace('\n', '') + '_legend'
    legendfig = plt.figure(figsize=(.5, 6))
    legend_ax = legendfig.add_subplot(111)
    cbar = Colorbar(legend_ax, heatmap)
    legendfig.savefig(legend)
    plt.close(legendfig)

    # Plot expectation as solid line
    ax.plot(window_x, expectation, 'k-', linewidth=2, label='Expected Rate')

    # legend = ax.legend(loc='upper left')
    ax.set_ylabel(label)
    ax.set_ylim(0, 0.003)  #ax.set_ylim(bottom, top)
    ax.yaxis.grid(which="major", color='k', linestyle='--', linewidth=1)
def plotProfDist_in_BoundingBox(df,
                                boundingBox=[],
                                var='CTEMP',
                                wd=7.48,
                                ht=5,
                                varmin=-2,
                                varmax=5,
                                levs=[],
                                show=True,
                                plotEcho=False,
                                xlat=False,
                                colorunit='$\\theta^{\circ}$C ',
                                save=False,
                                savename="Untitled.png",
                                fontsize=8,
                                levels=[],
                                zmin=0.0,
                                ticks=[],
                                cline=[],
                                legend_show=True,
                                plotTimeHist=False):

    matplotlib.rcParams.update({'font.size': fontsize})
    plt.close(1)
    fig = plt.figure(1, figsize=(wd, ht))
    gs = gridspec.GridSpec(2, 1, height_ratios=[1, 0.05])
    ax = plt.subplot(gs[0, 0])

    if not boundingBox:
        raise ValueError(
            'provide arg boundingBox in fmt [[llcornerx, llcornery], [urcrnrx, urcrnry]] \n With x1,y1 being lower left corner of bounding box, and going counter-clockwise from that point.'
        )
    try:
        leftlonlim = boundingBox[0][0]
        rightlonlim = boundingBox[1][0]
        lowerlatlim = boundingBox[0][1]
        upperlatlim = boundingBox[1][1]
    except:
        raise ValueError(
            'provide arg boundingBox in fmt [[x1,y1], [x2, y2], [x3, y3], [x4, y4]] \n With x1,y1 being lower left corner of bounding box, and going counter-clockwise from that point.'
        )

    selectProfiles = (df.LATITUDE >= lowerlatlim) & (
        df.LATITUDE <= upperlatlim) & (df.LONGITUDE >= leftlonlim) & (
            df.LONGITUDE <= rightlonlim) & (~df.CTEMP.isnull())

    if xlat:
        dist = df.loc[selectProfiles, 'LATITUDE']
    else:
        dist = df.loc[selectProfiles, 'DIST_GLINE']
    depth = df.loc[selectProfiles, 'DEPTH']
    gamman = df.loc[selectProfiles, 'gamman']

    if xlat:
        ndist = int((np.max(dist) - np.min(dist)) / 0.01)
    else:
        ndist = int(df.loc[selectProfiles, 'DIST_GLINE'].max() / 10.)

    dist_grid = np.linspace(np.min(dist), np.max(dist), ndist)
    ndepth = int(np.abs(df.loc[selectProfiles, 'DEPTH'].min()) / 10.)
    depth_grid = np.linspace(df.loc[selectProfiles, 'DEPTH'].min(), 0, ndepth)

    gamman_interpolated = mlab.griddata(dist,
                                        depth,
                                        gamman,
                                        dist_grid,
                                        depth_grid,
                                        interp='linear')
    cs = ax.scatter(dist,
                    df.loc[selectProfiles, 'DEPTH'],
                    c=df.loc[selectProfiles, 'CTEMP'])

    if levels:
        cs_gamman = ax.contour(dist_grid,
                               depth_grid,
                               gamman_interpolated,
                               levels,
                               colors='0.5')
    else:
        cs_gamman = ax.contour(dist_grid,
                               depth_grid,
                               gamman_interpolated,
                               colors='0.5')

    distSortedIndices = np.argsort(df.loc[selectProfiles, 'DIST_GLINE'])

    if plotEcho:
        depthMin = df.loc[selectProfiles].groupby(
            pd.cut(df.loc[selectProfiles].DIST_GLINE,
                   dist_grid))[["DEPTH"]].min(axis=1).values
        echodepthMin = df.loc[selectProfiles].groupby(
            pd.cut(df.loc[selectProfiles].DIST_GLINE,
                   dist_grid))[["ECHODEPTH"]].min(axis=1).values
        min_of_depth_echodepth = np.array(list(zip(depthMin,
                                                   echodepthMin))).min(axis=1)
        ax.plot(dist_grid[:-1], min_of_depth_echodepth, linewidth=4, color='k')

    #ax.set_xlim(df.loc[selectProfiles, 'DIST_GLINE'].min()-1, df.loc[selectProfiles, 'DIST_GLINE'].max()+1)

    if not cline:
        cline = np.arange(27.8, 28.5, 0.1)
    ax.clabel(cs_gamman, colors='k', fontsize=14, fmt='%3.2f')

    colorax = plt.subplot(gs[1, 0])
    cbar1 = Colorbar(ax=colorax, mappable=cs, orientation='horizontal')
    cbar1.ax.get_children()[0].set_linewidths(5)
    cbar1.set_label(colorunit)

    if plotTimeHist:
        plt.close(2)
        fig = plt.figure(2, figsize=(wd, ht))
        uniqueProfs = df.loc[selectProfiles].groupby("PROFILE_NUMBER").head(
            1).index
        df.loc[uniqueProfs, "JULD"].hist()
        plt.show()
    if save:
        plt.savefig(savename, dpi=300)
    if show:
        plt.show()
Exemplo n.º 21
0
def test_colorbarbase():
    # smoke test from #3805
    ax = plt.gca()
    Colorbar(ax, cmap=plt.cm.bone)
def generate_2d_histogram(data_x: np.ndarray, data_y: np.ndarray,
                          x_bounds: Tuple[float,
                                          float], y_bounds: Tuple[float,
                                                                  float],
                          x_label: Tuple[str, str], y_label: Tuple[str, str],
                          title: str, hist_axis: matplotlib.axes.Axes,
                          cbar_axis: matplotlib.axes.Axes) -> None:
    """
    Add the 2D histogram of trace values to the pairwise comparison
    plot

    Parameters
    ----------
    data_x: np.ndarray
        The trace array to plot on the x axis

    data_y: np.ndarray
        The trace array to plot on the y axis

    x_bounds: Tuple[float, float]
        The (min, max) values of the x axis

    y_bounds: Typle[float, float]
        The (min, max) values of the y axis

    x_label: Tuple[str, str]
        Zeroth element is the label of the x axis;
        First element is the hexadecimal color of that label

    y_label: Tuple[str, str]
        Zeroth element is the label of the y axis;
        First element is the hexadecimal color of that label

    title: str
        The title to be applied to the whole plot

    hist_axis: matplotlib.axes.Axes
        The axis on which to plot the 2D histogram

    cbar_axis: matplotlib.axes.Axes
        The axis on which to plot the colorbar associated with
        the histogram

    Returns
    -------
    None
    """

    # filter out NaNs
    valid = np.logical_and(np.logical_not(np.isnan(data_x)),
                           np.logical_not(np.isnan(data_y)))
    data_x = data_x[valid]
    data_y = data_y[valid]
    if len(data_x) == 0:
        return None

    # construct custom color map for the 2D histogram
    raw_cmap = plt.get_cmap('Blues')
    data = [raw_cmap(x) for x in np.arange(0.3, 0.95, 0.05)]
    cmap = matplotlib.colors.LinearSegmentedColormap.from_list(
        'custom_blue', data)

    xmin = x_bounds[0]
    ymin = y_bounds[0]

    # subtracting of xmin for conversion to pixel
    # coordinates in the image
    data_x = data_x - xmin
    data_y = data_y - ymin

    xmax = x_bounds[1] - xmin
    ymax = y_bounds[1] - ymin

    nx = 25  # number of x pixels
    ny = 25
    dx = xmax / nx  # size of x pixels
    dy = ymax / ny

    # convert traces to pixel integers
    xx = np.round(data_x / dx).astype(int)
    xx = np.where(xx < nx, xx, nx - 1)

    yy = np.round(data_y / dy).astype(int)
    yy = np.where(yy < ny, yy, ny - 1)

    # find number of timesteps that fall in each pixel
    one_d_coords = xx * ny + yy
    unq, unq_ct = np.unique(one_d_coords, return_counts=True)
    xx = unq // ny
    yy = unq % ny

    hist = np.zeros((ny, nx), dtype=int)
    hist[yy, xx] = unq_ct
    hist = np.where(hist > 0, hist, np.NaN)

    img = hist_axis.imshow(hist, cmap=cmap, origin='lower')

    # find reasonable tick labels for x axis
    log10_nx = np.floor(np.log10(dx))
    xticks = None
    while xticks is None or len(xticks) > 4:
        log10_nx += 1
        v = np.power(10, log10_nx)
        for tick_dx in np.arange(v, 5 * v, v):
            xticks = np.arange(xmin, xmax + xmin, tick_dx)
            if len(xticks) <= 4:
                break

    xtick_labels = ['%d' % x for x in xticks]
    hist_axis.set_xticks((xticks - xmin) / dx)
    hist_axis.set_xticklabels(xtick_labels, fontsize=7)

    # find reasonable tick labels for y axis
    log10_ny = np.floor(np.log10(dy))
    yticks = None
    while yticks is None or len(yticks) > 4:
        log10_ny += 1
        v = np.power(10, log10_ny)
        for tick_dy in np.arange(v, 5 * v, v):
            yticks = np.arange(ymin, ymax + ymin, tick_dy)
            if len(yticks) <= 4:
                break

    ytick_labels = ['%d' % y for y in yticks]
    hist_axis.set_yticks((yticks - ymin) / dy)
    hist_axis.set_yticklabels(ytick_labels, fontsize=7)

    hist_axis.set_xlabel(x_label[0], color=x_label[1], fontsize=10)
    hist_axis.set_ylabel(y_label[0], color=y_label[1], fontsize=10)

    hist_axis.set_title(title, fontsize=10)

    # plot color bar
    _ = Colorbar(mappable=img, ax=cbar_axis)
    cbar_axis.yaxis.set_ticks_position('left')

    # find reasonable tick labels for color bar
    hist_min = np.nanmin(hist)
    hist_max = np.nanmax(hist)
    log10_nhist = np.floor(np.log10(hist_max)) - 2
    hist_ticks = None
    while hist_ticks is None or len(hist_ticks) > 4:
        log10_nhist += 1
        v = np.power(10, log10_nhist)
        for tick_hist in np.arange(v, 5 * v, v):
            _min = np.round(hist_min / tick_hist).astype(int) * tick_hist
            _max = np.round(hist_max / tick_hist).astype(int) * tick_hist
            hist_ticks = np.arange(_min, _max + 1, tick_hist)
            hist_ticks = hist_ticks[np.where(hist_ticks < hist_max)]
            if len(hist_ticks) <= 4:
                break

    cbar_axis.yaxis.set_ticks(hist_ticks)

    return None
Exemplo n.º 23
0
X = X /1e+3
Y = Y / 1e+3
cordx = cordx /1e+3
cordy = cordy /1e+3
filename_counter = 0
for i in np.arange(len(magnitude1)):
    
    fig = plt.figure(figsize =(4.1,4.1))
    gs = fig.add_gridspec(28,28)
    
    ax_cb = plt.subplot(gs[0:12,13])
    ax_map = plt.subplot(gs[0:12,1:13])
    ax_UWD = plt.subplot(gs[17:22,1:-1])
    ax_SDH = plt.subplot(gs[23:,1:-1])
    cf = ax_map.contourf(X,Y,uztot[i,:,:],levels = np.linspace(np.min(uztot),0,30))
    cb = Colorbar(ax = ax_cb, mappable = cf,ticks = np.linspace(np.min(uztot),0,5))
    cbar_label = np.round(np.linspace(np.min(uztot),0,5)*10)/10
    cb.ax.set_yticklabels(cbar_label,fontsize = 6 )
    cb.set_label('Vert. Displacement [m]',fontsize = 8 )

    ax_map.set_xticks([np.min(X),0,np.max(X)])
    ax_map.set_yticks([np.min(Y),0,np.max(Y)])
    ax_map.set_xlabel('x [km]',fontsize = 8 )
    ax_map.set_ylabel('y [km]', fontsize = 8)
    ax_map.set_xticklabels(labels = [int(np.min(X)),int(0),int(np.max(X))], fontsize = 6)
    ax_map.set_yticklabels(labels = [int(np.min(Y)),0,int(np.max(Y))], fontsize = 6)

    
    h1 = []
    h2 = []
    names_st = ['ST1','ST2']
def plot_station_locations(positions,
                           title=' ',
                           save=False,
                           savename="untitled.png",
                           wd=12,
                           ht=12,
                           region='Whole',
                           plotBathy=True):
    x = positions[:, 1]
    y = positions[:, 0]

    lat0 = -90
    lon0 = 0

    plt.figure(1, figsize=(wd, ht))
    gs = gridspec.GridSpec(2, 1, height_ratios=[1, 0.05])
    mapax = plt.subplot(gs[0, 0])
    m = createMapProjections(lat0, lon0, region=region)

    m.drawmapboundary()
    m.drawcoastlines()
    #m.fillcontinents(color='#cc9966');
    m.readshapefile(
        "/media/data/Datasets/Shapefiles/AntarcticGroundingLine/GSHHS_f_L6",
        "GSHHS_f_L6",
        color='m')

    ## if(markers != None):
    ##     for i in range(len(markers)):
    ##         plt.text(xgrid[i],ygrid[i], str(markers[i]), color='b');

    parallels = np.arange(-80, -30 + 1, 5.)
    labels = [1, 1, 1, 0]
    m.drawparallels(parallels, labels=labels)
    meridians = np.arange(-180, 180, 20.)
    labels = [1, 1, 0, 1]
    m.drawmeridians(meridians, labels=labels)
    m.scatter(x, y, latlon=True, color='r', s=0.25, marker='.')

    if (plotBathy == True):
        bathy = xr.open_dataset(
            '/media/data/Datasets/Bathymetry/GEBCO_2014_2D.nc')
        lonlen = len(bathy.lon)
        lonindices = np.arange(0, lonlen + 1, 30)
        lonindices[-1] = lonindices[-1] - 1
        bathyS = bathy.isel(lon=lonindices, lat=np.arange(0, 3600, 5))
        clevs = np.array([-100, -500, -1000, -1500, -2000, -3000, -6000])[::-1]

        longrid, latgrid = np.meshgrid(bathyS.lon.values, bathyS.lat.values)
        cs = m.contour(longrid,
                       latgrid,
                       bathyS.elevation.where(bathyS.elevation <= 0).values,
                       latlon=True,
                       levels=clevs,
                       linewidths=0.2,
                       extend='min',
                       ax=mapax)  #, , cmap='rainbow'   , levels=clevs,
        ## plt.figure(2)
        ## cf = plt.contourf(longrid, latgrid,bathyS.elevation.where(bathyS.elevation <= 0).values, levels=clevs, extend='min') #, , cmap='rainbow'   , levels=clevs,
        ## plt.figure(1)
        bathycolorbar = plt.subplot(gs[1, 0])
        cbar1 = Colorbar(ax=bathycolorbar,
                         mappable=cs,
                         orientation='horizontal')
        cbar1.ax.get_children()[0].set_linewidths(5)
        cbar1.set_label('Depth (m)')

    if (save == True):
        plt.savefig(savename, dpi=900)
    plt.show()
Exemplo n.º 25
0
cmap=copy(plt.cm.plasma)
cmap.set_bad('white', 1.)
cmap.set_over('yellow', 1.)

offset=.125
image1 = m1.pcolormesh(x-offset,y+offset,np.ma.masked_invalid(plotter1),shading='flat', cmap=cmap,vmin=0, vmax=1)
image2 = m2.pcolormesh(x-offset,y+offset,np.ma.masked_invalid(plotter2),shading='flat', cmap=cmap,vmin=0, vmax=1)


# DRAW COASTLINES AND MAP BOUNDARY
m1.drawcoastlines()
m1.drawmapboundary()
m2.drawcoastlines()
m2.drawmapboundary()

#COLORBAR
from matplotlib.colorbar import Colorbar
cb=Colorbar(ax=ax3, mappable = image1, orientation="vertical", ticks=[0,.25,.5,.75,1])             
cb.ax.tick_params(labelsize=ftsz-2)
cb.ax.set_ylabel('R$^2$ (BA$_{actual}$, BA$_{predicted}$)',fontsize=ftsz, labelpad=12)

#TEXT LABELS
ax1.text(.38,1.02,'Soil Moisture', fontsize=ftsz-2,transform=ax1.transAxes)
ax2.text(.38,1.02,'Precipitation', fontsize=ftsz-2, transform=ax2.transAxes)
#A and B label
ax1.text(-.05,.96,'a', weight='bold', fontsize=ftsz,transform=ax1.transAxes)
ax2.text(-.05,.96,'b', weight='bold',fontsize=ftsz, transform=ax2.transAxes)

plt.show()

Exemplo n.º 26
0
def voronoi_plot(box, polytopes, ax=None, color_by_sides=True, cmap=None):
    """Helper function to draw 2D Voronoi diagram.

    Args:
        box (:class:`freud.box.Box`):
            Simulation box.
        polytopes (:class:`numpy.ndarray`):
            Array containing Voronoi polytope vertices.
        ax (:class:`matplotlib.axes.Axes`): Axes object to plot.
            If :code:`None`, make a new axes and figure object.
            (Default value = :code:`None`).
        color_by_sides (bool):
            If :code:`True`, color cells by the number of sides.
            If :code:`False`, random colors are used for each cell.
            (Default value = :code:`True`).
        cmap (str):
            Colormap name to use (Default value = :code:`None`).

    Returns:
        :class:`matplotlib.axes.Axes`: Axes object with the diagram.
    """
    from matplotlib import cm
    from matplotlib.collections import PatchCollection
    from matplotlib.patches import Polygon
    from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
    from matplotlib.colorbar import Colorbar

    if ax is None:
        fig = Figure()
        ax = fig.subplots()

    # Draw Voronoi polytopes
    patches = [Polygon(poly[:, :2]) for poly in polytopes]
    patch_collection = PatchCollection(patches, edgecolors='black', alpha=0.4)

    if color_by_sides:
        colors = np.array([len(poly) for poly in polytopes])
        num_colors = np.ptp(colors) + 1
    else:
        colors = np.random.RandomState().permutation(np.arange(len(patches)))
        num_colors = np.unique(colors).size

    # Ensure we have enough colors to uniquely identify the cells
    if cmap is None:
        if color_by_sides and num_colors <= 10:
            cmap = 'tab10'
        else:
            if num_colors > 20:
                warnings.warn('More than 20 unique colors were requested. '
                              'Consider providing a colormap to the cmap '
                              'argument.', UserWarning)
            cmap = 'tab20'
    cmap = cm.get_cmap(cmap, num_colors)
    bounds = np.arange(np.min(colors), np.max(colors)+1)

    patch_collection.set_array(np.array(colors)-0.5)
    patch_collection.set_cmap(cmap)
    patch_collection.set_clim(bounds[0]-0.5, bounds[-1]+0.5)
    ax.add_collection(patch_collection)

    # Draw box
    corners = [[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]]
    # Need to copy the last point so that the box is closed.
    corners.append(corners[0])
    corners = box.make_absolute(corners)[:, :2]
    ax.plot(corners[:, 0], corners[:, 1], color='k')

    # Set title, limits, aspect
    ax.set_title('Voronoi Diagram')
    ax.set_xlim((np.min(corners[:, 0]), np.max(corners[:, 0])))
    ax.set_ylim((np.min(corners[:, 1]), np.max(corners[:, 1])))
    ax.set_aspect('equal', 'datalim')

    # Add colorbar for number of sides
    if color_by_sides:
        ax_divider = make_axes_locatable(ax)
        cax = ax_divider.append_axes("right", size="7%", pad="10%")
        cb = Colorbar(cax, patch_collection)
        cb.set_label("Number of sides")
        cb.set_ticks(bounds)
    return ax
Exemplo n.º 27
0
    def plot(self, figure=None, overlays=[], colorbar=True, vmin=None,
             vmax=None, linear=True, showz=True, yres=DEFAULT_YRES,
             max_dist=None, **matplotlib_args):
        """
        Plot spectrogram onto figure.

        Parameters
        ----------
        figure : `~matplotlib.Figure`
            Figure to plot the spectrogram on. If None, new Figure is created.
        overlays : list
            List of overlays (functions that receive figure and axes and return
            new ones) to be applied after drawing.
        colorbar : bool
            Flag that determines whether or not to draw a colorbar. If existing
            figure is passed, it is attempted to overdraw old colorbar.
        vmin : float
            Clip intensities lower than vmin before drawing.
        vmax : float
            Clip intensities higher than vmax before drawing.
        linear : bool
            If set to True, "stretch" image to make frequency axis linear.
        showz : bool
            If set to True, the value of the pixel that is hovered with the
            mouse is shown in the bottom right corner.
        yres : int or None
            To be used in combination with linear=True. If None, sample the
            image with half the minimum frequency delta. Else, sample the
            image to be at most yres pixels in vertical dimension. Defaults
            to 1080 because that's a common screen size.
        max_dist : float or None
            If not None, mask elements that are further than max_dist away
            from actual data points (ie, frequencies that actually have data
            from the receiver and are not just nearest-neighbour interpolated).
        """
        # [] as default argument is okay here because it is only read.
        # pylint: disable=W0102,R0914
        if linear:
            delt = yres
            if delt is not None:
                delt = max(
                    (self.freq_axis[0] - self.freq_axis[-1]) / (yres - 1),
                    _min_delt(self.freq_axis) / 2.
                )
                delt = float(delt)

            data = _LinearView(self.clip_values(vmin, vmax), delt)
            freqs = np.arange(
                self.freq_axis[0], self.freq_axis[-1], -data.delt
            )
        else:
            data = np.array(self.clip_values(vmin, vmax))
            freqs = self.freq_axis

        figure = plt.gcf()

        if figure.axes:
            axes = figure.axes[0]
        else:
            axes = figure.add_subplot(111)

        params = {
            'origin': 'lower',
            'aspect': 'auto',
        }
        params.update(matplotlib_args)
        if linear and max_dist is not None:
            toplot = ma.masked_array(data, mask=data.make_mask(max_dist))
        else:
            toplot = data
        im = axes.imshow(toplot, **params)

        xa = axes.get_xaxis()
        ya = axes.get_yaxis()

        xa.set_major_formatter(
            FuncFormatter(self.time_formatter)
        )

        if linear:
            # Start with a number that is divisible by 5.
            init = (self.freq_axis[0] % 5) / data.delt
            nticks = 15.
            # Calculate MHz difference between major ticks.
            dist = (self.freq_axis[0] - self.freq_axis[-1]) / nticks
            # Round to next multiple of 10, at least ten.
            dist = max(round(dist, -1), 10)
            # One pixel in image space is data.delt MHz, thus we can convert
            # our distance between the major ticks into image space by dividing
            # it by data.delt.

            ya.set_major_locator(
                IndexLocator(
                    dist / data.delt, init
                )
            )
            ya.set_minor_locator(
                IndexLocator(
                    dist / data.delt / 10, init
                )
            )

            def freq_fmt(x, pos):
                # This is necessary because matplotlib somehow tries to get
                # the mid-point of the row, which we do not need here.
                x = x + 0.5
                return self.format_freq(self.freq_axis[0] - x * data.delt)
        else:
            freq_fmt = _list_formatter(freqs, self.format_freq)
            ya.set_major_locator(MaxNLocator(integer=True, steps=[1, 5, 10]))

        ya.set_major_formatter(
            FuncFormatter(freq_fmt)
        )

        axes.set_xlabel(self.t_label)
        axes.set_ylabel(self.f_label)
        # figure.suptitle(self.content)

        figure.suptitle(
            ' '.join([
                get_day(self.start).strftime("%d %b %Y"),
                'Radio flux density',
                '(' + ', '.join(self.instruments) + ')',
            ])
        )

        for tl in xa.get_ticklabels():
            tl.set_fontsize(10)
            tl.set_rotation(30)
        figure.add_axes(axes)
        figure.subplots_adjust(bottom=0.2)
        figure.subplots_adjust(left=0.2)

        if showz:
            axes.format_coord = self._mk_format_coord(
                data, figure.gca().format_coord)

        if colorbar:
            if len(figure.axes) > 1:
                Colorbar(figure.axes[1], im).set_label("Intensity")
            else:
                figure.colorbar(im).set_label("Intensity")

        for overlay in overlays:
            figure, axes = overlay(figure, axes)

        for ax in figure.axes:
            ax.autoscale()
        if isinstance(figure, SpectroFigure):
            figure._init(self, freqs)
        return axes
Exemplo n.º 28
0
def diffraction_plot(diffraction,
                     k_values,
                     ax=None,
                     cmap="afmhot",
                     vmin=4e-6,
                     vmax=0.7):
    """Helper function to plot diffraction pattern.

    Args:
        diffraction (:class:`numpy.ndarray`):
            Diffraction image data.
        k_values (:class:`numpy.ndarray`):
            :math:`k` value magnitudes for each bin of the diffraction image.
        ax (:class:`matplotlib.axes.Axes`):
            Axes object to plot. If :code:`None`, make a new axes and figure
            object (Default value = :code:`None`).
        cmap (str):
            Colormap name to use (Default value = :code:`'afmhot'`).
        vmin (float):
            Minimum of the color scale (Default value = 4e-6).
        vmax (float):
            Maximum of the color scale (Default value = 0.7).

    Returns:
        :class:`matplotlib.axes.Axes`: Axes object with the diagram.
    """
    import matplotlib.colors
    from matplotlib.colorbar import Colorbar
    from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable

    if ax is None:
        fig = plt.figure()
        ax = fig.subplots()

    # Plot the diffraction image and color bar
    norm = matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax)
    im = ax.imshow(np.clip(diffraction, vmin, vmax),
                   interpolation="nearest",
                   cmap=cmap,
                   norm=norm)
    ax_divider = make_axes_locatable(ax)
    cax = ax_divider.append_axes("right", size="7%", pad="10%")
    cb = Colorbar(cax, im)
    cb.set_label(r"$S(\vec{k})$")

    # Determine the number of ticks on the axis
    grid_size = diffraction.shape[0]
    num_ticks = len(
        [i for i in ax.xaxis.get_ticklocs() if 0 <= i <= grid_size])

    # Ensure there are an odd number of ticks, so that there is a tick at zero
    num_ticks += 1 - num_ticks % 2
    ticks = np.linspace(0, grid_size, num_ticks)

    # Set tick locations and labels
    tick_labels = np.interp(ticks, range(grid_size), k_values)
    tick_labels = [f"{x:.3g}" for x in tick_labels]
    ax.xaxis.set_ticks(ticks)
    ax.xaxis.set_ticklabels(tick_labels)
    ax.yaxis.set_ticks(ticks)
    ax.yaxis.set_ticklabels(tick_labels)

    # Set title, limits, aspect
    ax.set_title("Diffraction Pattern")
    ax.set_aspect("equal", "datalim")
    ax.set_xlabel("$k_x$")
    ax.set_ylabel("$k_y$")

    return ax
Exemplo n.º 29
0
def plot_cartopy(lons,
                 lats,
                 size,
                 color,
                 labels=None,
                 projection='global',
                 resolution='110m',
                 continent_fill_color='0.8',
                 water_fill_color='1.0',
                 colormap=None,
                 colorbar=None,
                 marker="o",
                 title=None,
                 colorbar_ticklabel_format=None,
                 show=True,
                 proj_kwargs=None,
                 **kwargs):  # @UnusedVariable
    """
    Creates a Cartopy plot with a data point scatter plot.

    :type lons: list/tuple of floats
    :param lons: Longitudes of the data points.
    :type lats: list/tuple of floats
    :param lats: Latitudes of the data points.
    :type size: float or list/tuple of floats
    :param size: Size of the individual points in the scatter plot.
    :type color: list/tuple of floats (or objects that can be
        converted to floats, like e.g.
        :class:`~obspy.core.utcdatetime.UTCDateTime`)
    :param color: Color information of the individual data points to be
        used in the specified color map (e.g. origin depths,
        origin times).
    :type labels: list/tuple of str
    :param labels: Annotations for the individual data points.
    :type projection: str, optional
    :param projection: The map projection.
        Currently supported are:

            * ``"global"`` (Will plot the whole world using
              :class:`~cartopy.crs.Mollweide`.)
            * ``"ortho"`` (Will center around the mean lat/long using
              :class:`~cartopy.crs.Orthographic`.)
            * ``"local"`` (Will plot around local events using
              :class:`~cartopy.crs.AlbersEqualArea`.)
            * Any other Cartopy :class:`~cartopy.crs.Projection`. An instance
              of this class will be created using the supplied ``proj_kwargs``.

        Defaults to "global"
    :type resolution: str, optional
    :param resolution: Resolution of the boundary database to use. Will be
        passed directly to the Cartopy module. Possible values are:

            * ``"110m"``
            * ``"50m"``
            * ``"10m"``

        Defaults to ``"110m"``. For compatibility, you may also specify any of
        the Basemap resolutions defined in :func:`plot_basemap`.
    :type continent_fill_color: Valid matplotlib color, optional
    :param continent_fill_color:  Color of the continents. Defaults to
        ``"0.9"`` which is a light gray.
    :type water_fill_color: Valid matplotlib color, optional
    :param water_fill_color: Color of all water bodies.
        Defaults to ``"white"``.
    :type colormap: str, any matplotlib colormap, optional
    :param colormap: The colormap for color-coding the events as provided
        in `color` kwarg.
        The event with the smallest `color` property will have the
        color of one end of the colormap and the event with the highest
        `color` property the color of the other end with all other events
        in between.
        Defaults to None which will use the default matplotlib colormap.
    :type colorbar: bool, optional
    :param colorbar: When left `None`, a colorbar is plotted if more than one
        object is plotted. Using `True`/`False` the colorbar can be forced
        on/off.
    :type title: str
    :param title: Title above plot.
    :type colorbar_ticklabel_format: str or function or
        subclass of :class:`matplotlib.ticker.Formatter`
    :param colorbar_ticklabel_format: Format string or Formatter used to format
        colorbar tick labels.
    :type show: bool
    :param show: Whether to show the figure after plotting or not. Can be used
        to do further customization of the plot before showing it.
    :type proj_kwargs: dict
    :param proj_kwargs: Keyword arguments to pass to the Cartopy
        :class:`~cartopy.ccrs.Projection`. In this dictionary, you may specify
        ``central_longitude='auto'`` or ``central_latitude='auto'`` to have
        this function calculate the latitude or longitude as it would for other
        projections. Some arguments may be ignored if you choose one of the
        built-in ``projection`` choices.
    """
    import matplotlib.pyplot as plt
    min_color = min(color)
    max_color = max(color)

    if isinstance(color[0], (datetime.datetime, UTCDateTime)):
        datetimeplot = True
        color = [date2num(getattr(t, 'datetime', t)) for t in color]
    else:
        datetimeplot = False

    scal_map = ScalarMappable(norm=Normalize(min_color, max_color),
                              cmap=colormap)
    scal_map.set_array(np.linspace(0, 1, 1))

    fig = plt.figure()

    # The colorbar should only be plotted if more then one event is
    # present.
    if colorbar is not None:
        show_colorbar = colorbar
    else:
        if len(lons) > 1 and hasattr(color, "__len__") and \
                not isinstance(color, (str, native_str)):
            show_colorbar = True
        else:
            show_colorbar = False

    if projection == "local":
        ax_x0, ax_width = 0.10, 0.80
    elif projection == "global":
        ax_x0, ax_width = 0.01, 0.98
    else:
        ax_x0, ax_width = 0.05, 0.90

    proj_kwargs = proj_kwargs or {}
    if projection == 'global':
        proj_kwargs['central_longitude'] = np.mean(lons)
        proj = ccrs.Mollweide(**proj_kwargs)
    elif projection == 'ortho':
        proj_kwargs['central_latitude'] = np.mean(lats)
        proj_kwargs['central_longitude'] = np.mean(lons)
        proj = ccrs.Orthographic(**proj_kwargs)
    elif projection == 'local':
        if min(lons) < -150 and max(lons) > 150:
            max_lons = max(np.array(lons) % 360)
            min_lons = min(np.array(lons) % 360)
        else:
            max_lons = max(lons)
            min_lons = min(lons)
        lat_0 = max(lats) / 2. + min(lats) / 2.
        lon_0 = max_lons / 2. + min_lons / 2.
        if lon_0 > 180:
            lon_0 -= 360
        deg2m_lat = 2 * np.pi * 6371 * 1000 / 360
        deg2m_lon = deg2m_lat * np.cos(lat_0 / 180 * np.pi)
        if len(lats) > 1:
            height = (max(lats) - min(lats)) * deg2m_lat
            width = (max_lons - min_lons) * deg2m_lon
            margin = 0.2 * (width + height)
            height += margin
            width += margin
        else:
            height = 2.0 * deg2m_lat
            width = 5.0 * deg2m_lon
        # Do intelligent aspect calculation for local projection
        # adjust to figure dimensions
        w, h = fig.get_size_inches()
        aspect = w / h
        if show_colorbar:
            aspect *= 1.2
        if width / height < aspect:
            width = height * aspect
        else:
            height = width / aspect

        proj_kwargs['central_latitude'] = lat_0
        proj_kwargs['central_longitude'] = lon_0
        proj = ccrs.AlbersEqualArea(**proj_kwargs)

    # User-supplied projection.
    elif isinstance(projection, type):
        if 'central_longitude' in proj_kwargs:
            if proj_kwargs['central_longitude'] == 'auto':
                proj_kwargs['central_longitude'] = np.mean(lons)
        if 'central_latitude' in proj_kwargs:
            if proj_kwargs['central_latitude'] == 'auto':
                proj_kwargs['central_latitude'] = np.mean(lats)
        if 'pole_longitude' in proj_kwargs:
            if proj_kwargs['pole_longitude'] == 'auto':
                proj_kwargs['pole_longitude'] = np.mean(lons)
        if 'pole_latitude' in proj_kwargs:
            if proj_kwargs['pole_latitude'] == 'auto':
                proj_kwargs['pole_latitude'] = np.mean(lats)

        proj = projection(**proj_kwargs)

    else:
        msg = "Projection '%s' not supported." % projection
        raise ValueError(msg)

    if show_colorbar:
        map_ax = fig.add_axes([ax_x0, 0.13, ax_width, 0.77], projection=proj)
        cm_ax = fig.add_axes([ax_x0, 0.05, ax_width, 0.05])
        plt.sca(map_ax)
    else:
        ax_y0, ax_height = 0.05, 0.85
        if projection == "local":
            ax_y0 += 0.05
            ax_height -= 0.05
        map_ax = fig.add_axes([ax_x0, ax_y0, ax_width, ax_height],
                              projection=proj)

    if projection == 'local':
        x0, y0 = proj.transform_point(lon_0, lat_0, proj.as_geodetic())
        map_ax.set_xlim(x0 - width / 2, x0 + width / 2)
        map_ax.set_ylim(y0 - height / 2, y0 + height / 2)
    else:
        map_ax.set_global()

    # Pick features at specified resolution.
    resolution = _CARTOPY_RESOLUTIONS[resolution]
    try:
        borders, land, ocean = _CARTOPY_FEATURES[resolution]
    except KeyError:
        borders = cfeature.NaturalEarthFeature(cfeature.BORDERS.category,
                                               cfeature.BORDERS.name,
                                               resolution,
                                               edgecolor='none',
                                               facecolor='none')
        land = cfeature.NaturalEarthFeature(cfeature.LAND.category,
                                            cfeature.LAND.name,
                                            resolution,
                                            edgecolor='face',
                                            facecolor='none')
        ocean = cfeature.NaturalEarthFeature(cfeature.OCEAN.category,
                                             cfeature.OCEAN.name,
                                             resolution,
                                             edgecolor='face',
                                             facecolor='none')
        _CARTOPY_FEATURES[resolution] = (borders, land, ocean)

    # Draw coast lines, country boundaries, fill continents.
    map_ax.set_axis_bgcolor(water_fill_color)
    map_ax.add_feature(ocean, facecolor=water_fill_color)
    map_ax.add_feature(land, facecolor=continent_fill_color)
    map_ax.add_feature(borders, edgecolor='0.75')
    map_ax.coastlines(resolution=resolution, color='0.4')

    # Draw grid lines - TODO: draw_labels=True doesn't work yet.
    if projection == 'local':
        map_ax.gridlines()
    else:
        # Draw lat/lon grid lines every 30 degrees.
        map_ax.gridlines(xlocs=range(-180, 181, 30), ylocs=range(-90, 91, 30))

    # Plot labels
    if labels and len(lons) > 0:
        with map_ax.hold_limits():
            for name, xpt, ypt, _colorpt in zip(labels, lons, lats, color):
                map_ax.text(xpt,
                            ypt,
                            name,
                            weight="heavy",
                            color="k",
                            zorder=100,
                            transform=ccrs.Geodetic(),
                            path_effects=[
                                PathEffects.withStroke(linewidth=3,
                                                       foreground="white")
                            ])

    scatter = map_ax.scatter(lons,
                             lats,
                             marker=marker,
                             s=size,
                             c=color,
                             zorder=10,
                             cmap=colormap,
                             transform=ccrs.Geodetic())

    if title:
        plt.suptitle(title)

    # Only show the colorbar for more than one event.
    if show_colorbar:
        if colorbar_ticklabel_format is not None:
            if isinstance(colorbar_ticklabel_format, (str, native_str)):
                formatter = FormatStrFormatter(colorbar_ticklabel_format)
            elif hasattr(colorbar_ticklabel_format, '__call__'):
                formatter = FuncFormatter(colorbar_ticklabel_format)
            elif isinstance(colorbar_ticklabel_format, Formatter):
                formatter = colorbar_ticklabel_format
            locator = MaxNLocator(5)
        else:
            if datetimeplot:
                locator = AutoDateLocator()
                formatter = AutoDateFormatter(locator)
                # Compat with old matplotlib versions.
                if hasattr(formatter, "scaled"):
                    formatter.scaled[1 / (24. * 60.)] = '%H:%M:%S'
            else:
                locator = None
                formatter = None
        cb = Colorbar(cm_ax,
                      scatter,
                      cmap=colormap,
                      orientation='horizontal',
                      ticks=locator,
                      format=formatter)
        # Compat with old matplotlib versions.
        if hasattr(cb, "update_ticks"):
            cb.update_ticks()

    if show:
        plt.show()

    return fig
            plt.plot([startx, startx + 35000], [starty, starty],
                     'k',
                     linewidth=3)
            plt.text(startx + 17500,
                     starty - 12000,
                     '35 km',
                     fontsize=fontsize,
                     ha='center',
                     va='center')

        #deal with colorbars
        if ((filenum == 1) & (i == 0)):  # plot first color bar in row 1
            colorax = plt.subplot(gs[1, rowscale])
            colorbar1 = Colorbar(ax=colorax,
                                 mappable=cs,
                                 orientation='horizontal',
                                 ticklocation='bottom',
                                 ticks=[0.2, 0.5, 0.8])
            colorbar1.ax.tick_params(labelsize=fontsize)
            clabel = '$\mathrm{sig}(\mathrm{a}\Delta \mathrm{CFS}-\mathrm{b})$'
            colorbar1.set_label(clabel, size=fontsize)
            pos = colorax.get_position()  # get the original position
            colorax.set_position(
                [pos.x0, pos.y0 + 0.017, pos.width, pos.height])
        if ((filenum == 1) & (i == 1)):  # plot first color bar in row 3
            colorax = plt.subplot(gs[i * 2 + 1, filenum * rowscale])
            colorbar2 = Colorbar(ax=colorax,
                                 mappable=cs,
                                 orientation='horizontal',
                                 ticklocation='bottom',
                                 ticks=[0.2, 0.5, 0.8])