コード例 #1
0
ファイル: colorbar.py プロジェクト: gemmaguest/mantid
    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()
コード例 #2
0
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()
コード例 #3
0
ファイル: plot.py プロジェクト: 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
コード例 #4
0
ファイル: plot.py プロジェクト: chrisjonesBSU/freud
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
コード例 #5
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
コード例 #6
0
ファイル: ctaging.py プロジェクト: dguest/tagging-performance
def draw_ctag_ratio(in_file, out_dir, ext='.pdf', **opts):
    """
    Heat map showing efficiency ratio gaia and some other tagger.
    Makes iso-efficiency contours for gaia.

    misc options:
      tagger
      tagger_disp (for display)
      vmax
    """
    options = {'tagger':'jfc', 'tagger_disp':'JetFitterCharm', 'vmax':1.2,
               'num_tagger':'gaia', 'num_tagger_disp':None,
               'textsize':_text_size}
    for key, val in opts.items():
        if not key in options:
            raise TypeError("{} not a valid arg".format(key))
        options[key] = val

    fig = Figure(figsize=_fig_size)
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(1,1,1)
    ds = in_file['{}/all'.format(options['num_tagger'])]
    ds_denom = in_file['{}/all'.format(options['tagger'])]

    eff_array, extent = _get_arr_extent(ds)
    denom_array, denom_extent = _get_arr_extent(ds_denom)
    ratio_array = eff_array / denom_array
    im = ax.imshow(ratio_array.T, extent=extent,
                   origin='lower', aspect='auto',
                   vmin=1.0, vmax=options['vmax'])

    textsize = options['textsize']
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    cb = Colorbar(ax=cax, mappable=im)
    cb.set_label('$\epsilon_{{c}}$ ratio ({} / {})'.format(
            options['num_tagger_disp'] or options['num_tagger'].upper(),
            options['tagger_disp']), size=textsize)
    cb.ax.tick_params(labelsize=textsize, which='both')

    label_rejrej_axes(ax, ds, textsize=textsize)
    _add_eq_contour(ax, ds, ds_denom, colorbar=cb)
    add_contour(ax,ds, opts=dict(textsize=textsize))

    out_name = '{}/ctag-2d-{}-vs-{}{}'.format(
        out_dir, options['num_tagger'], options['tagger'], ext)
    # ignore complaints about not being able to log scale images
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        canvas.print_figure(out_name, bbox_inches='tight')
コード例 #7
0
ファイル: test_colorbar.py プロジェクト: lukelbd/matplotlib
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
コード例 #8
0
ファイル: test_colorbar.py プロジェクト: lukelbd/matplotlib
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
コード例 #9
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
コード例 #10
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
コード例 #11
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
コード例 #12
0
def draw_ctag_ratio(in_file, out_dir, ext='.pdf', **opts): 
    """
    misc options: 
      tagger
      tagger_disp (for display)
      vmax
    """
    options = {'tagger':'jfc', 'tagger_disp':'JetFitterCharm', 'vmax':1.2}
    for key, val in opts.items(): 
        if not key in options: 
            raise TypeError("{} not a valid arg".format(key))
        options[key] = val

    fig = Figure(figsize=(8,6))
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(1,1,1)
    ds = in_file['gaia/all']
    ds_denom = in_file['{}/all'.format(options['tagger'])]

    eff_array, extent = _get_arr_extent(ds)
    denom_array, denom_extent = _get_arr_extent(ds_denom)
    ratio_array = eff_array / denom_array
    im = ax.imshow(ratio_array.T, extent=extent, 
                   origin='lower', aspect='auto', 
                   vmin=1.0, vmax=options['vmax'])
    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.grid(which='both')

    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    cb = Colorbar(ax=cax, mappable=im)
    cb.set_label('$\epsilon_{{c}}$ ratio (GAIA / {})'.format(
            options['tagger_disp']))

    _label_axes(ax, ds)
    _add_eq_contour(ax, ds, ds_denom, colorbar=cb)
    _add_contour(ax,ds)

    out_name = '{}/rejrej-ratio-{}{}'.format(
        out_dir, options['tagger'], ext)
    # ignore complaints about not being able to log scale images
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        canvas.print_figure(out_name, bbox_inches='tight')
コード例 #13
0
ファイル: colorbar.py プロジェクト: mantidproject/mantid
 def set_mappable(self, mappable):
     """
     When a new plot is created this method should be called with the new mappable
     """
     self.ax.clear()
     self.colorbar = Colorbar(ax=self.ax, mappable=mappable)
     self.cmin_value, self.cmax_value = self.colorbar.get_clim()
     self.update_clim_text()
     self.redraw()
コード例 #14
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()
コード例 #15
0
ファイル: gui.py プロジェクト: MonaNis/NanoObjectDetection
    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()
コード例 #16
0
ファイル: plot.py プロジェクト: 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
コード例 #17
0
ファイル: colorbar.py プロジェクト: ethoeng/mantid
    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()
コード例 #18
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
コード例 #19
0
ファイル: vertical.py プロジェクト: seventyxseven/gql
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()
コード例 #20
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
コード例 #21
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)
コード例 #22
0
ファイル: BRAG_figures.py プロジェクト: channsoden/BRAG
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)
コード例 #23
0
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()
コード例 #24
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']
コード例 #25
0
ファイル: pyqz_plots.py プロジェクト: fpavogt/pyqz
def plot_grid(ratios, coeffs = [[1,0],[0,1]],
              Pk = 5.0, kappa=np.inf, struct = 'pp', sampling = 1,
              color_mode = 'Tot[O]+12', figname = None, show_plot = True,
              data = None, interp_data = None):
    '''
    Creates the diagram of a given line ratio grid for rapid inspection, including wraps
    (fold-over regions), and of certain line ratios, if "data" is specified.
        
    :Args:
        ratios: string 
                The line ratios defining the grid, e.g. '[NII]/[SII]+;[OIII]/Hb'
        coeffs: list of list [default: [[1,0],[0,1]] ]
                The different coefficients with which to mix the line ratios. 
                The size of each sub-list must be equal to the number of line ratios 
                involved. Used for projected 3D diagnostic grids.
        Pk: float [default: 5.0] 
            MAPPINGS model pressure. This value must match an existing grid file.
        kappa: float [default: np.inf 
               The kappa value. This value must match an existing grid file.
        struct: string [default: 'pp']
                spherical ('sph') or plane-parallel ('pp') HII regions. This value 
                must match an existing reference grid file.
        sampling: int [default: 1]
                  Use a resampled grid ?
        color_mode: string [default: 'Tot[O]+12']
                    Color the grid according to 'Tot[O]+12', 'gas[O]+12' or 'LogQ'.    
        figname: string [default: None]
                  'path+name+format' to save the Figure to.
        show_plot: bool [default: True]
                  Do you want to display the Figure ?
        data: list of numpy array [default: None]
              List of Arrays of the line ratio values. One array per line ratio.
        interp_data: numpy array [default: 'linear']
                     interpolated line ratios (via pyqz.interp_qz)
   ''' 

    # 0) Let's get the data in question
    [grid, grid_cols, metadata] = pyqz.get_grid(ratios, coeffs=coeffs, Pk=Pk, kappa=kappa,     
                                                struct=struct, sampling = sampling)
                                            
    # 1) What are the bad segments in this grid ?
    bad_segs = pyqz.check_grid(ratios, coeffs=coeffs, Pk = Pk, kappa=kappa, struct=struct, 
                               sampling = sampling)                  
                                     
    # 2) Start the plotting
    fig = plt.figure(figsize=(10,8))
    
    gs = gridspec.GridSpec(1,2, height_ratios=[1], width_ratios=[1,0.05])
    gs.update(left=0.14,right=0.88,bottom=0.14,top=0.92,
                wspace=0.1,hspace=0.1)    
    ax1 = fig.add_subplot(gs[0,0])  

    if not(color_mode in grid_cols):
        sys.exit('color_mode unknown: %s' % color_mode)

    # 2) Plot the grid points 
    # Let's make the distinction between the 'TRUE' MAPPINGS point, 
    # and those that were interpolated in a finer grid using Akima splines
    pts = ax1.scatter(grid[:,grid_cols.index('Mix_x')],
                      grid[:,grid_cols.index('Mix_y')],
                      marker='o',
                      c=grid[:,grid_cols.index(color_mode)],
                      s=30, cmap=pyqz_cmap_0, edgecolor='none', 
                      vmin=np.min(grid[:,grid_cols.index(color_mode)]), 
                      vmax=np.max(grid[:,grid_cols.index(color_mode)]), 
                      zorder=3)
           
    # Now mark the "original" points with a black outline. First, which are they ?
    if sampling > 1:
        origin_cond = [n for n in range(len(grid)) if 
                         (grid[n,metadata['columns'].index('LogQ')] in 
                                                      metadata['resampled']['LogQ']) and 
                         (grid[n,metadata['columns'].index('Tot[O]+12')] in 
                                                      metadata['resampled']['Tot[O]+12'])]
    else:
        origin_cond = [n for n in range(len(grid))]
    
    # Now plot the black outlines.
    original_pts = ax1.scatter(grid[origin_cond, grid_cols.index('Mix_x')],
                               grid[origin_cond, grid_cols.index('Mix_y')],
                               marker='o',
                               c=grid[origin_cond, grid_cols.index(color_mode)],
                               s=60, cmap=pyqz_cmap_0, edgecolor='k', facecolor='white',
                               vmin=np.min(grid[:,grid_cols.index(color_mode)]), 
                               vmax=np.max(grid[:,grid_cols.index(color_mode)]), 
                               zorder=5)          


    # 2-1) Draw the grid lines
    # Check as a function of LogQ and Tot[O]+12. Where are these ?
    u = grid_cols.index('LogQ')
    v = grid_cols.index('Tot[O]+12')

    for i in [u,v]:  
        # Here, 'var' plays the role of 'q' or 'z' depending on 'i'.
        for var in np.unique(grid[:,i]):
            # Plot the grid line
            ax1.plot(grid[grid[:,i]==var][:,grid_cols.index('Mix_x')],
                            grid[grid[:,i]==var][:,grid_cols.index('Mix_y')],
                            'k-', lw = 1, zorder=1)
                            
    # Plot the bad segments
    for bad_seg in bad_segs:
        ax1.plot([bad_seg[0][0],bad_seg[1][0]],[bad_seg[0][1],bad_seg[1][1]],  'r-',
                 linewidth=4, zorder=0)
                            
    # Now, also plot the data, if anything was provided !             
    if not(interp_data is None):
        
        # Compute the combined "observed" ratios
        data_comb = [np.zeros_like(data[0]),np.zeros_like(data[1])]    
        for k in range(len(ratios.split(';'))): 
            data_comb[0] += coeffs[0][k]*data[k]
            data_comb[1] += coeffs[1][k]*data[k]
        
        ax1.scatter(data_comb[0][interp_data == interp_data], 
                    data_comb[1][interp_data == interp_data],
                    marker='s', c=interp_data[interp_data == interp_data],
                    s=15, cmap = pyqz_cmap_0, edgecolor='k',
                    vmin = np.min(grid[:,grid_cols.index(color_mode)]),
                    vmax = np.max(grid[:,grid_cols.index(color_mode)]),
                    zorder=2, alpha=0.35)

        # Plot also the points outside the grid ?
        # Which are they ? Need to check if they have a valid input first !
        # mind the "~" to invert the bools ! isn't this cool ?
        my_out_pts = ~np.isnan(data_comb[0]) * ~np.isnan(data_comb[1]) * \
            np.isnan(interp_data)
  
        # Don't do this if this is a test with fullgrid_x ...
        ax1.scatter(data_comb[0][my_out_pts], data_comb[1][my_out_pts],
                    marker = '^', facecolor = 'none', edgecolor = 'k', s=60)           
                               
    # 3) Plot the colorbar
    cb_ax = plt.subplot(gs[0,1])
    cb = Colorbar(ax = cb_ax, mappable = pts, orientation='vertical')
        
    # Colorbar legend
    cb.set_label(color_mode, labelpad = 10)
        
    # 4) Axis names, kappa value, etc ...
    rats = ratios.split(';')
    # Make sure the labels look pretty in ALL cases ...
    labelx,labely = get_plot_labels(rats,coeffs)
                                                  
    ax1.set_xlabel(labelx,labelpad = 10)
    ax1.set_ylabel(labely,labelpad = 10)
        
    if not(kappa in [np.inf, 'inf']) :
        kappa_str = r'$\kappa$ = '+str(kappa)    
    else :
        kappa_str = r'$\kappa$ = $\infty$'
        
    ax1.text(0.85,0.9,kappa_str, horizontalalignment='left',verticalalignment='bottom',
             transform=ax1.transAxes)
    ax1.grid(True)
        
    if figname :
        fig.savefig(figname, bbox_inches='tight')
    if show_plot:
        plt.show()
    else:
        plt.close()
コード例 #26
0
ファイル: S7_R2_maps.py プロジェクト: ndadap/sm-ba-peatlands
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()

コード例 #27
0
ファイル: rejrej.py プロジェクト: dguest/JetFitter-Training
def _overlay_rejrej(array_one, array_two,
                    out_name = 'rejrej.pdf', 
                    do_rel = False, 
                    do_contour = False, 
                    do_abs_contour = False, 
                    do_equal_contour = False, 
                    z_range = None, 
                    extra_cuts=[]):     

    if do_contour and do_abs_contour: 
        warnings.warn("can't do both abs_contour and contour, "
                      "won't use abs_contour")
        do_abs_contour = False


    array_one['eff'] = _maximize_efficiency(array_one['eff'])
    array_two['eff'] = _maximize_efficiency(array_two['eff'])

    arrays = array_one, array_two

    
    # pretty sure the 'nonzero' calls here aren't needed (bool array returned
    # by the inequality should work)
    array_one['eff'][np.nonzero(array_one['eff'] <= 0.0)] = np.NaN
    array_two['eff'][np.nonzero(array_two['eff'] <= 0.0)] = np.NaN

        
    if do_rel: 
        old_warn_set = np.seterr(divide = 'ignore') 
        eff_array = array_one['eff'] / array_two['eff']
        np.seterr(**old_warn_set)
    else: 
        eff_array = array_one['eff'] - array_two['eff']


    for a in arrays: 
        if not 'tagger' in a: 
            warnings.warn('no tagger name given',stacklevel = 2)
            a['tagger'] = 'unknown'

    if _get_rel_plot_alignment(array_one, array_two) > 1e-6: 
        ranges = [(p['x_range'], p['y_range']) for p in arrays]
        raise ValueError("ranges {} don't match {}".format(*ranges))

    if not _check_sig_bg_match(*arrays): 
        err = 'array mismatch ---'
        for a in arrays: 
            err += 'sig: {signal}, bgx: {x_bg}, bgy: {y_bg} '.format(**a)
        raise ValueError(err)

    x_min, x_max = array_one['x_range']
    y_min, y_max = array_one['y_range']

    fig = plt.figure()
    gs = GridSpec(20,21)
    ax = plt.subplot(gs[:,0:-1])
    aspect = float(x_max - x_min) / (y_max - y_min)

    # cmap = mp.colors.Colormap('rainbow')

    rel_min = np.min(eff_array[np.isfinite(eff_array)])
    rel_max = np.max(eff_array[np.isfinite(eff_array)]) 
    if z_range: 
        rel_min, rel_max = z_range

    if do_abs_contour: 
        contour_array = array_one['eff']
        signal = array_one['signal']
        contour_range = (0,0.5) if signal == 'charm' else (0.5,1)
    else: 
        contour_array = eff_array
        contour_range = (rel_min, rel_max)

    contour_order, c_lines = _get_contour_order_and_lines(contour_range)

    print 'plot range: {: .2f}--{:.2f}'.format(
        rel_min, rel_max)

    im = ax.imshow(
        eff_array, 
        origin = 'upper', 
        extent = (x_min,x_max, y_min, y_max), 
        aspect = aspect, 
        interpolation = 'nearest', 
        vmin = rel_min, 
        vmax = rel_max, 
        )


    if len(c_lines) == 0: 
        do_contour = False
    if do_contour or do_abs_contour: 
        ct = ax.contour(
            contour_array, 
            origin = 'upper', 
            extent = (x_min,x_max, y_min, y_max), 
            aspect = aspect, 
            linewidths = 2, 
            levels = c_lines,
            colors = 'k', 
            )
        plt.clabel(ct, fontsize=12, inline=1, 
                   fmt = '%.{}f'.format(-contour_order + 1 ))

    equal_contour_level = 1.0 if do_rel else 0.0
    if do_equal_contour: 
        equal_ct = ax.contour(
            eff_array, 
            origin = 'upper', 
            extent = (x_min,x_max, y_min, y_max), 
            aspect = aspect, 
            linewidths = 2, 
            levels = [equal_contour_level],
            colors = 'r', 
            )
        plt.clabel(equal_ct, fontsize=9, inline=True, 
                   fmt={equal_contour_level:'equal'})

    im.get_cmap().set_bad(alpha=0)

    ax.set_xticks([])
    ax.set_yticks([])
    ax.invert_yaxis()

    cb_ax = plt.subplot(gs[:,-1])
    plt.subplots_adjust(left = 0.25) # FIXME: use OO call here
    # cb = plt.colorbar()
    cb = Colorbar(ax = cb_ax, mappable = im)
    taggers = [_simplify_tagger_name(x) for x in arrays]
    flav_char = _flav_to_char[array_one['signal']]
    sig_label = '$\epsilon_\mathrm{{ {} }}$'.format(flav_char)
    cb_lab_string = '{} $/$ {} {s}' if do_rel else '{} $-$ {} {s}'
    cb.set_label(cb_lab_string.format(*taggers, s = sig_label ))
    if do_contour: 
        cb.add_lines(ct)
        
    if do_equal_contour: 
        if rel_min < equal_contour_level < rel_max: 
            cb.add_lines(equal_ct)

    position = ax.get_position()
    new_aspect = ax.get_aspect()
    # ax.set_position(position)
        

    ax_log = fig.add_subplot(111, frameon = False)
    ax_log.set_xscale('log')
    ax_log.set_yscale('log')
    ax_log.axis((10**x_min, 10**x_max, 10**y_min, 10**y_max))
    ax_log.set_aspect(aspect)
    ax_log.set_xlabel('{} rejection'.format(array_one['x_bg']))
    ax_log.set_ylabel('{} rejection'.format(array_one['y_bg']))
    ax_log.grid(True)

    cuts_to_display = array_one['cuts_to_display'] 
    for cut in extra_cuts:
        cut.point_type = 'wo'
        cuts_to_display.append(cut)

    for cut in cuts_to_display:
        x, y, z = cut.xyz
        # print cut.xyz
        ax_log.plot([x],[y],cut.point_type)
        fmt_dict = dict(cut1=cut.cut1, cut2=cut.cut2, eff=z)
        ax_log.annotate(cut.plot_string.format(**fmt_dict), (x,y), 
                        **cut.ann_opts)

    ax_log.set_aspect(new_aspect)
    ax_log.set_position(position)
            
    plt.savefig(out_name, bbox_inches = 'tight')
    plt.close()
コード例 #28
0
ax0 = pp.subplot(gs[0, 0:10])
ax1 = pp.subplot(gs[0, 12:22])
cb_ax = pp.subplot(gs[0,-1])

ax0.set_title('Base System Transition Matrix')
im = ax0.imshow(base_transition_matrix, interpolation='nearest', origin='lower',
                vmin=0, vmax=1, cmap='gist_earth')
ax0.set_xlabel('State [index]')
ax0.set_ylabel('State [index]')


ax1.set_title('Mutant Transition Matrix')
im = ax1.imshow(sampling['transition_matrix'], interpolation='nearest',
                origin='lower', vmin=0, vmax=1, cmap='gist_earth')
ax1.set_xlabel('State [index]')
ax1.set_ylabel('State [index]')

cb = Colorbar(ax = cb_ax, mappable = im) # use the raw colorbar constructor
cb.set_label('Transition Probability')
cb.set_ticks([0, 0.25, 0.5, 0.75, 1.0])

#cb = Colorbar(ax=pp.subplot(gs[1, -1]), mappable=lower)
#cb.set_ticks(np.asarray(np.unique(trajectory), dtype=int))
#cb.set_label('state')

sampling.close()
print 'saving figure as %s' % plot_fn
pp.savefig(plot_fn)

if sys.platform == 'darwin':
    os.system('open %s' % plot_fn)
コード例 #29
0
ファイル: maps.py プロジェクト: johjam/obspy
def plot_basemap(
    lons,
    lats,
    size,
    color,
    labels=None,
    projection="cyl",
    resolution="l",
    continent_fill_color="0.8",
    water_fill_color="1.0",
    colormap=None,
    marker="o",
    title=None,
    colorbar_ticklabel_format=None,
    show=True,
    **kwargs
):  # @UnusedVariable
    """
    Creates a basemap 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: list/tuple of floats (or a single float)
    :param size: Size of the individual points in the scatter plot.
    :type color: list/tuple of
        floats/:class:`~obspy.core.utcdatetime.UTCDateTime` (or a single float)
    :param color: Color information of the individual data points. Can be
    :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
        * ``"cyl"`` (Will plot the whole world.)
        * ``"ortho"`` (Will center around the mean lat/long.)
        * ``"local"`` (Will plot around local events)
        Defaults to "cyl"
    :type resolution: str, optional
    :param resolution: Resolution of the boundary database to use. Will be
        based directly to the basemap module. Possible values are
        * ``"c"`` (crude)
        * ``"l"`` (low)
        * ``"i"`` (intermediate)
        * ``"h"`` (high)
        * ``"f"`` (full)
        Defaults to ``"l"``
    :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, optional, any matplotlib colormap
    :param colormap: The colormap for color-coding the events.
        The event with the smallest property will have the
        color of one end of the colormap and the event with the biggest
        property the color of the other end with all other events in
        between.
        Defaults to None which will use the default colormap for the date
        encoding and a colormap going from green over yellow to red for the
        depth encoding.
    :type title: str
    :param title: Title above plot.
    :type colorbar_ticklabel_format: str or func or
        subclass of :matplotlib:`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.
    """
    min_color = min(color)
    max_color = max(color)

    if isinstance(color[0], (datetime.datetime, UTCDateTime)):
        datetimeplot = True
        color = [date2num(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 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
    else:
        ax_x0, ax_width = 0.05, 0.90

    if show_colorbar:
        map_ax = fig.add_axes([ax_x0, 0.13, ax_width, 0.77])
        cm_ax = fig.add_axes([ax_x0, 0.05, ax_width, 0.05])
        plt.sca(map_ax)
    else:
        map_ax = fig.add_axes([ax_x0, 0.05, ax_width, 0.85])

    if projection == "cyl":
        bmap = Basemap(resolution=resolution)
    elif projection == "ortho":
        bmap = Basemap(
            projection="ortho", resolution=resolution, area_thresh=1000.0, lat_0=np.mean(lats), lon_0=np.mean(lons)
        )
    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) + min(lats)) / 2.0
        lon_0 = (max_lons + min_lons) / 2.0
        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

        bmap = Basemap(
            projection="aeqd",
            resolution=resolution,
            area_thresh=1000.0,
            lat_0=lat_0,
            lon_0=lon_0,
            width=width,
            height=height,
        )
        # not most elegant way to calculate some round lats/lons

        def linspace2(val1, val2, N):
            """
            returns around N 'nice' values between val1 and val2
            """
            dval = val2 - val1
            round_pos = int(round(-np.log10(1.0 * dval / N)))
            delta = round(2.0 * dval / N, round_pos) / 2
            new_val1 = np.ceil(val1 / delta) * delta
            new_val2 = np.floor(val2 / delta) * delta
            N = (new_val2 - new_val1) / delta + 1
            return np.linspace(new_val1, new_val2, N)

        N1 = int(np.ceil(height / max(width, height) * 8))
        N2 = int(np.ceil(width / max(width, height) * 8))
        bmap.drawparallels(
            linspace2(lat_0 - height / 2 / deg2m_lat, lat_0 + height / 2 / deg2m_lat, N1), labels=[0, 1, 1, 0]
        )
        if min(lons) < -150 and max(lons) > 150:
            lon_0 %= 360
        meridians = linspace2(lon_0 - width / 2 / deg2m_lon, lon_0 + width / 2 / deg2m_lon, N2)
        meridians[meridians > 180] -= 360
        bmap.drawmeridians(meridians, labels=[1, 0, 0, 1])
    else:
        msg = "Projection '%s' not supported." % projection
        raise ValueError(msg)

    # draw coast lines, country boundaries, fill continents.
    plt.gca().set_axis_bgcolor(water_fill_color)
    bmap.drawcoastlines(color="0.4")
    bmap.drawcountries(color="0.75")
    bmap.fillcontinents(color=continent_fill_color, lake_color=water_fill_color)
    # draw the edge of the bmap projection region (the projection limb)
    bmap.drawmapboundary(fill_color=water_fill_color)
    # draw lat/lon grid lines every 30 degrees.
    bmap.drawmeridians(np.arange(-180, 180, 30))
    bmap.drawparallels(np.arange(-90, 90, 30))

    # compute the native bmap projection coordinates for events.
    x, y = bmap(lons, lats)
    # plot labels
    if labels:
        if 100 > len(lons) > 1:
            for name, xpt, ypt, colorpt in zip(labels, x, y, color):
                # Check if the point can actually be seen with the current bmap
                # projection. The bmap object will set the coordinates to very
                # large values if it cannot project a point.
                if xpt > 1e25:
                    continue
                plt.text(
                    xpt,
                    ypt,
                    name,
                    weight="heavy",
                    color="k",
                    zorder=100,
                    path_effects=[PathEffects.withStroke(linewidth=3, foreground="white")],
                )
        elif len(lons) == 1:
            plt.text(
                x[0],
                y[0],
                labels[0],
                weight="heavy",
                color="k",
                path_effects=[PathEffects.withStroke(linewidth=3, foreground="white")],
            )

    scatter = bmap.scatter(x, y, marker=marker, s=size, c=color, zorder=10, cmap=colormap)

    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)
                formatter.scaled[1 / (24.0 * 60.0)] = "%H:%M:%S"
            else:
                locator = None
                formatter = None
        cb = Colorbar(cm_ax, scatter, cmap=colormap, orientation="horizontal", ticks=locator, format=formatter)
        # format=formatter)
        # ticks=mpl.ticker.MaxNLocator(4))
        cb.update_ticks()

    if show:
        plt.show()

    return fig
コード例 #30
0
def test_colorbarbase():
    # smoke test from #3805
    ax = plt.gca()
    Colorbar(ax, cmap=plt.cm.bone)
コード例 #31
0
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()
コード例 #32
0
ファイル: maps.py プロジェクト: Brtle/obspy
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

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

    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'] = mean_longitude(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_kwargs['standard_parallels'] = [lat_0, lat_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'] = mean_longitude(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.
    if MATPLOTLIB_VERSION >= [2, 0, 0]:
        map_ax.set_facecolor(water_fill_color)
    else:
        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
コード例 #33
0
ファイル: maps.py プロジェクト: 3rdcycle/obspy
def plot_basemap(lons, lats, size, color, labels=None, projection='global',
                 resolution='l', continent_fill_color='0.8',
                 water_fill_color='1.0', colormap=None, colorbar=None,
                 marker="o", title=None, colorbar_ticklabel_format=None,
                 show=True, **kwargs):  # @UnusedVariable
    """
    Creates a basemap 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.)
        * ``"ortho"`` (Will center around the mean lat/long.)
        * ``"local"`` (Will plot around local events)
        Defaults to "global"
    :type resolution: str, optional
    :param resolution: Resolution of the boundary database to use. Will be
        based directly to the basemap module. Possible values are
        * ``"c"`` (crude)
        * ``"l"`` (low)
        * ``"i"`` (intermediate)
        * ``"h"`` (high)
        * ``"f"`` (full)
        Defaults to ``"l"``. For compatibility, you may also specify any of the
        Cartopy resolutions defined in :func:`plot_cartopy`.
    :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.
    """
    min_color = min(color)
    max_color = max(color)

    if any([isinstance(c, (datetime.datetime, UTCDateTime)) for c in color]):
        datetimeplot = True
        color = [np.isfinite(float(t)) and date2num(t) or np.nan
                 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

    if show_colorbar:
        map_ax = fig.add_axes([ax_x0, 0.13, ax_width, 0.77])
        cm_ax = fig.add_axes([ax_x0, 0.05, ax_width, 0.05])
    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])

    if projection == 'global':
        bmap = Basemap(projection='moll', lon_0=round(np.mean(lons), 4),
                       resolution=_BASEMAP_RESOLUTIONS[resolution], ax=map_ax)
    elif projection == 'ortho':
        bmap = Basemap(projection='ortho',
                       resolution=_BASEMAP_RESOLUTIONS[resolution],
                       area_thresh=1000.0, lat_0=round(np.mean(lats), 4),
                       lon_0=round(np.mean(lons), 4), ax=map_ax)
    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

        bmap = Basemap(projection='aea',
                       resolution=_BASEMAP_RESOLUTIONS[resolution],
                       area_thresh=1000.0, lat_0=round(lat_0, 4),
                       lon_0=round(lon_0, 4),
                       width=width, height=height, ax=map_ax)
        # not most elegant way to calculate some round lats/lons

        def linspace2(val1, val2, N):
            """
            returns around N 'nice' values between val1 and val2
            """
            dval = val2 - val1
            round_pos = int(round(-np.log10(1. * dval / N)))
            # Fake negative rounding as not supported by future as of now.
            if round_pos < 0:
                factor = 10 ** (abs(round_pos))
                delta = round(2. * dval / N / factor) * factor / 2
            else:
                delta = round(2. * dval / N, round_pos) / 2
            new_val1 = np.ceil(val1 / delta) * delta
            new_val2 = np.floor(val2 / delta) * delta
            N = (new_val2 - new_val1) / delta + 1
            return np.linspace(new_val1, new_val2, N)

        N1 = int(np.ceil(height / max(width, height) * 8))
        N2 = int(np.ceil(width / max(width, height) * 8))
        parallels = linspace2(lat_0 - height / 2 / deg2m_lat,
                              lat_0 + height / 2 / deg2m_lat, N1)

        # Old basemap versions have problems with non-integer parallels.
        try:
            bmap.drawparallels(parallels, labels=[0, 1, 1, 0])
        except KeyError:
            parallels = sorted(list(set(map(int, parallels))))
            bmap.drawparallels(parallels, labels=[0, 1, 1, 0])

        if min(lons) < -150 and max(lons) > 150:
            lon_0 %= 360
        meridians = linspace2(lon_0 - width / 2 / deg2m_lon,
                              lon_0 + width / 2 / deg2m_lon, N2)
        meridians[meridians > 180] -= 360
        bmap.drawmeridians(meridians, labels=[1, 0, 0, 1])
    else:
        msg = "Projection '%s' not supported." % projection
        raise ValueError(msg)

    # draw coast lines, country boundaries, fill continents.
    map_ax.set_axis_bgcolor(water_fill_color)
    bmap.drawcoastlines(color="0.4")
    bmap.drawcountries(color="0.75")
    bmap.fillcontinents(color=continent_fill_color,
                        lake_color=water_fill_color)
    # draw the edge of the bmap projection region (the projection limb)
    bmap.drawmapboundary(fill_color=water_fill_color)
    # draw lat/lon grid lines every 30 degrees.
    bmap.drawmeridians(np.arange(-180, 180, 30))
    bmap.drawparallels(np.arange(-90, 90, 30))

    # compute the native bmap projection coordinates for events.
    x, y = bmap(lons, lats)
    # plot labels
    if labels:
        if 100 > len(lons) > 1:
            for name, xpt, ypt, _colorpt in zip(labels, x, y, color):
                # Check if the point can actually be seen with the current bmap
                # projection. The bmap object will set the coordinates to very
                # large values if it cannot project a point.
                if xpt > 1e25:
                    continue
                map_ax.text(xpt, ypt, name, weight="heavy",
                            color="k", zorder=100,
                            path_effects=[
                                PathEffects.withStroke(linewidth=3,
                                                       foreground="white")])
        elif len(lons) == 1:
            map_ax.text(x[0], y[0], labels[0], weight="heavy", color="k",
                        path_effects=[
                            PathEffects.withStroke(linewidth=3,
                                                   foreground="white")])

    # scatter plot is removing valid x/y points with invalid color value,
    # so we plot those points separately.
    try:
        nan_points = np.isnan(np.array(color, dtype=np.float))
    except ValueError:
        # `color' was not a list of values, but a list of colors.
        pass
    else:
        if nan_points.any():
            x_ = np.array(x)[nan_points]
            y_ = np.array(y)[nan_points]
            size_ = np.array(size)[nan_points]
            scatter = bmap.scatter(x_, y_, marker=marker, s=size_, c="0.3",
                                   zorder=10, cmap=None)
    scatter = bmap.scatter(x, y, marker=marker, s=size, c=color,
                           zorder=10, cmap=colormap)

    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
コード例 #34
0
ファイル: plot.py プロジェクト: chrisjonesBSU/freud
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
コード例 #35
0
ファイル: plotting.py プロジェクト: seismology/stfinv
def add_ortho(lats, lons, colors, CClim,
              central_longitude, central_latitude,
              text=None, size=50, marker=['o', 'd'],
              colormap='viridis', fig=None,
              rect=[0.0, 0.0, 1.0, 1.0]):
    if not fig:
        fig = plt.figure()

    proj = ccrs.Orthographic(central_longitude=central_longitude,
                             central_latitude=central_latitude)

    # left, bottom, width, height
    ax = fig.add_axes([rect[0],
                       rect[1] + rect[3] * 0.12,
                       rect[2],
                       rect[3] * 0.85],
                      projection=proj)
    cm_ax = fig.add_axes([rect[0],
                          rect[1],
                          rect[2],
                          rect[3] * 0.08])
    plt.sca(ax)

    # make the map global rather than have it zoom in to
    # the extents of any plotted data
    ax.set_global()

    ax.stock_img()
    ax.coastlines()
    ax.gridlines()

    lats_mark1 = []
    lons_mark1 = []
    colors_mark1 = []
    lats_mark2 = []
    lons_mark2 = []
    colors_mark2 = []

    cmap = get_cmap(colormap)
    cmap.set_under('grey')

    for lon, lat, color in zip(lons, lats, colors):
        if color > CClim:
            lats_mark1.append(lat)
            lons_mark1.append(lon)
            colors_mark1.append(color)
        else:
            lats_mark2.append(lat)
            lons_mark2.append(lon)
            colors_mark2.append(color)

    if len(lons_mark1) > 0:
        scatter = ax.scatter(lons_mark1, lats_mark1, s=size, c=colors_mark1,
                             marker=marker[0],
                             cmap=cmap, vmin=CClim, vmax=1, zorder=10,
                             transform=ccrs.Geodetic())

    if len(lons_mark2) > 0:
        scatter = ax.scatter(lons_mark2, lats_mark2, s=size, c=colors_mark2,
                             marker=marker[1],
                             cmap=cmap, vmin=CClim, vmax=1, zorder=10,
                             transform=ccrs.Geodetic())

    locator = MaxNLocator(5)

    cb = Colorbar(cm_ax, scatter, cmap=cmap,
                  orientation='horizontal',
                  ticks=locator,
                  extend='min')
    cb.set_label('CC')
    # Compat with old matplotlib versions.
    if hasattr(cb, "update_ticks"):
        cb.update_ticks()

    ax.plot(central_longitude, central_latitude, color='red', marker='*',
            markersize=np.sqrt(size))

    if (text):
        for lat, lon, text in zip(lats, lons, text):
            # Avoid plotting invisible texts. They clutter at the origin
            # otherwise
            dist = locations2degrees(lat, lon,
                                     central_latitude, central_longitude)
            if (dist < 90):
                plt.text(lon, lat, text, weight="heavy",
                         transform=ccrs.Geodetic(),
                         color="k", zorder=100,
                         path_effects=[
                             PathEffects.withStroke(linewidth=3,
                                                    foreground="white")])

    return ax
コード例 #36
0
class ColorbarWidget(QWidget):
    colorbarChanged = Signal() # The parent should simply redraw their canvas

    def __init__(self, parent=None):
        super(ColorbarWidget, self).__init__(parent)

        self.setWindowTitle("Colorbar")
        self.setMaximumWidth(200)

        self.cmap = QComboBox()
        self.cmap.addItems(sorted(cm.cmap_d.keys()))
        self.cmap.currentIndexChanged.connect(self.cmap_index_changed)

        self.cmin = QLineEdit()
        self.cmin_value = 0
        self.cmin.setMaximumWidth(100)
        self.cmin.editingFinished.connect(self.clim_changed)
        self.cmin_layout = QHBoxLayout()
        self.cmin_layout.addStretch()
        self.cmin_layout.addWidget(self.cmin)
        self.cmin_layout.addStretch()

        self.cmax = QLineEdit()
        self.cmax_value = 1
        self.cmax.setMaximumWidth(100)
        self.cmax.editingFinished.connect(self.clim_changed)
        self.cmin.setValidator(QDoubleValidator())
        self.cmax.setValidator(QDoubleValidator())
        self.cmax_layout = QHBoxLayout()
        self.cmax_layout.addStretch()
        self.cmax_layout.addWidget(self.cmax)
        self.cmax_layout.addStretch()

        self.norm_layout = QHBoxLayout()
        self.norm = QComboBox()
        self.norm.addItems(NORM_OPTS)
        self.norm.currentIndexChanged.connect(self.norm_changed)

        self.powerscale = QLineEdit()
        self.powerscale_value = 2
        self.powerscale.setText("2")
        self.powerscale.setValidator(QDoubleValidator(0.001,100,3))
        self.powerscale.setMaximumWidth(50)
        self.powerscale.editingFinished.connect(self.norm_changed)
        self.powerscale.hide()
        self.powerscale_label = QLabel("n=")
        self.powerscale_label.hide()

        self.norm_layout.addStretch()
        self.norm_layout.addWidget(self.norm)
        self.norm_layout.addStretch()
        self.norm_layout.addWidget(self.powerscale_label)
        self.norm_layout.addWidget(self.powerscale)

        self.autoscale = QCheckBox("Autoscaling")
        self.autoscale.setChecked(True)
        self.autoscale.stateChanged.connect(self.update_clim)

        self.canvas = FigureCanvas(Figure())
        if parent:
            # Set facecolor to match parent
            self.canvas.figure.set_facecolor(parent.palette().window().color().getRgbF())
        self.ax = self.canvas.figure.add_axes([0.4,0.05,0.2,0.9])

        # layout
        self.layout = QVBoxLayout(self)
        self.layout.addWidget(self.cmap)
        self.layout.addLayout(self.cmax_layout)
        self.layout.addWidget(self.canvas, stretch=1)
        self.layout.addLayout(self.cmin_layout)
        self.layout.addLayout(self.norm_layout)
        self.layout.addWidget(self.autoscale)

    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()

    def cmap_index_changed(self):
        self.cmap_changed(self.cmap.currentText())

    def cmap_changed(self, name):
        self.colorbar.set_cmap(name)
        self.colorbar.mappable.set_cmap(name)
        self.redraw()

    def norm_changed(self):
        """
        Called when a different normalization is selected
        """
        idx = self.norm.currentIndex()
        if NORM_OPTS[idx] == 'Power':
            self.powerscale.show()
            self.powerscale_label.show()
        else:
            self.powerscale.hide()
            self.powerscale_label.hide()
        self.colorbar.mappable.set_norm(self.get_norm())
        self.set_mappable(self.colorbar.mappable)

    def get_norm(self):
        """
        This will create a matplotlib.colors.Normalize from selected idx, limits and powerscale
        """
        idx = self.norm.currentIndex()
        if self.autoscale.isChecked():
            cmin = cmax = None
        else:
            cmin = self.cmin_value
            cmax = self.cmax_value
        if NORM_OPTS[idx] == 'Power':
            if self.powerscale.hasAcceptableInput():
                self.powerscale_value = float(self.powerscale.text())
            return PowerNorm(gamma=self.powerscale_value, vmin=cmin, vmax=cmax)
        elif NORM_OPTS[idx] == "SymmetricLog10":
            return SymLogNorm(1e-8 if cmin is None else max(1e-8, abs(cmin)*1e-3),
                              vmin=cmin, vmax=cmax)
        else:
            return Normalize(vmin=cmin, vmax=cmax)

    def clim_changed(self):
        """
        Called when either the min or max is changed. Will unset the autoscale.
        """
        self.autoscale.blockSignals(True)
        self.autoscale.setChecked(False)
        self.autoscale.blockSignals(False)
        self.update_clim()

    def update_clim(self):
        """
        This will update the clim of the plot based on min, max, and autoscale
        """
        if self.autoscale.isChecked():
            data = self.colorbar.mappable.get_array()
            try:
                try:
                    self.cmin_value = data[~data.mask].min()
                    self.cmax_value = data[~data.mask].max()
                except AttributeError:
                    self.cmin_value = np.nanmin(data)
                    self.cmax_value = np.nanmax(data)
            except (ValueError, RuntimeWarning):
                # all values mask
                pass
            self.update_clim_text()
        else:
            if self.cmin.hasAcceptableInput():
                cmin = float(self.cmin.text())
                if cmin < self.cmax_value:
                    self.cmin_value = cmin
                else: # reset values back
                    self.update_clim_text()
            if self.cmax.hasAcceptableInput():
                cmax = float(self.cmax.text())
                if cmax > self.cmin_value:
                    self.cmax_value = cmax
                else: #reset values back
                    self.update_clim_text()
        self.colorbar.set_clim(self.cmin_value, self.cmax_value)
        self.redraw()

    def update_clim_text(self):
        """
        Update displayed limit values based on stored ones
        """
        self.cmin.setText("{:.4}".format(self.cmin_value))
        self.cmax.setText("{:.4}".format(self.cmax_value))

    def redraw(self):
        """
        Redraws the colobar and emits signal to cause the parent to redraw
        """
        self.colorbar.update_ticks()
        self.colorbar.draw_all()
        self.canvas.draw_idle()
        self.colorbarChanged.emit()
コード例 #37
0
ファイル: spectrogram.py プロジェクト: sunpy/radiospectra
    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
コード例 #38
0
ファイル: pyqz_plots.py プロジェクト: fpavogt/pyqz
def plot_global_qz(pickle_fn, do_all_diags = True, show_plots = True, save_loc = None):
    ''' A plotting function designed to plot the pickle output from pyqz.get_global_qz().
    
    :Args:
        pickel_fn: string
                   the path+filename of the pickle filed to process.
        do_all_diags: bool [default: True]
                      Whether to construct the diagnostic grid plots for all individual
                      diagnostics or not.
        show_plots: bool [default: True]
                    Whether to display the plots or not.
        save_loc: string [default: None][
                  If set, the location where the plots will be saved. If not set, no plots
                  will be saved.
    :Notes: 
        You must set KDE_pickle_loc to the location of your choice when running 
        pyqz.get_global_qz() and pyqz.get_global_qz_ff(), if you want the associated 
        pickle file to be generated.
    '''
    # 0) Open the pickle file, and check what we are dealing with ...
    ftmp = open(pickle_fn,'r')
    KDE_frompickle = pickle.load(ftmp)
    ftmp.close()

    # What will I call my plots ?

    ids = KDE_frompickle['ids']
    Pk = KDE_frompickle['Pk'] 
    kappa = KDE_frompickle['kappa']
    struct = KDE_frompickle['struct']
    sampling = KDE_frompickle['sampling']
    KDE_method = KDE_frompickle['KDE_method']
    
    fn_in = pyqz_tools.get_KDE_picklefn(ids, Pk, kappa, struct, sampling, KDE_method)

    # First things first. Generate the grid plots for all the diagnostics. ---------------
    
    discrete_pdf = KDE_frompickle['discrete_pdf']
    rsf = KDE_frompickle['rsf']
    rsf_keys = KDE_frompickle['rsf_keys']
    
    if do_all_diags:
        for key in discrete_pdf.keys():
    
            # Reconstruct the line flux mix from the raw rsf data
            Rval = []
            for (r,ratio) in enumerate(key.split('|')[0].split(';')):
                l1 = ratio.split('/')[0]
                l2 = ratio.split('/')[1]
            
                Rval.append(np.log10(rsf[:,rsf_keys.index(l1)]/
                                     rsf[:,rsf_keys.index(l2)]))
     
            if save_loc:
                plot_name = os.path.join(save_loc, fn_in[:-4] + '_' + 
                                key.replace('/','-').replace(';','_vs_').replace('|','_')
                                + '.pdf')
            else:
                plot_name = None
            
            plot_grid(key.split('|')[0], 
                      coeffs = diagnostics[key.split('|')[0]]['coeffs'],
                      Pk = Pk, kappa=kappa, struct = struct, sampling = sampling,
                      color_mode = key.split('|')[1], 
                      figname = plot_name, show_plot = show_plots,
                      data = Rval, interp_data = discrete_pdf[key])
                  
    # Let's get started with the KDE plot ------------------------------------------------
    plt.figure(figsize=(13,8))
    gs = gridspec.GridSpec(2,2, height_ratios=[0.05,1.], width_ratios=[1.,1.])
    gs.update(left=0.1, right=0.95, bottom=0.1,top=0.9, wspace=0.15, hspace=0.07 )
    ax1 = plt.subplot(gs[1,0])
    ax2 = plt.subplot(gs[1,1])
    
    # First, the direct estimates --------------------------------------------------------
    qzs = KDE_frompickle['qzs']
    which_grids = KDE_frompickle['which_grids']
    
    # Create an array to keep track of how big my zoom window will be for ax2
    ax2_lims = [np.nan, np.nan, np.nan, np.nan]
    
    for (k,key) in enumerate(discrete_pdf.keys()):
        # Make sure we show each point only once
        if not(qzs[0] in key):
            continue

        # Don't do anything if the point lands outside the plot.
        if np.isnan(discrete_pdf[key][0]):
            continue
        
        this_diag = key.split('|')[0]
            
        for ax in [ax1,ax2]: 
            
            # The individual realizations
            ax.scatter(discrete_pdf[this_diag+'|'+qzs[0]][1:],
                       discrete_pdf[this_diag+'|'+qzs[1]][1:],  
                       c='k', marker = 'o', s = 1, zorder = 2)  
            
            # Update the zoom-window limits if required
            ax2_lims = [np.nanmin(( ax2_lims[0], 
                                np.nanmin(discrete_pdf[this_diag+'|'+qzs[0]][1:])
                              )),
                        np.nanmax(( ax2_lims[1], 
                                np.nanmax(discrete_pdf[this_diag+'|'+qzs[0]][1:])
                              )),
                        np.nanmin(( ax2_lims[2], 
                                np.nanmin(discrete_pdf[this_diag+'|'+qzs[1]][1:])
                              )),
                        np.nanmax(( ax2_lims[3], 
                                np.nanmax(discrete_pdf[this_diag+'|'+qzs[1]][1:])
                              )),
                       ]
                        
            # The direct estimate               
            ax.plot(discrete_pdf[this_diag+'|'+qzs[0]][0],
                    discrete_pdf[this_diag+'|'+qzs[1]][0],
                    c='w', marker = 's',markeredgewidth=1.5,
                    markerfacecolor='w', 
                    markeredgecolor='k', markersize=11, zorder=10)
            
            grid_number  = which_grids.index(this_diag)+1
      
            ax.text(discrete_pdf[this_diag+'|'+qzs[0]][0],
                    discrete_pdf[this_diag+'|'+qzs[1]][0],
                    grid_number,
                    size=12, ha='center',va='center', zorder=11, color='k')
            
            if ax == ax1:
                # And also add the name of the diagnostic
                ax.text(QZs_lim[qzs[0]][0] +0.05, QZs_lim[qzs[1]][1] - 0.05*grid_number, 
                        '%i: %s' % (grid_number,this_diag),
                        horizontalalignment = 'left', verticalalignment = 'center')
    
    # Now, plot the global KDE and the associated contours -------------------------------
    all_gridZ = KDE_frompickle['all_gridZ']
    gridX = KDE_frompickle['gridX']
    gridY = KDE_frompickle['gridY']
    
    final_data = KDE_frompickle['final_data']
    final_cols = KDE_frompickle['final_cols']
    
    # Loop through all reconstructed KDEs. Plot all the contours, but only the full KDE.
    kde = False
    for gridZ_key in all_gridZ.keys():
        
        # If it is just some nans, go no further
        if np.all(np.isnan(all_gridZ[gridZ_key])):
            continue
        
        # Careful here: gridZ has a weird arrangement ...
        gridZ = np.rot90(all_gridZ[gridZ_key])[::-1,:]

        for ax in [ax1,ax2]:
            if gridZ_key == 'all':
                my_c = 'darkorange'
                my_c2 = 'none'
                my_lw = 2.5
                my_zo = 7
                
                # Plot the KDE
                kde = ax.imshow(gridZ,
                                extent=[QZs_lim[qzs[0]][0],
                                        QZs_lim[qzs[0]][1],
                                        QZs_lim[qzs[1]][0],
                                        QZs_lim[qzs[1]][1],
                                        ], 
                                        cmap=pyqz_cmap_1,
                                        origin='lower', 
                                        zorder=0, interpolation='nearest')      
            else:
                my_c = 'royalblue'
                my_c2 = 'none'
                my_lw = 1.5
                my_zo = 3
        
            # Plot the contour (two times for the look)
            # Mind the fact that gridX and gridY refer to the "un-derotated" gridZ !
                
            kde_cont = ax.contour(gridX, gridY, all_gridZ[gridZ_key], [PDF_cont_level], 
                                  colors = my_c, linestyles = '-', linewidths = my_lw, 
                                  zorder = my_zo)
                                            
            # Plot the individual and global KDE estimates -------------------------------    
            
            if gridZ_key == 'all':
                final_keys = ['<'+qzs[0]+'{KDE}>','err('+qzs[0]+'{KDE})',
                              '<'+qzs[1]+'{KDE}>','err('+qzs[1]+'{KDE})']
            else:
                final_keys = [gridZ_key+'|'+qzs[0]+'{KDE}',
                              'err('+gridZ_key+'|'+qzs[0]+'{KDE})',
                              gridZ_key+'|'+qzs[1]+'{KDE}',
                              'err('+gridZ_key+'|'+qzs[1]+'{KDE})']
                
            mean_est = [final_data[final_cols.index(final_keys[0])],
                        final_data[final_cols.index(final_keys[2])]]
            err_est = [final_data[final_cols.index(final_keys[1])],
                       final_data[final_cols.index(final_keys[3])]]
                       
            ax.errorbar(mean_est[0], mean_est[1],
                        xerr = err_est[0],yerr = err_est[1],
                        elinewidth = 2., ecolor = my_c, capthick = 0, 
                        zorder = my_zo)  
            ax.plot(mean_est[0], mean_est[1],
                    c = my_c, marker = 'o', markersize = 10, markeredgecolor = my_c,
                    markerfacecolor = my_c2, markeredgewidth = 2, zorder = my_zo)             
    
        
    # Plot the combined direct estimates -------------------------------------------------
    
    final_keys = ['<'+qzs[0]+'>','std('+qzs[0]+')', '<'+qzs[1]+'>','std('+qzs[1]+')']
    
    mean_est = [final_data[final_cols.index(final_keys[0])],
                final_data[final_cols.index(final_keys[2])]]
    err_est = [final_data[final_cols.index(final_keys[1])],
               final_data[final_cols.index(final_keys[3])]]
    
    # Only if that value actually exists !
    if not(np.any(np.isnan(mean_est))):
    
        for ax in [ax1,ax2]:
          
            ax.errorbar(mean_est[0], mean_est[1],
                        xerr = err_est[0], yerr = err_est[1], 
                        elinewidth = 2, 
                        ecolor = 'k', capthick = 0, zorder = 8)

            ax.plot(mean_est[0],mean_est[1],    
                    '*', c = 'w', markeredgecolor = 'k',
                    markeredgewidth = 2, markerfacecolor = 'w',
                    markersize = 20, zorder = 9)
    
    # Very well, finalize the plot now.
    for ax in [ax1, ax2]:               
        ax.set_xlabel(qzs[0])   
        ax.grid(True) 
      
    # Set the left plot to cover the full extent of the qz plane
    ax1.set_xlim(QZs_lim[qzs[0]])
    ax1.set_ylim(QZs_lim[qzs[1]])
    ax1.set_ylabel(qzs[1])
    
    
    # Define the limits for the right plot - a zoomed-in version
    if np.any(np.isnan(ax2_lims)):
        ax2.set_xlim(QZs_lim[qzs[0]])
        ax2.set_ylim(QZs_lim[qzs[1]])
    else:
        ax2.set_xlim(ax2_lims[:2])
        ax2.set_ylim(ax2_lims[2:])
        
        # Plot the window of the right plot in the left one
        rectx = [ax2_lims[0], ax2_lims[1], ax2_lims[1], ax2_lims[0], ax2_lims[0]]
        recty = [ax2_lims[2], ax2_lims[2], ax2_lims[3], ax2_lims[3], ax2_lims[2]]
        ax1.plot(rectx,recty, 'k--', lw = 1.5, markersize=5,zorder=1)
       
    ax2.set_aspect('auto')
    ax1.set_aspect('auto')
    ax1.locator_params(axis='x',nbins=5)
    ax2.locator_params(axis='x',nbins=5)

    # Plot the colorbar if required
    if kde:
        cb_ax = plt.subplot(gs[0,:])
        cb = Colorbar(ax = cb_ax, mappable = kde, orientation='horizontal')
        # Colorbar legend
        cb.set_label(r'Joint Probability Density (normalized to peak)', labelpad = -60)
        cb.ax.xaxis.set_ticks_position('top')
        cb.solids.set_edgecolor('face')
        # Draw the 1-sigma level (assuming gaussian = 61% of the peak)
        cb.ax.axvline(x = PDF_cont_level, color = 'darkorange', linewidth = 3, 
                      linestyle = '-')
   
    # Get ready to save this:
    if save_loc:
        plot_name = os.path.join(save_loc, fn_in[:-3]+'pdf')
        plt.savefig(plot_name, bbox_inches='tight')            
    if show_plots:     
        plt.show()
    else:
        plt.close()
    
# ----------------------------------------------------------------------------------------
コード例 #39
0
ファイル: plot.py プロジェクト: joanibal/freud
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
コード例 #40
0
ファイル: rejrej.py プロジェクト: dguest/JetFitter-Training
def _plot_eff_array(array_dict, use_contour = True, 
                    out_name = 'rejrej.pdf'):     

    eff_array = array_dict['eff']
    eff_array = _maximize_efficiency(eff_array)
    x_min, x_max = array_dict['x_range']
    y_min, y_max = array_dict['y_range']
    eff_array[np.nonzero(eff_array < 0.0)] = np.nan

    fig = plt.figure()
    gs = GridSpec(20,21)
    ax = plt.subplot(gs[:,0:-1])
    aspect = float(x_max - x_min) / (y_max - y_min)

    im = ax.imshow(
        eff_array, 
        origin = 'upper', 
        extent = (x_min,x_max, y_min, y_max), 
        aspect = aspect, 
        interpolation = 'nearest', 
        vmin = 0, 
        vmax = 1, 
        )

    if use_contour: 
        im.set_cmap('Greys')

        ct = ax.contour(
            eff_array, 
            origin = 'upper', 
            extent = (x_min,x_max, y_min, y_max), 
            aspect = aspect, 
            linewidths = 2, 
            levels = np.arange(0.1,1.0,0.1),
            )

    im.get_cmap().set_bad(alpha=0)

    ax.set_xticks([])
    ax.set_yticks([])
    ax.invert_yaxis()

    cb_ax = plt.subplot(gs[:,-1])
    plt.subplots_adjust(left = 0.25) # FIXME: use OO call here
    # cb = plt.colorbar()
    cb = Colorbar(ax = cb_ax, mappable = im)
    cb.set_label('{} efficiency'.format(array_dict['signal']))
    if use_contour: cb.add_lines(ct)
    position = ax.get_position()
    new_aspect = ax.get_aspect()
    # ax.set_position(position)
        

    ax_log = fig.add_subplot(111, frameon = False)
    ax_log.set_xscale('log')
    ax_log.set_yscale('log')
    ax_log.axis((10**x_min, 10**x_max, 10**y_min, 10**y_max))
    ax_log.set_aspect(aspect)
    ax_log.set_xlabel('{} rejection'.format(array_dict['x_bg']))
    ax_log.set_ylabel('{} rejection'.format(array_dict['y_bg']))
    ax_log.grid(True)


    ax_log.set_aspect(new_aspect)
    ax_log.set_position(position)
            
    plt.savefig(out_name, bbox_inches = 'tight')
    plt.close()
コード例 #41
0
ファイル: colorbar.py プロジェクト: mantidproject/mantid
class ColorbarWidget(QWidget):
    colorbarChanged = Signal() # The parent should simply redraw their canvas

    def __init__(self, parent=None):
        super(ColorbarWidget, self).__init__(parent)

        self.setWindowTitle("Colorbar")
        self.setMaximumWidth(200)

        self.dval = QDoubleValidator()

        self.cmin = QLineEdit()
        self.cmin_value = 0
        self.cmin.setMaximumWidth(100)
        self.cmin.editingFinished.connect(self.clim_changed)
        self.cmin_layout = QHBoxLayout()
        self.cmin_layout.addStretch()
        self.cmin_layout.addWidget(self.cmin)
        self.cmin_layout.addStretch()

        self.cmax = QLineEdit()
        self.cmax_value = 1
        self.cmax.setMaximumWidth(100)
        self.cmax.editingFinished.connect(self.clim_changed)
        self.cmin.setValidator(self.dval)
        self.cmax.setValidator(self.dval)
        self.cmax_layout = QHBoxLayout()
        self.cmax_layout.addStretch()
        self.cmax_layout.addWidget(self.cmax)
        self.cmax_layout.addStretch()

        self.norm_layout = QHBoxLayout()
        self.norm = QComboBox()
        self.norm.addItems(NORM_OPTS)
        self.norm.currentIndexChanged.connect(self.norm_changed)

        self.powerscale = QLineEdit()
        self.powerscale_value = 2
        self.powerscale.setText("2")
        self.powerscale.setValidator(QDoubleValidator(0.001,100,3))
        self.powerscale.setMaximumWidth(50)
        self.powerscale.editingFinished.connect(self.norm_changed)
        self.powerscale.hide()
        self.powerscale_label = QLabel("n=")
        self.powerscale_label.hide()

        self.norm_layout.addStretch()
        self.norm_layout.addWidget(self.norm)
        self.norm_layout.addStretch()
        self.norm_layout.addWidget(self.powerscale_label)
        self.norm_layout.addWidget(self.powerscale)

        self.autoscale = QCheckBox("Autoscaling")
        self.autoscale.setChecked(True)
        self.autoscale.stateChanged.connect(self.update_clim)

        self.canvas = FigureCanvas(Figure())
        if parent:
            # Set facecolor to match parent
            self.canvas.figure.set_facecolor(parent.palette().window().color().getRgbF())
        self.ax = self.canvas.figure.add_axes([0.4,0.05,0.2,0.9])

        # layout
        self.layout = QVBoxLayout(self)
        self.layout.addLayout(self.cmax_layout)
        self.layout.addWidget(self.canvas, stretch=1)
        self.layout.addLayout(self.cmin_layout)
        self.layout.addLayout(self.norm_layout)
        self.layout.addWidget(self.autoscale)

    def set_mappable(self, mappable):
        """
        When a new plot is created this method should be called with the new mappable
        """
        self.ax.clear()
        self.colorbar = Colorbar(ax=self.ax, mappable=mappable)
        self.cmin_value, self.cmax_value = self.colorbar.get_clim()
        self.update_clim_text()
        self.redraw()

    def norm_changed(self):
        """
        Called when a different normalization is selected
        """
        idx = self.norm.currentIndex()
        if NORM_OPTS[idx] == 'Power':
            self.powerscale.show()
            self.powerscale_label.show()
        else:
            self.powerscale.hide()
            self.powerscale_label.hide()
        self.colorbar.mappable.set_norm(self.get_norm())
        self.colorbarChanged.emit()

    def get_norm(self):
        """
        This will create a matplotlib.colors.Normalize from selected idx, limits and powerscale
        """
        idx = self.norm.currentIndex()
        if self.autoscale.isChecked():
            cmin = cmax = None
        else:
            cmin = self.cmin_value
            cmax = self.cmax_value
        if NORM_OPTS[idx] == 'Power':
            if self.powerscale.hasAcceptableInput():
                self.powerscale_value = float(self.powerscale.text())
            return PowerNorm(gamma=self.powerscale_value, vmin=cmin, vmax=cmax)
        elif NORM_OPTS[idx] == "SymmetricLog10":
            return SymLogNorm(1e-8 if cmin is None else max(1e-8, abs(cmin)*1e-3),
                              vmin=cmin, vmax=cmax)
        else:
            return Normalize(vmin=cmin, vmax=cmax)

    def clim_changed(self):
        """
        Called when either the min or max is changed. Will unset the autoscale.
        """
        self.autoscale.blockSignals(True)
        self.autoscale.setChecked(False)
        self.autoscale.blockSignals(False)
        self.update_clim()

    def update_clim(self):
        """
        This will update the clim of the plot based on min, max, and autoscale
        """
        if self.autoscale.isChecked():
            data = self.colorbar.mappable.get_array()
            try:
                try:
                    self.cmin_value = data[~data.mask].min()
                    self.cmax_value = data[~data.mask].max()
                except AttributeError:
                    self.cmin_value = np.nanmin(data)
                    self.cmax_value = np.nanmax(data)
            except (ValueError, RuntimeWarning):
                # all values mask
                pass
            self.update_clim_text()
        else:
            if self.cmin.hasAcceptableInput():
                self.cmin_value = float(self.cmin.text())
            if self.cmax.hasAcceptableInput():
                self.cmax_value = float(self.cmax.text())
        self.colorbar.set_clim(self.cmin_value, self.cmax_value)
        self.redraw()

    def update_clim_text(self):
        """
        Update displayed limit values based on stored ones
        """
        self.cmin.setText("{:.4}".format(self.cmin_value))
        self.cmax.setText("{:.4}".format(self.cmax_value))

    def redraw(self):
        """
        Redraws the colobar and emits signal to cause the parent to redraw
        """
        self.colorbar.update_ticks()
        self.colorbar.draw_all()
        self.canvas.draw_idle()
        self.colorbarChanged.emit()
コード例 #42
0
ファイル: maps.py プロジェクト: rgrapenthin/obspy
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])