Ejemplo n.º 1
0
    def plot_grid(self,
                  field,
                  level=0,
                  vmin=None,
                  vmax=None,
                  norm=None,
                  cmap=None,
                  mask_outside=False,
                  title=None,
                  title_flag=True,
                  axislabels=(None, None),
                  axislabels_flag=False,
                  colorbar_flag=True,
                  colorbar_label=None,
                  colorbar_orient='vertical',
                  ax=None,
                  fig=None,
                  lat_lines=None,
                  lon_lines=None,
                  projection=None,
                  embelish=True,
                  ticks=None,
                  ticklabs=None,
                  imshow=False,
                  **kwargs):
        """
        Plot the grid using xarray and cartopy.

        Additional arguments are passed to Xarray's pcolormesh function.

        Parameters
        ----------
        field : str
            Field to be plotted.
        level : int
            Index corresponding to the height level to be plotted.

        Other Parameters
        ----------------
        vmin, vmax : float
            Lower and upper range for the colormesh. If either parameter is
            None, a value will be determined from the field attributes (if
            available) or the default values of -8, 64 will be used.
            Parameters are used for luminance scaling.
        norm : Normalize or None, optional
            matplotlib Normalize instance used to scale luminance data. If not
            None the vmax and vmin parameters are ignored. If None, vmin and
            vmax are used for luminance scaling.
        cmap : str or None
            Matplotlib colormap name. None will use default colormap for
            the field being plotted as specified by the Py-ART configuration.
        mask_outside : bool
            True to mask data outside of vmin, vmax. False performs no
            masking.
        title : str
            Title to label plot with, None will use the default generated from
            the field and level parameters. Parameter is ignored if the
            title_flag is False.
        title_flag : bool
            True to add title to plot, False does not add a title.
        axislabels : (str, str)
            2-tuple of x-axis, y-axis labels. None for either label will use
            the default axis label. Parameter is ignored if axislabels_flag is
            False.
        axislabels_flag : bool
            True to add label the axes, False does not label the axes.
        colorbar_flag : bool
            True to add a colorbar with label to the axis. False leaves off
            the colorbar.
        colorbar_label : str
            Colorbar label, None will use a default label generated from the
            field information.
        colorbar_orient : 'vertical' or 'horizontal'
            Colorbar orientation.
        ax : Axis
            Axis to plot on. None will use the current axis.
        fig : Figure
            Figure to add the colorbar to. None will use the current figure.
        lat_lines, lon_lines : array or None
            Location at which to draw latitude and longitude lines.
            None will use default values which are reasonable for maps of
            North America.
        projection : cartopy.crs class
            Map projection supported by cartopy. Used for all subsequent calls
            to the GeoAxes object generated. Defaults to PlateCarree.
        emblish : bool
            True by default. Set to False to supress drawinf of coastlines
            etc... Use for speedup when specifying shapefiles.
            Note that lat lon labels only work with certain projections.
        ticks : array
            Colorbar custom tick label locations.
        ticklabs : array
            Colorbar custom tick labels.
        imshow : bool
            If used, plot uses ax.imshow instead of ax.pcolormesh.
            Default is False.

        """
        ds = self.grid.to_xarray()

        # parse parameters
        ax, fig = common.parse_ax_fig(ax, fig)
        vmin, vmax = common.parse_vmin_vmax(self.grid, field, vmin, vmax)
        cmap = common.parse_cmap(cmap, field)

        if lon_lines is None:
            lon_lines = np.linspace(np.around(ds.lon.min() - .1, decimals=2),
                                    np.around(ds.lon.max() + .1, decimals=2),
                                    5)
        if lat_lines is None:
            lat_lines = np.linspace(np.around(ds.lat.min() - .1, decimals=2),
                                    np.around(ds.lat.max() + .1, decimals=2),
                                    5)

        # mask the data where outside the limits
        if mask_outside:
            data = ds[field].data
            masked_data = np.ma.masked_invalid(data)
            masked_data = np.ma.masked_outside(masked_data, vmin, vmax)
            ds[field].data = masked_data

        if hasattr(ax, 'projection'):
            projection = ax.projection
        else:
            if projection is None:
                # set map projection to Mercator if none is specified
                projection = cartopy.crs.Mercator()

            ax = plt.axes(projection=projection)

        # plot the grid using xarray
        if norm is not None:  # if norm is set do not override with vmin/vmax
            vmin = vmax = None

        if imshow:
            pm = ds[field][0, level].plot.imshow(x='lon',
                                                 y='lat',
                                                 cmap=cmap,
                                                 vmin=vmin,
                                                 vmax=vmax,
                                                 add_colorbar=False,
                                                 **kwargs)
        else:
            pm = ds[field][0, level].plot.pcolormesh(x='lon',
                                                     y='lat',
                                                     cmap=cmap,
                                                     vmin=vmin,
                                                     vmax=vmax,
                                                     add_colorbar=False,
                                                     **kwargs)

        self.mappables.append(pm)
        self.fields.append(field)

        if embelish:
            # Create a feature for States/Admin 1 regions at 1:50m
            # from Natural Earth
            states = self.cartopy_states()
            coastlines = self.cartopy_coastlines()
            ax.add_feature(states, linestyle='-', edgecolor='k', linewidth=2)
            ax.add_feature(coastlines,
                           linestyle='-',
                           edgecolor='k',
                           linewidth=2)

            # labeling gridlines poses some difficulties depending on the
            # projection, so we need some projection-specific methods
            if ax.projection in [
                    cartopy.crs.PlateCarree(),
                    cartopy.crs.Mercator()
            ]:
                ax.gridlines(draw_labels=False,
                             linewidth=2,
                             color='gray',
                             alpha=0.5,
                             linestyle='--',
                             xlocs=lon_lines,
                             ylocs=lat_lines)
                ax.set_extent([
                    lon_lines.min(),
                    lon_lines.max(),
                    lat_lines.min(),
                    lat_lines.max()
                ],
                              crs=projection)
                ax.set_xticks(lon_lines, crs=projection)
                ax.set_yticks(lat_lines, crs=projection)

            elif isinstance(ax.projection, cartopy.crs.LambertConformal):
                fig.canvas.draw()
                ax.gridlines(xlocs=lon_lines, ylocs=lat_lines)

                # Label the end-points of the gridlines using the custom
                # tick makers:
                ax.xaxis.set_major_formatter(
                    cartopy.mpl.gridliner.LONGITUDE_FORMATTER)
                ax.yaxis.set_major_formatter(
                    cartopy.mpl.gridliner.LATITUDE_FORMATTER)
                if _LAMBERT_GRIDLINES:
                    lambert_xticks(ax, lon_lines)
                    lambert_yticks(ax, lat_lines)
            else:
                ax.gridlines(xlocs=lon_lines, ylocs=lat_lines)

        if title_flag:
            if title is None:
                ax.set_title(self.generate_grid_title(field, level))
            else:
                ax.set_title(title)

        if axislabels_flag:
            self._label_axes_grid(axislabels, ax)

        if colorbar_flag:
            self.plot_colorbar(mappable=pm,
                               label=colorbar_label,
                               orientation=colorbar_orient,
                               field=field,
                               ax=ax,
                               fig=fig,
                               ticks=ticks,
                               ticklabs=ticklabs)

        return
Ejemplo n.º 2
0
    def plot_longitudinal_level(self,
                                field,
                                x_index,
                                vmin=None,
                                vmax=None,
                                norm=None,
                                cmap=None,
                                mask_outside=False,
                                title=None,
                                title_flag=True,
                                axislabels=(None, None),
                                axislabels_flag=True,
                                colorbar_flag=True,
                                colorbar_label=None,
                                colorbar_orient='vertical',
                                edges=True,
                                ax=None,
                                fig=None,
                                ticks=None,
                                ticklabs=None,
                                **kwargs):
        """
        Plot a slice along a given longitude.

        Additional arguments are passed to Basemaps's pcolormesh function.

        Parameters
        ----------
        field : str
            Field to be plotted.
        x_index : float
            Index of the longitudinal level to plot.
        vmin, vmax : float
            Lower and upper range for the colormesh. If either parameter is
            None, a value will be determined from the field attributes (if
            available) or the default values of -8, 64 will be used.
            Parameters are ignored is norm is not None.
        norm : Normalize or None, optional
            matplotlib Normalize instance used to scale luminance data. If not
            None the vmax and vmin parameters are ignored. If None, vmin and
            vmax are used for luminance scaling.
        cmap : str or None
            Matplotlib colormap name. None will use the default colormap for
            the field being plotted as specified by the Py-ART configuration.
        mask_outside : bool
            True to mask data outside of vmin, vmax. False performs no
            masking.
        title : str
            Title to label plot with, None to use default title generated from
            the field and lat,lon parameters. Parameter is ignored if
            title_flag is False.
        title_flag : bool
            True to add a title to the plot, False does not add a title.
        axislabels : (str, str)
            2-tuple of x-axis, y-axis labels. None for either label will use
            the default axis label. Parameter is ignored if axislabels_flag is
            False.
        axislabels_flag : bool
            True to add label the axes, False does not label the axes.
        colorbar_flag : bool
            True to add a colorbar with label to the axis. False leaves off
            the colorbar.
        colorbar_label : str
            Colorbar label, None will use a default label generated from the
            field information.
        colorbar_orient : 'vertical' or 'horizontal'
            Colorbar orientation.
        edges : bool
            True will interpolate and extrapolate the gate edges from the
            range, azimuth and elevations in the radar, treating these
            as specifying the center of each gate. False treats these
            coordinates themselved as the gate edges, resulting in a plot
            in which the last gate in each ray and the entire last ray are not
            not plotted.
        ax : Axis
            Axis to plot on. None will use the current axis.
        fig : Figure
            Figure to add the colorbar to. None will use the current figure.
        ticks : array
            Colorbar custom tick label locations.
        ticklabs : array
            Colorbar custom tick labels.

        """
        # parse parameters
        ax, fig = common.parse_ax_fig(ax, fig)
        vmin, vmax = common.parse_vmin_vmax(self.grid, field, vmin, vmax)
        cmap = common.parse_cmap(cmap, field)

        data = self.grid.fields[field]['data'][:, :, x_index]

        # mask the data where outside the limits
        if mask_outside:
            data = np.ma.masked_invalid(data)
            data = np.ma.masked_outside(data, vmin, vmax)

        # plot the grid
        y_1d = self.grid.y['data'] / 1000
        z_1d = self.grid.z['data'] / 1000

        if edges:
            if len(y_1d) > 1:
                y_1d = _interpolate_axes_edges(y_1d)
            if len(z_1d) > 1:
                z_1d = _interpolate_axes_edges(z_1d)
        xd, yd = np.meshgrid(y_1d, z_1d)

        if norm is not None:  # if norm is set do not override with vmin, vmax
            vmin = vmax = None

        pm = ax.pcolormesh(xd,
                           yd,
                           data,
                           vmin=vmin,
                           vmax=vmax,
                           norm=norm,
                           cmap=cmap,
                           **kwargs)

        self.mappables.append(pm)
        self.fields.append(field)

        if title_flag:
            if title is None:
                ax.set_title(
                    common.generate_longitudinal_level_title(
                        self.grid, field, x_index))
            else:
                ax.set_title(title)

        if axislabels_flag:
            self._label_axes_longitude(axislabels, ax)

        if colorbar_flag:
            self.plot_colorbar(mappable=pm,
                               label=colorbar_label,
                               orientation=colorbar_orient,
                               field=field,
                               ax=ax,
                               fig=fig,
                               ticks=ticks,
                               ticklabs=ticklabs)
        return
Ejemplo n.º 3
0
def test_parse_cmap():
    assert common.parse_cmap('jet', 'foo') == 'jet'
    assert common.parse_cmap(None, 'reflectivity') == 'pyart_NWSRef'
Ejemplo n.º 4
0
def test_parse_cmap():
    assert common.parse_cmap('jet', 'foo') == 'jet'
    assert common.parse_cmap(None, 'reflectivity') == 'pyart_NWSRef'
def plot_ppi_mask_fixed(display,
                        field,
                        sweep=0,
                        mask_tuple=None,
                        vmin=None,
                        vmax=None,
                        norm=None,
                        cmap=None,
                        mask_outside=False,
                        title=None,
                        title_flag=True,
                        axislabels=(None, None),
                        axislabels_flag=True,
                        colorbar_flag=True,
                        colorbar_label=None,
                        colorbar_orient='vertical',
                        edges=True,
                        gatefilter=None,
                        filter_transitions=True,
                        ax=None,
                        fig=None,
                        ticks=None,
                        ticklabs=None,
                        raster=None,
                        **kwargs):

    # parse parameters
    ax, fig = common.parse_ax_fig(ax, fig)
    vmin, vmax = common.parse_vmin_vmax(display._radar, field, vmin, vmax)
    cmap = common.parse_cmap(cmap, field)

    # get data for the plot
    data = display._get_data(field, sweep, mask_tuple, filter_transitions,
                             gatefilter)
    x, y = display._get_x_y(sweep, edges, filter_transitions)

    data.fill_value = -100.0
    data = data.filled()
    data = np.add(100.0, data)
    #print data

    # mask the data where outside the limits
    data = _mask_outside(mask_outside, data, vmin, vmax)

    # plot the data
    if norm is not None:  # if norm is set do not override with vmin/vmax
        vmin = vmax = None
    vmin = 0
    vmax = 255
    pm = ax.pcolormesh(x,
                       y,
                       data,
                       vmin=vmin,
                       vmax=vmax,
                       cmap=cmap,
                       norm=norm,
                       **kwargs)

    if raster is not None:
        pm.set_rasterized(True)

    if title_flag:
        display._set_title(field, sweep, title, ax)

    if axislabels_flag:
        display._label_axes_ppi(axislabels, ax)

    # add plot and field to lists
    display.plots.append(pm)
    display.plot_vars.append(field)

    if colorbar_flag:
        display.plot_colorbar(mappable=pm,
                              label=colorbar_label,
                              orient=colorbar_orient,
                              field=field,
                              ax=ax,
                              fig=fig,
                              ticks=ticks,
                              ticklabs=ticklabs)
Ejemplo n.º 6
0
def test_parse_cmap():
    assert common.parse_cmap('jet', 'foo') == 'jet'
    assert common.parse_cmap(None, 'reflectivity') == 'pyart_HomeyerRainbow'