예제 #1
0
def mapImg(img, lons, lats, vmin, vmax, pad, zoom, title):

    minlat = lats.min()
    maxlat = lats.max()
    minlon = lons.min()
    maxlon = lons.max()
    bg = 'World_Imagery'
    url = 'https://server.arcgisonline.com/ArcGIS/rest/services/' + bg + '/MapServer/tile/{z}/{y}/{x}.jpg'
    image = cimgt.GoogleTiles(url=url)
    data_crs = ccrs.PlateCarree()
    fig = plt.figure(figsize=(6, 8))
    ax = plt.axes(projection=data_crs)
    img_handle = plt.pcolormesh(lons,
                                lats,
                                img,
                                vmin=vmin,
                                vmax=vmax,
                                transform=data_crs,
                                rasterized=True)

    lon_range = (pad + maxlon) - (minlon - pad)
    lat_range = (pad + maxlat) - (minlat - pad)
    rangeMin = np.min(np.array([lon_range, lat_range]))
    tick_increment = round(rangeMin / 4, 1)

    import matplotlib.ticker as mticker
    from cartopy.mpl.ticker import (LongitudeFormatter, LatitudeFormatter,
                                    LatitudeLocator)

    gl = ax.gridlines(crs=ccrs.PlateCarree(),
                      draw_labels=True,
                      linewidth=0.5,
                      color='gray',
                      alpha=0.5,
                      linestyle='--')
    gl.xlocator = mticker.FixedLocator(
        np.arange(np.floor(minlon - pad), np.ceil(maxlon + pad),
                  tick_increment))
    gl.ylocator = LatitudeLocator()
    gl.xformatter = LongitudeFormatter()
    gl.yformatter = LatitudeFormatter()
    gl.ylabel_style = {'size': 8, 'color': 'black'}
    gl.xlabel_style = {'size': 8, 'color': 'black'}
    gl.top_labels = False
    gl.right_labels = False

    # ax.set_xticks(np.arange(np.floor(minlon-pad),np.ceil(maxlon+pad),tick_increment), crs=ccrs.PlateCarree())
    # ax.set_yticks(np.arange(np.floor(minlat-pad),np.ceil(maxlat+pad),tick_increment), crs=ccrs.PlateCarree())
    # ax.lon_formatter = LongitudeFormatter(zero_direction_label=True)
    # lat_formatter = LatitudeFormatter()
    # ax.xlabel_style = {'size': 15, 'color': 'gray'}
    # ax.xlabel_style = {'color': 'red', 'weight': 'bold'}
    # ax.xaxis.set_major_formatter(lon_formatter)
    # ax.yaxis.set_major_formatter(lat_formatter)
    ax.add_image(image, zoom)  #zoom level
    plt.colorbar(img_handle, fraction=0.03, pad=0.05, orientation='horizontal')
    plt.title(title)
    plt.show()
예제 #2
0
    def __init__(self,
                 axes,
                 crs,
                 draw_labels=False,
                 xlocator=None,
                 ylocator=None,
                 collection_kwargs=None,
                 xformatter=None,
                 yformatter=None,
                 dms=False,
                 x_inline=None,
                 y_inline=None,
                 auto_inline=True):
        """
        Object used by :meth:`cartopy.mpl.geoaxes.GeoAxes.gridlines`
        to add gridlines and tick labels to a map.

        Parameters
        ----------
        axes
            The :class:`cartopy.mpl.geoaxes.GeoAxes` object to be drawn on.
        crs
            The :class:`cartopy.crs.CRS` defining the coordinate system that
            the gridlines are drawn in.
        draw_labels: optional
            Toggle whether to draw labels. For finer control, attributes of
            :class:`Gridliner` may be modified individually. Defaults to False.
        xlocator: optional
            A :class:`matplotlib.ticker.Locator` instance which will be used
            to determine the locations of the gridlines in the x-coordinate of
            the given CRS. Defaults to None, which implies automatic locating
            of the gridlines.
        ylocator: optional
            A :class:`matplotlib.ticker.Locator` instance which will be used
            to determine the locations of the gridlines in the y-coordinate of
            the given CRS. Defaults to None, which implies automatic locating
            of the gridlines.
        xformatter: optional
            A :class:`matplotlib.ticker.Formatter` instance to format
            longitude labels. It defaults to None, which implies the use of a
            :class:`cartopy.mpl.ticker.LongitudeFormatter` initiated
            with the ``dms`` argument.
        yformatter: optional
            A :class:`matplotlib.ticker.Formatter` instance to format
            latitude labels. It defaults to None, which implies the use of a
            :class:`cartopy.mpl.ticker.LatitudeFormatter` initiated
            with the ``dms`` argument.
        collection_kwargs: optional
            Dictionary controlling line properties, passed to
            :class:`matplotlib.collections.Collection`. Defaults to None.
        dms: bool
            When default locators and formatters are used,
            ticks are able to stop on minutes and seconds if minutes
            is set to True, and not fraction of degrees.
        x_inline: optional
            Toggle whether the x labels drawn should be inline.
        y_inline: optional
            Toggle whether the y labels drawn should be inline.
        auto_inline: optional
            Set x_inline and y_inline automatically based on projection

        .. note:: Note that the "x" and "y" labels for locators and
             formatters do not necessarily correspond to X and Y,
             but to longitudes and latitudes: indeed, according to
             geographical projections, meridians and parallels can
             cross both the X axis and the Y axis.
        """
        self.axes = axes

        #: The :class:`~matplotlib.ticker.Locator` to use for the x
        #: gridlines and labels.
        if xlocator is not None:
            if not isinstance(xlocator, mticker.Locator):
                xlocator = mticker.FixedLocator(xlocator)
            self.xlocator = xlocator
        elif isinstance(crs, cartopy.crs.PlateCarree):
            self.xlocator = LongitudeLocator(dms=dms)
        else:
            self.xlocator = classic_locator

        #: The :class:`~matplotlib.ticker.Locator` to use for the y
        #: gridlines and labels.
        if ylocator is not None:
            if not isinstance(ylocator, mticker.Locator):
                ylocator = mticker.FixedLocator(ylocator)
            self.ylocator = ylocator
        elif isinstance(crs, cartopy.crs.PlateCarree):
            self.ylocator = LatitudeLocator(dms=dms)
        else:
            self.ylocator = classic_locator

        #: The :class:`~matplotlib.ticker.Formatter` to use for the lon labels.
        self.xformatter = xformatter or LongitudeFormatter(dms=dms)

        #: The :class:`~matplotlib.ticker.Formatter` to use for the lat labels.
        self.yformatter = yformatter or LatitudeFormatter(dms=dms)

        #: Whether to draw labels on the top of the map.
        self.top_labels = draw_labels

        #: Whether to draw labels on the bottom of the map.
        self.bottom_labels = draw_labels

        #: Whether to draw labels on the left hand side of the map.
        self.left_labels = draw_labels

        #: Whether to draw labels on the right hand side of the map.
        self.right_labels = draw_labels

        if auto_inline:
            if isinstance(self.axes.projection, _X_INLINE_PROJS):
                self.x_inline = True
                self.y_inline = False
            elif isinstance(self.axes.projection, _POLAR_PROJS):
                self.x_inline = False
                self.y_inline = True
            else:
                self.x_inline = False
                self.y_inline = False

        # overwrite auto_inline if necessary
        if x_inline is not None:
            #: Whether to draw x labels inline
            self.x_inline = x_inline
        elif not auto_inline:
            self.x_inline = False

        if y_inline is not None:
            #: Whether to draw y labels inline
            self.y_inline = y_inline
        elif not auto_inline:
            self.y_inline = False

        #: Whether to draw the longitude gridlines (meridians).
        self.xlines = True

        #: Whether to draw the latitude gridlines (parallels).
        self.ylines = True

        #: A dictionary passed through to ``ax.text`` on x label creation
        #: for styling of the text labels.
        self.xlabel_style = {}

        #: A dictionary passed through to ``ax.text`` on y label creation
        #: for styling of the text labels.
        self.ylabel_style = {}

        #: The padding from the map edge to the x labels in points.
        self.xpadding = 5

        #: The padding from the map edge to the y labels in points.
        self.ypadding = 5

        #: Allow the rotation of labels.
        self.rotate_labels = True

        # Current transform
        self.crs = crs

        # if the user specifies tick labels at this point, check if they can
        # be drawn. The same check will take place at draw time in case
        # public attributes are changed after instantiation.
        if draw_labels and not (x_inline or y_inline or auto_inline):
            self._assert_can_draw_ticks()

        #: The number of interpolation points which are used to draw the
        #: gridlines.
        self.n_steps = 100

        #: A dictionary passed through to
        #: ``matplotlib.collections.LineCollection`` on grid line creation.
        self.collection_kwargs = collection_kwargs

        #: The x gridlines which were created at draw time.
        self.xline_artists = []

        #: The y gridlines which were created at draw time.
        self.yline_artists = []

        # Plotted status
        self._plotted = False

        # Check visibility of labels at each draw event
        # (or once drawn, only at resize event ?)
        self.axes.figure.canvas.mpl_connect('draw_event', self._draw_event)
예제 #3
0
class Gridliner(object):
    # NOTE: In future, one of these objects will be add-able to a GeoAxes (and
    # maybe even a plain old mpl axes) and it will call the "_draw_gridliner"
    # method on draw. This will enable automatic gridline resolution
    # determination on zoom/pan.
    def __init__(self,
                 axes,
                 crs,
                 draw_labels=False,
                 xlocator=None,
                 ylocator=None,
                 collection_kwargs=None,
                 xformatter=None,
                 yformatter=None,
                 dms=False,
                 x_inline=None,
                 y_inline=None,
                 auto_inline=True):
        """
        Object used by :meth:`cartopy.mpl.geoaxes.GeoAxes.gridlines`
        to add gridlines and tick labels to a map.

        Parameters
        ----------
        axes
            The :class:`cartopy.mpl.geoaxes.GeoAxes` object to be drawn on.
        crs
            The :class:`cartopy.crs.CRS` defining the coordinate system that
            the gridlines are drawn in.
        draw_labels: optional
            Toggle whether to draw labels. For finer control, attributes of
            :class:`Gridliner` may be modified individually. Defaults to False.
        xlocator: optional
            A :class:`matplotlib.ticker.Locator` instance which will be used
            to determine the locations of the gridlines in the x-coordinate of
            the given CRS. Defaults to None, which implies automatic locating
            of the gridlines.
        ylocator: optional
            A :class:`matplotlib.ticker.Locator` instance which will be used
            to determine the locations of the gridlines in the y-coordinate of
            the given CRS. Defaults to None, which implies automatic locating
            of the gridlines.
        xformatter: optional
            A :class:`matplotlib.ticker.Formatter` instance to format
            longitude labels. It defaults to None, which implies the use of a
            :class:`cartopy.mpl.ticker.LongitudeFormatter` initiated
            with the ``dms`` argument.
        yformatter: optional
            A :class:`matplotlib.ticker.Formatter` instance to format
            latitude labels. It defaults to None, which implies the use of a
            :class:`cartopy.mpl.ticker.LatitudeFormatter` initiated
            with the ``dms`` argument.
        collection_kwargs: optional
            Dictionary controlling line properties, passed to
            :class:`matplotlib.collections.Collection`. Defaults to None.
        dms: bool
            When default locators and formatters are used,
            ticks are able to stop on minutes and seconds if minutes
            is set to True, and not fraction of degrees.
        x_inline: optional
            Toggle whether the x labels drawn should be inline.
        y_inline: optional
            Toggle whether the y labels drawn should be inline.
        auto_inline: optional
            Set x_inline and y_inline automatically based on projection

        .. note:: Note that the "x" and "y" labels for locators and
             formatters do not necessarily correspond to X and Y,
             but to longitudes and latitudes: indeed, according to
             geographical projections, meridians and parallels can
             cross both the X axis and the Y axis.
        """
        self.axes = axes

        #: The :class:`~matplotlib.ticker.Locator` to use for the x
        #: gridlines and labels.
        if xlocator is not None:
            if not isinstance(xlocator, mticker.Locator):
                xlocator = mticker.FixedLocator(xlocator)
            self.xlocator = xlocator
        elif isinstance(crs, cartopy.crs.PlateCarree):
            self.xlocator = LongitudeLocator(dms=dms)
        else:
            self.xlocator = classic_locator

        #: The :class:`~matplotlib.ticker.Locator` to use for the y
        #: gridlines and labels.
        if ylocator is not None:
            if not isinstance(ylocator, mticker.Locator):
                ylocator = mticker.FixedLocator(ylocator)
            self.ylocator = ylocator
        elif isinstance(crs, cartopy.crs.PlateCarree):
            self.ylocator = LatitudeLocator(dms=dms)
        else:
            self.ylocator = classic_locator

        #: The :class:`~matplotlib.ticker.Formatter` to use for the lon labels.
        self.xformatter = xformatter or LongitudeFormatter(dms=dms)

        #: The :class:`~matplotlib.ticker.Formatter` to use for the lat labels.
        self.yformatter = yformatter or LatitudeFormatter(dms=dms)

        #: Whether to draw labels on the top of the map.
        self.top_labels = draw_labels

        #: Whether to draw labels on the bottom of the map.
        self.bottom_labels = draw_labels

        #: Whether to draw labels on the left hand side of the map.
        self.left_labels = draw_labels

        #: Whether to draw labels on the right hand side of the map.
        self.right_labels = draw_labels

        if auto_inline:
            if isinstance(self.axes.projection, _X_INLINE_PROJS):
                self.x_inline = True
                self.y_inline = False
            elif isinstance(self.axes.projection, _POLAR_PROJS):
                self.x_inline = False
                self.y_inline = True
            else:
                self.x_inline = False
                self.y_inline = False

        # overwrite auto_inline if necessary
        if x_inline is not None:
            #: Whether to draw x labels inline
            self.x_inline = x_inline
        elif not auto_inline:
            self.x_inline = False

        if y_inline is not None:
            #: Whether to draw y labels inline
            self.y_inline = y_inline
        elif not auto_inline:
            self.y_inline = False

        #: Whether to draw the longitude gridlines (meridians).
        self.xlines = True

        #: Whether to draw the latitude gridlines (parallels).
        self.ylines = True

        #: A dictionary passed through to ``ax.text`` on x label creation
        #: for styling of the text labels.
        self.xlabel_style = {}

        #: A dictionary passed through to ``ax.text`` on y label creation
        #: for styling of the text labels.
        self.ylabel_style = {}

        #: The padding from the map edge to the x labels in points.
        self.xpadding = 5

        #: The padding from the map edge to the y labels in points.
        self.ypadding = 5

        #: Allow the rotation of labels.
        self.rotate_labels = True

        # Current transform
        self.crs = crs

        # if the user specifies tick labels at this point, check if they can
        # be drawn. The same check will take place at draw time in case
        # public attributes are changed after instantiation.
        if draw_labels and not (x_inline or y_inline or auto_inline):
            self._assert_can_draw_ticks()

        #: The number of interpolation points which are used to draw the
        #: gridlines.
        self.n_steps = 100

        #: A dictionary passed through to
        #: ``matplotlib.collections.LineCollection`` on grid line creation.
        self.collection_kwargs = collection_kwargs

        #: The x gridlines which were created at draw time.
        self.xline_artists = []

        #: The y gridlines which were created at draw time.
        self.yline_artists = []

        # Plotted status
        self._plotted = False

        # Check visibility of labels at each draw event
        # (or once drawn, only at resize event ?)
        self.axes.figure.canvas.mpl_connect('draw_event', self._draw_event)

    def _draw_event(self, event):
        if self.has_labels():
            self._update_labels_visibility(event.renderer)

    def has_labels(self):
        return hasattr(self, '_labels') and self._labels

    @property
    def label_artists(self):
        if self.has_labels():
            return self._labels
        return []

    def _crs_transform(self):
        """
        Get the drawing transform for our gridlines.

        Note
        ----
            The drawing transform depends on the transform of our 'axes', so
            it may change dynamically.

        """
        transform = self.crs
        if not isinstance(transform, mtrans.Transform):
            transform = transform._as_mpl_transform(self.axes)
        return transform

    @staticmethod
    def _round(x, base=5):
        if np.isnan(base):
            base = 5
        return int(base * round(float(x) / base))

    def _find_midpoints(self, lim, ticks):
        # find the cneter point between each lat gridline
        cent = np.diff(ticks).mean() / 2
        if isinstance(self.axes.projection, _POLAR_PROJS):
            lq = 90
            uq = 90
        else:
            lq = 25
            uq = 75
        midpoints = (self._round(np.percentile(lim, lq), cent),
                     self._round(np.percentile(lim, uq), cent))
        return midpoints

    def _draw_gridliner(self,
                        nx=None,
                        ny=None,
                        background_patch=None,
                        renderer=None):
        """Create Artists for all visible elements and add to our Axes."""
        # Check status
        if self._plotted:
            return
        self._plotted = True

        # Inits
        lon_lim, lat_lim = self._axes_domain(nx=nx,
                                             ny=ny,
                                             background_patch=background_patch)

        transform = self._crs_transform()
        rc_params = matplotlib.rcParams
        n_steps = self.n_steps
        crs = self.crs

        # Get nice ticks within crs domain
        lon_ticks = self.xlocator.tick_values(lon_lim[0], lon_lim[1])
        lat_ticks = self.ylocator.tick_values(lat_lim[0], lat_lim[1])
        lon_ticks = [
            value for value in lon_ticks
            if value >= max(lon_lim[0], crs.x_limits[0])
            and value <= min(lon_lim[1], crs.x_limits[1])
        ]
        lat_ticks = [
            value for value in lat_ticks
            if value >= max(lat_lim[0], crs.y_limits[0])
            and value <= min(lat_lim[1], crs.y_limits[1])
        ]

        #####################
        # Gridlines drawing #
        #####################

        collection_kwargs = self.collection_kwargs
        if collection_kwargs is None:
            collection_kwargs = {}
        collection_kwargs = collection_kwargs.copy()
        collection_kwargs['transform'] = transform
        # XXX doesn't gracefully handle lw vs linewidth aliases...
        collection_kwargs.setdefault('color', rc_params['grid.color'])
        collection_kwargs.setdefault('linestyle', rc_params['grid.linestyle'])
        collection_kwargs.setdefault('linewidth', rc_params['grid.linewidth'])

        # Meridians
        lon_lines = []
        lat_min, lat_max = lat_lim
        if lat_ticks:
            lat_min = min(lat_min, min(lat_ticks))
            lat_max = max(lat_max, max(lat_ticks))
        for x in lon_ticks:
            ticks = list(
                zip([x] * n_steps, np.linspace(lat_min, lat_max, n_steps)))
            lon_lines.append(ticks)

        if self.xlines:
            nx = len(lon_lines) + 1
            # XXX this bit is cartopy specific. (for circular longitudes)
            # Purpose: omit plotting the last x line,
            # as it may overlap the first.
            if (isinstance(crs, Projection)
                    and isinstance(crs, _RectangularProjection)
                    and abs(np.diff(lon_lim)) == abs(np.diff(crs.x_limits))):
                nx -= 1
            lon_lc = mcollections.LineCollection(lon_lines,
                                                 **collection_kwargs)
            self.xline_artists.append(lon_lc)
            self.axes.add_collection(lon_lc, autolim=False)

        # Parallels
        lat_lines = []
        lon_min, lon_max = lon_lim
        if lon_ticks:
            lon_min = min(lon_min, min(lon_ticks))
            lon_max = max(lon_max, max(lon_ticks))
        for y in lat_ticks:
            ticks = list(
                zip(np.linspace(lon_min, lon_max, n_steps), [y] * n_steps))
            lat_lines.append(ticks)
        if self.ylines:
            lat_lc = mcollections.LineCollection(lat_lines,
                                                 **collection_kwargs)
            self.yline_artists.append(lat_lc)
            self.axes.add_collection(lat_lc, autolim=False)

        #################
        # Label drawing #
        #################

        self.bottom_label_artists = []
        self.top_label_artists = []
        self.left_label_artists = []
        self.right_label_artists = []
        if not (self.left_labels or self.right_labels or self.bottom_labels
                or self.top_labels):
            return
        self._assert_can_draw_ticks()

        # Get the real map boundaries
        map_boundary_vertices = self.axes.background_patch.get_path().vertices
        map_boundary = sgeom.Polygon(map_boundary_vertices)

        self._labels = []

        if self.x_inline:
            y_midpoints = self._find_midpoints(lat_lim, lat_ticks)
        if self.y_inline:
            x_midpoints = self._find_midpoints(lon_lim, lon_ticks)

        for lonlat, lines, line_ticks, formatter, label_style in (
            ('lon', lon_lines, lon_ticks, self.xformatter, self.xlabel_style),
            ('lat', lat_lines, lat_ticks, self.yformatter, self.ylabel_style)):

            formatter.set_locs(line_ticks)

            # lines = lines[::2]
            # line_ticks = line_ticks[::2]
            for line, tick_value in zip(lines, line_ticks):
                # Intersection of line with map boundary
                line = np.array(line)
                line = self.axes.projection.transform_points(
                    crs, line[:, 0], line[:, 1])[:, :2]
                infs = np.isinf(line)
                if infs.any():
                    if infs.all():
                        continue
                    line = line.compress(~infs.any(axis=1), axis=0)
                line = sgeom.LineString(line)
                if line.intersects(map_boundary):
                    intersection = line.intersection(map_boundary)
                    del line
                    if intersection.is_empty:
                        continue
                    if isinstance(intersection, sgeom.MultiPoint):
                        if len(intersection) < 2:
                            continue
                        tails = [[(pt.x, pt.y) for pt in intersection[:2]]]
                        heads = [[(pt.x, pt.y)
                                  for pt in intersection[-1:-3:-1]]]
                    elif isinstance(intersection,
                                    (sgeom.LineString, sgeom.MultiLineString)):
                        if isinstance(intersection, sgeom.LineString):
                            intersection = [intersection]
                        elif len(intersection) > 4:
                            # Gridline and map boundary are parallel
                            # and they intersect themselves too much
                            # it results in a multiline string
                            # that must be converted to a single linestring.
                            # This is an empirical workaround for a problem
                            # that can probably be solved in a cleaner way.
                            x, y = intersection[0].coords.xy
                            x += intersection[-1].coords.xy[0]
                            y += intersection[-1].coords.xy[1]
                            xy = np.array((x, y))
                            intersection = [sgeom.LineString(xy.T)]
                        tails = []
                        heads = []
                        for inter in intersection:
                            if len(inter.coords) < 2:
                                continue
                            tails.append(inter.coords[:2])
                            heads.append(inter.coords[-1:-3:-1])
                        if not tails:
                            continue
                    elif isinstance(intersection,
                                    sgeom.collection.GeometryCollection):
                        # This is a collection of Point and LineString that
                        # represent the same gridline. We only consider
                        # the first and last geometries, merge their
                        # coordinates and keep first or last two points
                        # to get only one tail and and one head.
                        tails = []
                        heads = []
                        for ht, slicer in [(tails, slice(0, 2)),
                                           (heads, slice(-1, -3, -1))]:
                            x = array('d', [])
                            y = array('d', [])
                            for geom in list(intersection.geoms)[slicer]:
                                x += geom.xy[0]
                                y += geom.xy[1]
                            ht.append(list(zip(x[slicer], y[slicer])))
                    else:
                        warn('Unsupported intersection geometry for gridline'
                             'labels: ' + intersection.__class__)
                        continue
                    del intersection

                    # Loop on head and tail and plot label by extrapolation
                    for tail, head in zip(tails, heads):
                        for i, (pt0, pt1) in enumerate([tail, head]):
                            kw, angle, loc = self._segment_to_text_specs(
                                pt0, pt1, lonlat)
                            if not getattr(self, loc + '_labels'):
                                continue
                            kw.update(label_style,
                                      bbox={
                                          'pad': 0,
                                          'visible': False
                                      })
                            text = formatter(tick_value)

                            if self.y_inline and lonlat == 'lat':
                                # 180 degrees isn't formatted with a
                                # suffix and adds confusion if it's inline
                                if abs(tick_value) == 180:
                                    continue
                                x = x_midpoints[i]
                                y = tick_value
                                y_set = True
                            else:
                                x = pt0[0]
                                y_set = False

                            if self.x_inline and lonlat == 'lon':
                                if abs(tick_value) == 180:
                                    continue
                                x = tick_value
                                y = y_midpoints[i]
                            elif not y_set:
                                y = pt0[1]

                            tt = self.axes.text(x, y, text, **kw)
                            tt._angle = angle
                            priority = (((lonlat == 'lon')
                                         and loc in ('bottom', 'top'))
                                        or ((lonlat == 'lat')
                                            and loc in ('left', 'right')))
                            self._labels.append((lonlat, priority, tt))
                            getattr(self, loc + '_label_artists').append(tt)

        # Sort labels
        if self._labels:
            self._labels.sort(key=operator.itemgetter(0), reverse=True)
            self._update_labels_visibility(renderer)

    def _segment_to_text_specs(self, pt0, pt1, lonlat):
        """Get appropriate kwargs for a label from lon or lat line segment"""
        x0, y0 = pt0
        x1, y1 = pt1
        angle = np.arctan2(y0 - y1, x0 - x1) * 180 / np.pi
        kw, loc = self._segment_angle_to_text_specs(angle, lonlat)
        return kw, angle, loc

    def _text_angle_to_specs_(self, angle, lonlat):
        """Get specs for a rotated label from its angle in degrees"""

        if matplotlib.__version__ >= '3.1':
            # rotation_mode='anchor' and va_align_center='center_baseline'
            # are incompatible before mpl-3.1
            va_align_center = 'center_baseline'
        else:
            va_align_center = 'center'

        angle %= 360
        if angle > 180:
            angle -= 360

        if ((self.x_inline and lonlat == 'lon')
                or (self.y_inline and lonlat == 'lat')):
            kw = {
                'rotation': 0,
                'rotation_mode': 'anchor',
                'ha': 'center',
                'va': 'center'
            }
            loc = 'bottom'
            return kw, loc

        # Default options
        kw = {'rotation': angle, 'rotation_mode': 'anchor'}

        # Options that depend in which quarter the angle falls
        if abs(angle) <= 45:

            loc = 'right'
            kw.update(ha='left', va=va_align_center)

        elif abs(angle) >= 135:

            loc = 'left'
            kw.update(ha='right', va=va_align_center)
            kw['rotation'] -= np.sign(angle) * 180

        elif angle > 45:

            loc = 'top'
            kw.update(ha='center', va='bottom', rotation=angle - 90)

        else:

            loc = 'bottom'
            kw.update(ha='center', va='top', rotation=angle + 90)

        return kw, loc

    def _segment_angle_to_text_specs(self, angle, lonlat):
        """Get appropriate kwargs for a given text angle"""
        kw, loc = self._text_angle_to_specs_(angle, lonlat)
        if not self.rotate_labels:
            angle = {
                'top': 90.,
                'right': 0.,
                'bottom': -90.,
                'left': 180.
            }[loc]
            del kw['rotation']

        if ((self.x_inline and lonlat == 'lon')
                or (self.y_inline and lonlat == 'lat')):
            kw.update(transform=cartopy.crs.PlateCarree())
        else:
            xpadding = (self.xpadding if self.xpadding is not None else
                        matplotlib.rc_params['xtick.major.pad'])
            ypadding = (self.ypadding if self.ypadding is not None else
                        matplotlib.rc_params['ytick.major.pad'])
            dx = ypadding * np.cos(angle * np.pi / 180)
            dy = xpadding * np.sin(angle * np.pi / 180)
            transform = mtrans.offset_copy(self.axes.transData,
                                           self.axes.figure,
                                           x=dx,
                                           y=dy,
                                           units='dots')
            kw.update(transform=transform)

        return kw, loc

    def _update_labels_visibility(self, renderer):
        """Update the visibility of each plotted label

        The following rules apply:

        - Labels are plotted and checked by order of priority,
          with a high priority for longitude labels at the bottom and
          top of the map, and the reverse for latitude labels.
        - A label must not overlap another label marked as visible.
        - A label must not overlap the map boundary.
        - When a label is about to be hidden, other angles are tried in the
          absolute given limit of max_delta_angle by increments of delta_angle
          of difference from the original angle.
        """
        if renderer is None or not self._labels:
            return
        paths = []
        outline_path = None
        delta_angle = 22.5
        max_delta_angle = 45
        axes_children = self.axes.get_children()

        for lonlat, priority, artist in self._labels:

            if artist not in axes_children:
                warn('The labels of this gridliner do not belong'
                     'to the gridliner axes')

            # Compute angles to try
            orig_specs = {
                'rotation': artist.get_rotation(),
                'ha': artist.get_ha(),
                'va': artist.get_va()
            }
            angles = [None]
            for abs_delta_angle in np.arange(delta_angle, max_delta_angle + 1,
                                             delta_angle):
                for sign_delta_angle in (1, -1):
                    angle = artist._angle + sign_delta_angle * abs_delta_angle
                    angles.append(angle)

            # Loop on angles until it works
            for angle in angles:
                if ((self.x_inline and lonlat == 'lon')
                        or (self.y_inline and lonlat == 'lat')):
                    angle = 0

                if angle is not None:
                    specs, _ = self._segment_angle_to_text_specs(angle, lonlat)
                    plt.setp(artist, **specs)

                artist.update_bbox_position_size(renderer)
                this_patch = artist.get_bbox_patch()
                this_path = this_patch.get_path().transformed(
                    this_patch.get_transform())
                visible = False

                for path in paths:

                    # Check it does not overlap another label
                    if this_path.intersects_path(path):
                        break

                else:

                    # Finally check that it does not overlap the map
                    if outline_path is None:
                        outline_path = self.axes.background_patch.get_path(
                        ).transformed(self.axes.transData)
                    visible = (not outline_path.intersects_path(this_path)
                               or (lonlat == 'lon' and self.x_inline)
                               or (lonlat == 'lat' and self.y_inline))

                    # Good
                    if visible:
                        break

                if ((self.x_inline and lonlat == 'lon')
                        or (self.y_inline and lonlat == 'lat')):
                    break

            # Action
            artist.set_visible(visible)
            if not visible:
                plt.setp(artist, **orig_specs)
            else:
                paths.append(this_path)

    def _assert_can_draw_ticks(self):
        """
        Check to see if ticks can be drawn. Either returns True or raises
        an exception.

        """
        # Check labelling is supported, currently a limited set of options.
        if not isinstance(self.crs, cartopy.crs.PlateCarree):
            raise TypeError('Cannot label {crs.__class__.__name__} gridlines.'
                            ' Only PlateCarree gridlines are currently '
                            'supported.'.format(crs=self.crs))
        return True

    def _axes_domain(self, nx=None, ny=None, background_patch=None):
        """Return lon_range, lat_range"""
        DEBUG = False

        transform = self._crs_transform()

        ax_transform = self.axes.transAxes
        desired_trans = ax_transform - transform

        nx = nx or 100
        ny = ny or 100
        x = np.linspace(1e-9, 1 - 1e-9, nx)
        y = np.linspace(1e-9, 1 - 1e-9, ny)
        x, y = np.meshgrid(x, y)

        coords = np.column_stack((x.ravel(), y.ravel()))

        in_data = desired_trans.transform(coords)

        ax_to_bkg_patch = self.axes.transAxes - \
            background_patch.get_transform()

        # convert the coordinates of the data to the background patches
        # coordinates
        background_coord = ax_to_bkg_patch.transform(coords)
        ok = background_patch.get_path().contains_points(background_coord)

        if DEBUG:
            import matplotlib.pyplot as plt
            plt.plot(coords[ok, 0],
                     coords[ok, 1],
                     'or',
                     clip_on=False,
                     transform=ax_transform)
            plt.plot(coords[~ok, 0],
                     coords[~ok, 1],
                     'ob',
                     clip_on=False,
                     transform=ax_transform)

        inside = in_data[ok, :]

        # If there were no data points in the axes we just use the x and y
        # range of the projection.
        if inside.size == 0:
            lon_range = self.crs.x_limits
            lat_range = self.crs.y_limits
        else:
            # np.isfinite must be used to prevent np.inf values that
            # not filtered by np.nanmax for some projections
            lat_max = np.compress(np.isfinite(inside[:, 1]), inside[:,
                                                                    1]).max()
            lon_range = np.nanmin(inside[:, 0]), np.nanmax(inside[:, 0])
            lat_range = np.nanmin(inside[:, 1]), lat_max

        # XXX Cartopy specific thing. Perhaps make this bit a specialisation
        # in a subclass...
        crs = self.crs
        if isinstance(crs, Projection):
            lon_range = np.clip(lon_range, *crs.x_limits)
            lat_range = np.clip(lat_range, *crs.y_limits)

            # if the limit is >90% of the full x limit, then just use the full
            # x limit (this makes circular handling better)
            prct = np.abs(np.diff(lon_range) / np.diff(crs.x_limits))
            if prct > 0.9:
                lon_range = crs.x_limits

        return lon_range, lat_range
예제 #4
0
def comp_fig(sa_obj=None, mc_obj=None, coll_obj=None, **kwargs):
    import matplotlib.cm as mplcm
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    import numpy as np
    import cartopy.crs as ccrs
    import cartopy.feature as cfeature
    import cmocean
    from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
    import matplotlib.ticker as mticker
    from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
    from cartopy.mpl.ticker import LatitudeLocator, LongitudeLocator

    # sort out data/coordinates for plotting
    sat = "NA"
    model = "NA"
    """
    If sa_obj is not None get satellite_altimetry data for plotting
    """
    if sa_obj is not None:
        slons, slats = sa_obj.vars['longitude'], sa_obj.vars['latitude']
        svar = sa_obj.vars[sa_obj.stdvarname]
        stdvarname = sa_obj.stdvarname
        sat = sa_obj.mission
    """
    If mc_obj is not None get model data for plotting
    """
    if mc_obj is not None:
        mlons = mc_obj.vars['longitude']
        mlats = mc_obj.vars['latitude']
        mvar = mc_obj.vars[mc_obj.stdvarname]
        # inflate coords if regular lat/lon grid
        if (len(mlons.shape) == 1):
            mlons, mlats = np.meshgrid(mlons, mlats)
        stdvarname = mc_obj.stdvarname
        model = mc_obj.model
    """
    If sa_obj is not None get satellite_altimetry data for plotting
    """
    if sa_obj is None:
        slons, slats = coll_obj.vars['obs_lons'], coll_obj.vars['obs_lats']
        svar = coll_obj.vars['obs_values']
    """
    Get all misc in **kwargs
    """
    """
    Prepare plotting
    """

    # determine region bounds
    if sa_obj is not None:
        if sa_obj.region in region_dict['rect']:
            latmin = region_dict['rect'][sa_obj.region]['llcrnrlat']
            latmax = region_dict['rect'][sa_obj.region]['urcrnrlat']
            lonmin = region_dict['rect'][sa_obj.region]['llcrnrlon']
            lonmax = region_dict['rect'][sa_obj.region]['urcrnrlon']
        elif sa_obj.region in region_dict['geojson']:
            latmin = np.min(sa_obj.vars['latitude']) - .5
            latmax = np.max(sa_obj.vars['latitude']) + .5
            lonmin = np.min(sa_obj.vars['longitude']) - .5
            lonmax = np.max(sa_obj.vars['longitude']) + .5
        elif sa_obj.region in region_dict['poly']:
            latmin = np.min(region_dict['poly'][sa_obj.region]['lats']) - .5
            latmax = np.max(region_dict['poly'][sa_obj.region]['lats']) + .5
            lonmin = np.min(region_dict['poly'][sa_obj.region]['lons']) - .5
            lonmax = np.max(region_dict['poly'][sa_obj.region]['lons']) + .5
        elif sa_obj.region in model_dict:
            # model bounds
            latmin = np.min(mlats)
            latmax = np.max(mlats)
            lonmin = np.min(mlons)
            lonmax = np.max(mlons)
        else:
            print("Error: Region not defined!")
    elif (sa_obj is None and mc_obj is not None):
        # model bounds
        latmin = np.min(mlats)
        latmax = np.max(mlats)
        lonmin = np.min(mlons)
        lonmax = np.max(mlons)

    # determine projection
    """
    Here, a routine is needed to determine a suitable projection.
    As for now, there is Mercator as default.
    """
    projection_default = ccrs.Mercator(
        central_longitude=(lonmin + lonmax) / 2.,
        min_latitude=latmin,
        max_latitude=latmax,
        globe=None,
        latitude_true_scale=(latmin + latmax) / 2.,
        false_easting=0.0,
        false_northing=0.0,
        scale_factor=None)
    projection = kwargs.get('projection', projection_default)

    land = cfeature.GSHHSFeature(scale='i',
                                 levels=[1],
                                 facecolor=cfeature.COLORS['land'])

    # make figure
    fig, ax = plt.subplots(nrows=1,
                           ncols=1,
                           subplot_kw=dict(projection=projection),
                           figsize=(9, 9))
    # plot domain extent
    ax.set_extent([lonmin, lonmax, latmin, latmax], crs=ccrs.PlateCarree())

    # plot model domain if model is available
    if mc_obj is not None:
        ax.plot(mlons[0, :],
                mlats[0, :],
                '-',
                transform=ccrs.PlateCarree(),
                color='gray',
                linewidth=2)
        ax.plot(mlons[-1, :],
                mlats[-1, :],
                '-',
                transform=ccrs.PlateCarree(),
                color='gray',
                linewidth=2)
        ax.plot(mlons[:, 0],
                mlats[:, 0],
                '-',
                transform=ccrs.PlateCarree(),
                color='gray',
                linewidth=2)
        ax.plot(mlons[:, -1],
                mlats[:, -1],
                '-',
                transform=ccrs.PlateCarree(),
                color='gray',
                linewidth=2)

    # plot polygon if defined
    if sa_obj.region in region_dict['poly']:
        ax.plot(region_dict['poly'][sa_obj.region]['lons'],
                region_dict['poly'][sa_obj.region]['lats'],
                '-',
                transform=ccrs.PlateCarree(),
                color='gray',
                linewidth=2)
    # plot polygon from geojson if defined
    if sa_obj.region in region_dict['geojson']:
        import geojson
        import matplotlib.patches as patches
        from matplotlib.patches import Polygon
        fstr = region_dict['geojson'][sa_obj.region]['fstr']
        with open(fstr) as f:
            gj = geojson.load(f)
        fidx = region_dict['geojson'][sa_obj.region].get('fidx')
        if fidx is not None:
            geo = {'type': 'Polygon',
                   'coordinates':\
                    gj['features'][fidx]['geometry']['coordinates'][0]}
            poly = Polygon([tuple(l) for l in geo['coordinates'][0]],
                           closed=True)
            ax.add_patch(\
                patches.Polygon(\
                    poly.get_path().to_polygons()[0],
                    transform=ccrs.PlateCarree(),
                    facecolor='None',
                    edgecolor='red',
                    lw = 3,
                    alpha=0.2))
        else:
            for i in range(len(gj['features'])):
                geo = {'type': 'Polygon',
                        'coordinates':\
                        gj['features'][i]['geometry']['coordinates'][0]}
                poly = Polygon([tuple(l) for l in geo['coordinates'][0]],
                               closed=True)
                ax.add_patch(\
                    patches.Polygon(\
                        poly.get_path().to_polygons()[0],
                        transform=ccrs.PlateCarree(),
                        facecolor='None',
                        edgecolor='red',
                        lw = 3,
                        alpha=0.2))

    # colors
    if stdvarname == 'sea_surface_wave_significant_height':
        cmap = cmocean.cm.amp
        levels = [
            0, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3,
            3.25, 3.5, 3.75, 4, 4.5, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
            17, 18
        ]
    elif stdvarname == 'wind_speed':
        cmap = cmocean.cm.amp
        levels = [
            0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 36,
            40, 44, 48
        ]
    if 'cmap' in kwargs.keys():
        cmap = kwargs['cmap']
    if 'levels' in kwargs.keys():
        levels = kwargs['levels']
    if 'scl' in kwargs.keys():
        scl = kwargs['scl']
    else:
        scl = 18
    if 'icl' in kwargs.keys():
        icl = kwargs['icl']
    else:
        icl = 1

    norm = mpl.colors.BoundaryNorm(levels, cmap.N)
    extend = 'neither'
    if 'extend' in kwargs.keys():
        extend = kwargs['extend']

    if sa_obj.region in quicklook_dict:
        if ('cm_levels' in \
        quicklook_dict[sa_obj.region]['varspec'][sa_obj.varalias]\
        and quicklook_dict[sa_obj.region]['varspec'][sa_obj.varalias]['cm_levels'] is not None):
            levels = quicklook_dict[sa_obj.region]['varspec']\
                    [sa_obj.varalias]['cm_levels']
        if ('scl' in \
        quicklook_dict[sa_obj.region]['varspec'][sa_obj.varalias]\
        and quicklook_dict[sa_obj.region]['varspec'][sa_obj.varalias]['scl'] is not None):
            scl = quicklook_dict[sa_obj.region]['varspec']\
                    [sa_obj.varalias]['scl']
        if ('icl' in \
        quicklook_dict[sa_obj.region]['varspec'][sa_obj.varalias]\
        and quicklook_dict[sa_obj.region]['varspec'][sa_obj.varalias]['icl'] is not None):
            scl = quicklook_dict[sa_obj.region]['varspec']\
                    [sa_obj.varalias]['icl']

    # draw figure features
    mpl.rcParams['contour.negative_linestyle'] = 'solid'
    fs = 11

    # plot lats/lons
    gridcolor = 'gray'
    gl = ax.gridlines(draw_labels=True,
                      crs=ccrs.PlateCarree(),
                      linewidth=1,
                      color=gridcolor,
                      alpha=0.4,
                      linestyle='-')
    gl.top_labels = False
    gl.right_labels = False
    gl.xlabel_style = {'size': fs, 'color': gridcolor}
    gl.ylabel_style = {'size': fs, 'color': gridcolor}
    #gl.xlocator = mticker.FixedLocator([-180, -45, 0, 45, 180])
    gl.xlocator = LongitudeLocator()
    gl.ylocator = LatitudeLocator()
    gl.xformatter = LongitudeFormatter()
    gl.yformatter = LatitudeFormatter()

    # - model contours
    im = ax.contourf(mlons,
                     mlats,
                     mvar,
                     levels=levels,
                     transform=ccrs.PlateCarree(),
                     cmap=cmocean.cm.amp,
                     norm=norm,
                     extend=extend)
    imc = ax.contour(mlons,
                     mlats,
                     mvar,
                     levels=levels[scl::icl],
                     transform=ccrs.PlateCarree(),
                     colors='w',
                     linewidths=0.3)
    ax.clabel(imc, fmt='%2d', colors='w', fontsize=fs)

    # - add coastline
    ax.add_geometries(land.intersecting_geometries(
        [lonmin, lonmax, latmin, latmax]),
                      ccrs.PlateCarree(),
                      facecolor=cfeature.COLORS['land'],
                      edgecolor='black',
                      linewidth=1)

    # - add land color
    ax.add_feature(land, facecolor='burlywood', alpha=0.5)

    # - add satellite
    if len(slats) > 0:
        sc = ax.scatter(slons,
                        slats,
                        s=10,
                        c=svar,
                        marker='o',
                        edgecolor='face',
                        cmap=cmocean.cm.amp,
                        norm=norm,
                        transform=ccrs.PlateCarree())

    # - point of interests depending on region
    if ('quicklook_dict' in globals() and sa_obj.region in quicklook_dict
            and 'poi' in quicklook_dict[sa_obj.region]):
        for poi in quicklook_dict[sa_obj.region]['poi']:
            pname = quicklook_dict[sa_obj.region]['poi'][poi]['name']
            plat = quicklook_dict[sa_obj.region]['poi'][poi]['lat']
            plon = quicklook_dict[sa_obj.region]['poi'][poi]['lon']
            scp = ax.scatter(
                plon,
                plat,
                s=20,
                c='b',
                marker=quicklook_dict[sa_obj.region]['poi'][poi]['marker'],
                transform=ccrs.PlateCarree())
            ax.text(plon, plat, pname, transform=ccrs.PlateCarree())

    # - colorbar
    axins = inset_axes(
        ax,
        width="5%",  # width = 5% of parent_bbox width
        height="100%",  # height : 50%
        loc='lower left',
        bbox_to_anchor=(1.01, 0., 1, 1),
        bbox_transform=ax.transAxes,
        borderpad=0,
    )
    cbar = fig.colorbar(im, cax=axins)
    cbar.ax.set_ylabel(stdvarname + ' [' +
                       variable_info[sa_obj.varalias]['units'] + ']',
                       size=fs)
    cbar.ax.tick_params(labelsize=fs)
    plt.subplots_adjust(bottom=0.1, right=0.8, top=0.9)

    # - title
    ax.set_title(
        model + ' model time step: ' +
        coll_obj.vars['valid_date'][0].strftime("%Y-%m-%d %H%M:%S UTC") +
        '\n' + sat + ' coverage \n from ' +
        coll_obj.vars['datetime'][0].strftime("%Y-%m-%d %H:%M:%S UTC") +
        ' to ' +
        coll_obj.vars['datetime'][-1].strftime("%Y-%m-%d %H:%M:%S UTC"),
        fontsize=fs)

    # - save figure
    if ('savepath' in kwargs.keys() and kwargs['savepath'] != None):
        plt.savefig(kwargs['savepath'] + '/' + model + '_vs_satellite_' +
                    coll_obj.vars['valid_date'][0].strftime("%Y%m%d") + 'T' +
                    coll_obj.vars['valid_date'][0].strftime("%H") + 'Z.png',
                    format='png',
                    dpi=200)

    # - show figure
    if ('showfig' in kwargs.keys() and kwargs['showfig'] == True):
        plt.show()
예제 #5
0
파일: makeMap.py 프로젝트: kylemurray2/PyPS
def mapBackground(bg,
                  minlon,
                  maxlon,
                  minlat,
                  maxlat,
                  pad,
                  zoomLevel,
                  title,
                  borders=True,
                  plotFaults=True):
    '''
    Makes a background map that you can then plot stuff over (footprints, scatterplot, etc.)
    bg: background type from the ARCGIS database choose from the following:
        NatGeo_world_Map
        USA_Topo_Maps
        World_Imagery
        World_Physical_Map
        World_Shaded_Relief 
        World_Street_Map 
        World_Terrain_Base 
        World_Topo_Map 
        Specialty/DeLorme_World_Base_Map
        Specialty/World_Navigation_Charts
        Canvas/World_Dark_Gray_Base 
        Canvas/World_Dark_Gray_Reference
        Canvas/World_Light_Gray_Base 
        Canvas/World_Light_Gray_Reference
        Elevation/World_Hillshade_Dark 
        Elevation/World_Hillshade 
        Ocean/World_Ocean_Base 
        Ocean/World_Ocean_Reference 
        Polar/Antarctic_Imagery
        Polar/Arctic_Imagery
        Polar/Arctic_Ocean_Base
        Polar/Arctic_Ocean_Reference
        Reference/World_Boundaries_and_Places_Alternate
        Reference/World_Boundaries_and_Places
        Reference/World_Reference_Overlay
        Reference/World_Transportation 
        WorldElevation3D/Terrain3D
        WorldElevation3D/TopoBathy3D
    '''

    url = 'https://server.arcgisonline.com/ArcGIS/rest/services/' + bg + '/MapServer/tile/{z}/{y}/{x}.jpg'
    image = cimgt.GoogleTiles(url=url)
    data_crs = ccrs.PlateCarree()
    fig = plt.figure(figsize=(6, 6))
    ax = plt.axes(projection=data_crs)
    ax.set_extent([minlon - pad, maxlon + pad, minlat - pad, maxlat + pad],
                  crs=ccrs.PlateCarree())

    if borders:
        ax.add_feature(cfeature.BORDERS, linewidth=1, color='white')
    # ax.add_feature(cfeature.OCEAN)
    # ax.add_feature(cfeature.LAKES)
    # ax.add_feature(cfeature.RIVERS)

    lon_range = (pad + maxlon) - (minlon - pad)
    lat_range = (pad + maxlat) - (minlat - pad)
    rangeMin = np.min(np.array([lon_range, lat_range]))
    tick_increment = round(rangeMin / 4, 1)

    import matplotlib.ticker as mticker
    from cartopy.mpl.ticker import (LongitudeFormatter, LatitudeFormatter,
                                    LatitudeLocator)

    gl = ax.gridlines(crs=ccrs.PlateCarree(),
                      draw_labels=True,
                      linewidth=0.5,
                      color='gray',
                      alpha=0.5,
                      linestyle='--')
    gl.xlocator = mticker.FixedLocator(
        np.arange(np.floor(minlon - pad), np.ceil(maxlon + pad),
                  tick_increment))
    gl.ylocator = LatitudeLocator()
    gl.xformatter = LongitudeFormatter()
    gl.yformatter = LatitudeFormatter()
    gl.ylabel_style = {'size': 8, 'color': 'black'}
    gl.xlabel_style = {'size': 8, 'color': 'black'}
    gl.top_labels = False
    gl.right_labels = False

    ax.add_image(image, zoomLevel)  #zoom level

    if plotFaults:
        # Plot faults
        import cartopy.io.shapereader as shpreader
        from cartopy.feature import ShapelyFeature
        reader = shpreader.Reader(
            "/d/MapData/gem-global-active-faults/shapefile/gem_active_faults.shp"
        )
        shape_feature = ShapelyFeature(reader.geometries(),
                                       ccrs.PlateCarree(),
                                       edgecolor='r',
                                       facecolor='none',
                                       linewidth=1,
                                       zorder=5,
                                       alpha=0.8)
        ax.add_feature(shape_feature)

    plt.title(title)
    plt.show()
    return plt
예제 #6
0
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import cartopy.crs as ccrs

from cartopy.mpl.ticker import (LongitudeFormatter, LatitudeFormatter,
                                LatitudeLocator)

ax = plt.axes(projection=ccrs.Mercator())
ax.coastlines()

gl = ax.gridlines(crs=ccrs.PlateCarree(),
                  draw_labels=True,
                  linewidth=2,
                  color='gray',
                  alpha=0.5,
                  linestyle='--')
gl.top_labels = False
gl.left_labels = False
gl.xlines = False
gl.xlocator = mticker.FixedLocator([-180, -45, 0, 45, 180])
gl.ylocator = LatitudeLocator()
gl.xformatter = LongitudeFormatter()
gl.yformatter = LatitudeFormatter()
gl.xlabel_style = {'size': 15, 'color': 'gray'}
gl.xlabel_style = {'color': 'red', 'weight': 'bold'}

plt.show()
예제 #7
0
    def __init__(self, axes, crs, draw_labels=False, xlocator=None,
                 ylocator=None, collection_kwargs=None,
                 xformatter=None, yformatter=None, dms=False,
                 x_inline=None, y_inline=None, auto_inline=True):
        """
        Object used by :meth:`cartopy.mpl.geoaxes.GeoAxes.gridlines`
        to add gridlines and tick labels to a map.

        Parameters
        ----------
        axes
            The :class:`cartopy.mpl.geoaxes.GeoAxes` object to be drawn on.
        crs
            The :class:`cartopy.crs.CRS` defining the coordinate system that
            the gridlines are drawn in.
        draw_labels: optional
            Toggle whether to draw labels. For finer control, attributes of
            :class:`Gridliner` may be modified individually. Defaults to False.
        xlocator: optional
            A :class:`matplotlib.ticker.Locator` instance which will be used
            to determine the locations of the gridlines in the x-coordinate of
            the given CRS. Defaults to None, which implies automatic locating
            of the gridlines.
        ylocator: optional
            A :class:`matplotlib.ticker.Locator` instance which will be used
            to determine the locations of the gridlines in the y-coordinate of
            the given CRS. Defaults to None, which implies automatic locating
            of the gridlines.
        xformatter: optional
            A :class:`matplotlib.ticker.Formatter` instance to format
            longitude labels. It defaults to None, which implies the use of a
            :class:`cartopy.mpl.ticker.LongitudeFormatter` initiated
            with the ``dms`` argument.
        yformatter: optional
            A :class:`matplotlib.ticker.Formatter` instance to format
            latitude labels. It defaults to None, which implies the use of a
            :class:`cartopy.mpl.ticker.LatitudeFormatter` initiated
            with the ``dms`` argument.
        collection_kwargs: optional
            Dictionary controlling line properties, passed to
            :class:`matplotlib.collections.Collection`. Defaults to None.
        dms: bool
            When default locators and formatters are used,
            ticks are able to stop on minutes and seconds if minutes
            is set to True, and not fraction of degrees.
        x_inline: optional
            Toggle whether the x labels drawn should be inline.
        y_inline: optional
            Toggle whether the y labels drawn should be inline.
        auto_inline: optional
            Set x_inline and y_inline automatically based on projection

        .. note:: Note that the "x" and "y" labels for locators and
             formatters do not necessarily correspond to X and Y,
             but to longitudes and latitudes: indeed, according to
             geographical projections, meridians and parallels can
             cross both the X axis and the Y axis.
        """
        self.axes = axes

        #: The :class:`~matplotlib.ticker.Locator` to use for the x
        #: gridlines and labels.
        if xlocator is not None:
            if not isinstance(xlocator, mticker.Locator):
                xlocator = mticker.FixedLocator(xlocator)
            self.xlocator = xlocator
        elif isinstance(crs, cartopy.crs.PlateCarree):
            self.xlocator = LongitudeLocator(dms=dms)
        else:
            self.xlocator = classic_locator

        #: The :class:`~matplotlib.ticker.Locator` to use for the y
        #: gridlines and labels.
        if ylocator is not None:
            if not isinstance(ylocator, mticker.Locator):
                ylocator = mticker.FixedLocator(ylocator)
            self.ylocator = ylocator
        elif isinstance(crs, cartopy.crs.PlateCarree):
            self.ylocator = LatitudeLocator(dms=dms)
        else:
            self.ylocator = classic_locator

        #: The :class:`~matplotlib.ticker.Formatter` to use for the lon labels.
        self.xformatter = xformatter or LongitudeFormatter(dms=dms)

        #: The :class:`~matplotlib.ticker.Formatter` to use for the lat labels.
        self.yformatter = yformatter or LatitudeFormatter(dms=dms)

        #: Whether to draw labels on the top of the map.
        self.top_labels = draw_labels

        #: Whether to draw labels on the bottom of the map.
        self.bottom_labels = draw_labels

        #: Whether to draw labels on the left hand side of the map.
        self.left_labels = draw_labels

        #: Whether to draw labels on the right hand side of the map.
        self.right_labels = draw_labels

        if auto_inline:
            if isinstance(self.axes.projection, _X_INLINE_PROJS):
                self.x_inline = True
                self.y_inline = False
            elif isinstance(self.axes.projection, _POLAR_PROJS):
                self.x_inline = False
                self.y_inline = True
            else:
                self.x_inline = False
                self.y_inline = False

        # overwrite auto_inline if necessary
        if x_inline is not None:
            #: Whether to draw x labels inline
            self.x_inline = x_inline
        elif not auto_inline:
            self.x_inline = False

        if y_inline is not None:
            #: Whether to draw y labels inline
            self.y_inline = y_inline
        elif not auto_inline:
            self.y_inline = False

        #: Whether to draw the longitude gridlines (meridians).
        self.xlines = True

        #: Whether to draw the latitude gridlines (parallels).
        self.ylines = True

        #: A dictionary passed through to ``ax.text`` on x label creation
        #: for styling of the text labels.
        self.xlabel_style = {}

        #: A dictionary passed through to ``ax.text`` on y label creation
        #: for styling of the text labels.
        self.ylabel_style = {}

        #: The padding from the map edge to the x labels in points.
        self.xpadding = 5

        #: The padding from the map edge to the y labels in points.
        self.ypadding = 5

        #: Allow the rotation of labels.
        self.rotate_labels = True

        # Current transform
        self.crs = crs

        # if the user specifies tick labels at this point, check if they can
        # be drawn. The same check will take place at draw time in case
        # public attributes are changed after instantiation.
        if draw_labels and not (x_inline or y_inline or auto_inline):
            self._assert_can_draw_ticks()

        #: The number of interpolation points which are used to draw the
        #: gridlines.
        self.n_steps = 100

        #: A dictionary passed through to
        #: ``matplotlib.collections.LineCollection`` on grid line creation.
        self.collection_kwargs = collection_kwargs

        #: The x gridlines which were created at draw time.
        self.xline_artists = []

        #: The y gridlines which were created at draw time.
        self.yline_artists = []

        # Plotted status
        self._plotted = False

        # Check visibility of labels at each draw event
        # (or once drawn, only at resize event ?)
        self.axes.figure.canvas.mpl_connect('draw_event', self._draw_event)
예제 #8
0
class Gridliner(object):
    # NOTE: In future, one of these objects will be add-able to a GeoAxes (and
    # maybe even a plain old mpl axes) and it will call the "_draw_gridliner"
    # method on draw. This will enable automatic gridline resolution
    # determination on zoom/pan.
    def __init__(self, axes, crs, draw_labels=False, xlocator=None,
                 ylocator=None, collection_kwargs=None,
                 xformatter=None, yformatter=None, dms=False,
                 x_inline=None, y_inline=None, auto_inline=True):
        """
        Object used by :meth:`cartopy.mpl.geoaxes.GeoAxes.gridlines`
        to add gridlines and tick labels to a map.

        Parameters
        ----------
        axes
            The :class:`cartopy.mpl.geoaxes.GeoAxes` object to be drawn on.
        crs
            The :class:`cartopy.crs.CRS` defining the coordinate system that
            the gridlines are drawn in.
        draw_labels: optional
            Toggle whether to draw labels. For finer control, attributes of
            :class:`Gridliner` may be modified individually. Defaults to False.
        xlocator: optional
            A :class:`matplotlib.ticker.Locator` instance which will be used
            to determine the locations of the gridlines in the x-coordinate of
            the given CRS. Defaults to None, which implies automatic locating
            of the gridlines.
        ylocator: optional
            A :class:`matplotlib.ticker.Locator` instance which will be used
            to determine the locations of the gridlines in the y-coordinate of
            the given CRS. Defaults to None, which implies automatic locating
            of the gridlines.
        xformatter: optional
            A :class:`matplotlib.ticker.Formatter` instance to format
            longitude labels. It defaults to None, which implies the use of a
            :class:`cartopy.mpl.ticker.LongitudeFormatter` initiated
            with the ``dms`` argument.
        yformatter: optional
            A :class:`matplotlib.ticker.Formatter` instance to format
            latitude labels. It defaults to None, which implies the use of a
            :class:`cartopy.mpl.ticker.LatitudeFormatter` initiated
            with the ``dms`` argument.
        collection_kwargs: optional
            Dictionary controlling line properties, passed to
            :class:`matplotlib.collections.Collection`. Defaults to None.
        dms: bool
            When default locators and formatters are used,
            ticks are able to stop on minutes and seconds if minutes
            is set to True, and not fraction of degrees.
        x_inline: optional
            Toggle whether the x labels drawn should be inline.
        y_inline: optional
            Toggle whether the y labels drawn should be inline.
        auto_inline: optional
            Set x_inline and y_inline automatically based on projection

        .. note:: Note that the "x" and "y" labels for locators and
             formatters do not necessarily correspond to X and Y,
             but to longitudes and latitudes: indeed, according to
             geographical projections, meridians and parallels can
             cross both the X axis and the Y axis.
        """
        self.axes = axes

        #: The :class:`~matplotlib.ticker.Locator` to use for the x
        #: gridlines and labels.
        if xlocator is not None:
            if not isinstance(xlocator, mticker.Locator):
                xlocator = mticker.FixedLocator(xlocator)
            self.xlocator = xlocator
        elif isinstance(crs, cartopy.crs.PlateCarree):
            self.xlocator = LongitudeLocator(dms=dms)
        else:
            self.xlocator = classic_locator

        #: The :class:`~matplotlib.ticker.Locator` to use for the y
        #: gridlines and labels.
        if ylocator is not None:
            if not isinstance(ylocator, mticker.Locator):
                ylocator = mticker.FixedLocator(ylocator)
            self.ylocator = ylocator
        elif isinstance(crs, cartopy.crs.PlateCarree):
            self.ylocator = LatitudeLocator(dms=dms)
        else:
            self.ylocator = classic_locator

        #: The :class:`~matplotlib.ticker.Formatter` to use for the lon labels.
        self.xformatter = xformatter or LongitudeFormatter(dms=dms)

        #: The :class:`~matplotlib.ticker.Formatter` to use for the lat labels.
        self.yformatter = yformatter or LatitudeFormatter(dms=dms)

        #: Whether to draw labels on the top of the map.
        self.top_labels = draw_labels

        #: Whether to draw labels on the bottom of the map.
        self.bottom_labels = draw_labels

        #: Whether to draw labels on the left hand side of the map.
        self.left_labels = draw_labels

        #: Whether to draw labels on the right hand side of the map.
        self.right_labels = draw_labels

        if auto_inline:
            if isinstance(self.axes.projection, _X_INLINE_PROJS):
                self.x_inline = True
                self.y_inline = False
            elif isinstance(self.axes.projection, _POLAR_PROJS):
                self.x_inline = False
                self.y_inline = True
            else:
                self.x_inline = False
                self.y_inline = False

        # overwrite auto_inline if necessary
        if x_inline is not None:
            #: Whether to draw x labels inline
            self.x_inline = x_inline
        elif not auto_inline:
            self.x_inline = False

        if y_inline is not None:
            #: Whether to draw y labels inline
            self.y_inline = y_inline
        elif not auto_inline:
            self.y_inline = False

        #: Whether to draw the longitude gridlines (meridians).
        self.xlines = True

        #: Whether to draw the latitude gridlines (parallels).
        self.ylines = True

        #: A dictionary passed through to ``ax.text`` on x label creation
        #: for styling of the text labels.
        self.xlabel_style = {}

        #: A dictionary passed through to ``ax.text`` on y label creation
        #: for styling of the text labels.
        self.ylabel_style = {}

        #: The padding from the map edge to the x labels in points.
        self.xpadding = 5

        #: The padding from the map edge to the y labels in points.
        self.ypadding = 5

        #: Allow the rotation of labels.
        self.rotate_labels = True

        # Current transform
        self.crs = crs

        # if the user specifies tick labels at this point, check if they can
        # be drawn. The same check will take place at draw time in case
        # public attributes are changed after instantiation.
        if draw_labels and not (x_inline or y_inline or auto_inline):
            self._assert_can_draw_ticks()

        #: The number of interpolation points which are used to draw the
        #: gridlines.
        self.n_steps = 100

        #: A dictionary passed through to
        #: ``matplotlib.collections.LineCollection`` on grid line creation.
        self.collection_kwargs = collection_kwargs

        #: The x gridlines which were created at draw time.
        self.xline_artists = []

        #: The y gridlines which were created at draw time.
        self.yline_artists = []

        # Plotted status
        self._plotted = False

        # Check visibility of labels at each draw event
        # (or once drawn, only at resize event ?)
        self.axes.figure.canvas.mpl_connect('draw_event', self._draw_event)

    def _draw_event(self, event):
        if self.has_labels():
            self._update_labels_visibility(event.renderer)

    def has_labels(self):
        return hasattr(self, '_labels') and self._labels

    @property
    def label_artists(self):
        if self.has_labels():
            return self._labels
        return []

    def _crs_transform(self):
        """
        Get the drawing transform for our gridlines.

        Note
        ----
            The drawing transform depends on the transform of our 'axes', so
            it may change dynamically.

        """
        transform = self.crs
        if not isinstance(transform, mtrans.Transform):
            transform = transform._as_mpl_transform(self.axes)
        return transform

    @staticmethod
    def _round(x, base=5):
        if np.isnan(base):
            base = 5
        return int(base * round(float(x) / base))

    def _find_midpoints(self, lim, ticks):
        # find the cneter point between each lat gridline
        cent = np.diff(ticks).mean() / 2
        if isinstance(self.axes.projection, _POLAR_PROJS):
            lq = 90
            uq = 90
        else:
            lq = 25
            uq = 75
        midpoints = (self._round(np.percentile(lim, lq), cent),
                     self._round(np.percentile(lim, uq), cent))
        return midpoints

    def _draw_gridliner(self, nx=None, ny=None, background_patch=None,
                        renderer=None):
        """Create Artists for all visible elements and add to our Axes."""
        # Check status
        if self._plotted:
            return
        self._plotted = True

        # Inits
        lon_lim, lat_lim = self._axes_domain(
            nx=nx, ny=ny, background_patch=background_patch)

        transform = self._crs_transform()
        rc_params = matplotlib.rcParams
        n_steps = self.n_steps
        crs = self.crs

        # Get nice ticks within crs domain
        lon_ticks = self.xlocator.tick_values(lon_lim[0], lon_lim[1])
        lat_ticks = self.ylocator.tick_values(lat_lim[0], lat_lim[1])
        lon_ticks = [value for value in lon_ticks
                     if value >= max(lon_lim[0], crs.x_limits[0]) and
                     value <= min(lon_lim[1], crs.x_limits[1])]
        lat_ticks = [value for value in lat_ticks
                     if value >= max(lat_lim[0], crs.y_limits[0]) and
                     value <= min(lat_lim[1], crs.y_limits[1])]

        #####################
        # Gridlines drawing #
        #####################

        collection_kwargs = self.collection_kwargs
        if collection_kwargs is None:
            collection_kwargs = {}
        collection_kwargs = collection_kwargs.copy()
        collection_kwargs['transform'] = transform
        # XXX doesn't gracefully handle lw vs linewidth aliases...
        collection_kwargs.setdefault('color', rc_params['grid.color'])
        collection_kwargs.setdefault('linestyle', rc_params['grid.linestyle'])
        collection_kwargs.setdefault('linewidth', rc_params['grid.linewidth'])

        # Meridians
        lon_lines = []
        lat_min, lat_max = lat_lim
        if lat_ticks:
            lat_min = min(lat_min, min(lat_ticks))
            lat_max = max(lat_max, max(lat_ticks))
        for x in lon_ticks:
            ticks = list(zip(
                [x]*n_steps,
                np.linspace(lat_min, lat_max, n_steps)))
            lon_lines.append(ticks)

        if self.xlines:
            nx = len(lon_lines) + 1
            # XXX this bit is cartopy specific. (for circular longitudes)
            # Purpose: omit plotting the last x line,
            # as it may overlap the first.
            if (isinstance(crs, Projection) and
                    isinstance(crs, _RectangularProjection) and
                    abs(np.diff(lon_lim)) == abs(np.diff(crs.x_limits))):
                nx -= 1
            lon_lc = mcollections.LineCollection(lon_lines,
                                                 **collection_kwargs)
            self.xline_artists.append(lon_lc)
            self.axes.add_collection(lon_lc, autolim=False)

        # Parallels
        lat_lines = []
        lon_min, lon_max = lon_lim
        if lon_ticks:
            lon_min = min(lon_min, min(lon_ticks))
            lon_max = max(lon_max, max(lon_ticks))
        for y in lat_ticks:
            ticks = list(zip(
                np.linspace(lon_min, lon_max, n_steps),
                [y]*n_steps))
            lat_lines.append(ticks)
        if self.ylines:
            lat_lc = mcollections.LineCollection(lat_lines,
                                                 **collection_kwargs)
            self.yline_artists.append(lat_lc)
            self.axes.add_collection(lat_lc, autolim=False)

        #################
        # Label drawing #
        #################

        self.bottom_label_artists = []
        self.top_label_artists = []
        self.left_label_artists = []
        self.right_label_artists = []
        if not (self.left_labels or self.right_labels or
                self.bottom_labels or self.top_labels):
            return
        self._assert_can_draw_ticks()

        # Get the real map boundaries
        map_boundary_vertices = self.axes.background_patch.get_path().vertices
        map_boundary = sgeom.Polygon(map_boundary_vertices)

        self._labels = []

        if self.x_inline:
            y_midpoints = self._find_midpoints(lat_lim, lat_ticks)
        if self.y_inline:
            x_midpoints = self._find_midpoints(lon_lim, lon_ticks)

        for lonlat, lines, line_ticks, formatter, label_style in (
                ('lon', lon_lines, lon_ticks,
                 self.xformatter, self.xlabel_style),
                ('lat', lat_lines, lat_ticks,
                 self.yformatter, self.ylabel_style)):

            formatter.set_locs(line_ticks)

            # lines = lines[::2]
            # line_ticks = line_ticks[::2]
            for line, tick_value in zip(lines, line_ticks):
                # Intersection of line with map boundary
                line = np.array(line)
                line = self.axes.projection.transform_points(
                    crs, line[:, 0], line[:, 1])[:, :2]
                infs = np.isinf(line)
                if infs.any():
                    if infs.all():
                        continue
                    line = line.compress(~infs.any(axis=1), axis=0)
                line = sgeom.LineString(line)
                if line.intersects(map_boundary):
                    intersection = line.intersection(map_boundary)
                    del line
                    if intersection.is_empty:
                        continue
                    if isinstance(intersection, sgeom.MultiPoint):
                        if len(intersection) < 2:
                            continue
                        tails = [[(pt.x, pt.y) for pt in intersection[:2]]]
                        heads = [[(pt.x, pt.y)
                                  for pt in intersection[-1:-3:-1]]]
                    elif isinstance(intersection, (sgeom.LineString,
                                                   sgeom.MultiLineString)):
                        if isinstance(intersection, sgeom.LineString):
                            intersection = [intersection]
                        elif len(intersection) > 4:
                            # Gridline and map boundary are parallel
                            # and they intersect themselves too much
                            # it results in a multiline string
                            # that must be converted to a single linestring.
                            # This is an empirical workaround for a problem
                            # that can probably be solved in a cleaner way.
                            x, y = intersection[0].coords.xy
                            x += intersection[-1].coords.xy[0]
                            y += intersection[-1].coords.xy[1]
                            xy = np.array((x, y))
                            intersection = [sgeom.LineString(xy.T)]
                        tails = []
                        heads = []
                        for inter in intersection:
                            if len(inter.coords) < 2:
                                continue
                            tails.append(inter.coords[:2])
                            heads.append(inter.coords[-1:-3:-1])
                        if not tails:
                            continue
                    elif isinstance(intersection,
                                    sgeom.collection.GeometryCollection):
                        # This is a collection of Point and LineString that
                        # represent the same gridline. We only consider
                        # the first and last geometries, merge their
                        # coordinates and keep first or last two points
                        # to get only one tail and and one head.
                        tails = []
                        heads = []
                        for ht, slicer in [(tails, slice(0, 2)),
                                           (heads, slice(-1, -3, -1))]:
                            x = array('d', [])
                            y = array('d', [])
                            for geom in list(intersection.geoms)[slicer]:
                                x += geom.xy[0]
                                y += geom.xy[1]
                            ht.append(list(zip(x[slicer], y[slicer])))
                    else:
                        warn('Unsupported intersection geometry for gridline'
                             'labels: '+intersection.__class__)
                        continue
                    del intersection

                    # Loop on head and tail and plot label by extrapolation
                    for tail, head in zip(tails, heads):
                        for i, (pt0, pt1) in enumerate([tail, head]):
                            kw, angle, loc = self._segment_to_text_specs(
                                pt0, pt1, lonlat)
                            if not getattr(self, loc+'_labels'):
                                continue
                            kw.update(label_style,
                                      bbox={'pad': 0, 'visible': False})
                            text = formatter(tick_value)

                            if self.y_inline and lonlat == 'lat':
                                # 180 degrees isn't formatted with a
                                # suffix and adds confusion if it's inline
                                if abs(tick_value) == 180:
                                    continue
                                x = x_midpoints[i]
                                y = tick_value
                                y_set = True
                            else:
                                x = pt0[0]
                                y_set = False

                            if self.x_inline and lonlat == 'lon':
                                if abs(tick_value) == 180:
                                    continue
                                x = tick_value
                                y = y_midpoints[i]
                            elif not y_set:
                                y = pt0[1]

                            tt = self.axes.text(x, y, text, **kw)
                            tt._angle = angle
                            priority = (((lonlat == 'lon') and
                                         loc in ('bottom', 'top')) or
                                        ((lonlat == 'lat') and
                                         loc in ('left', 'right')))
                            self._labels.append((lonlat, priority, tt))
                            getattr(self, loc + '_label_artists').append(tt)

        # Sort labels
        if self._labels:
            self._labels.sort(key=operator.itemgetter(0), reverse=True)
            self._update_labels_visibility(renderer)

    def _segment_to_text_specs(self, pt0, pt1, lonlat):
        """Get appropriate kwargs for a label from lon or lat line segment"""
        x0, y0 = pt0
        x1, y1 = pt1
        angle = np.arctan2(y0-y1, x0-x1) * 180 / np.pi
        kw, loc = self._segment_angle_to_text_specs(angle, lonlat)
        return kw, angle, loc

    def _text_angle_to_specs_(self, angle, lonlat):
        """Get specs for a rotated label from its angle in degrees"""

        if matplotlib.__version__ >= '3.1':
            # rotation_mode='anchor' and va_align_center='center_baseline'
            # are incompatible before mpl-3.1
            va_align_center = 'center_baseline'
        else:
            va_align_center = 'center'

        angle %= 360
        if angle > 180:
            angle -= 360

        if ((self.x_inline and lonlat == 'lon') or
                (self.y_inline and lonlat == 'lat')):
            kw = {'rotation': 0, 'rotation_mode': 'anchor',
                  'ha': 'center', 'va': 'center'}
            loc = 'bottom'
            return kw, loc

        # Default options
        kw = {'rotation': angle, 'rotation_mode': 'anchor'}

        # Options that depend in which quarter the angle falls
        if abs(angle) <= 45:

            loc = 'right'
            kw.update(ha='left', va=va_align_center)

        elif abs(angle) >= 135:

            loc = 'left'
            kw.update(ha='right', va=va_align_center)
            kw['rotation'] -= np.sign(angle) * 180

        elif angle > 45:

            loc = 'top'
            kw.update(ha='center', va='bottom', rotation=angle-90)

        else:

            loc = 'bottom'
            kw.update(ha='center', va='top', rotation=angle+90)

        return kw, loc

    def _segment_angle_to_text_specs(self, angle, lonlat):
        """Get appropriate kwargs for a given text angle"""
        kw, loc = self._text_angle_to_specs_(angle, lonlat)
        if not self.rotate_labels:
            angle = {'top': 90., 'right': 0.,
                     'bottom': -90., 'left': 180.}[loc]
            del kw['rotation']

        if ((self.x_inline and lonlat == 'lon') or
                (self.y_inline and lonlat == 'lat')):
            kw.update(transform=cartopy.crs.PlateCarree())
        else:
            xpadding = (self.xpadding if self.xpadding is not None
                        else matplotlib.rc_params['xtick.major.pad'])
            ypadding = (self.ypadding if self.ypadding is not None
                        else matplotlib.rc_params['ytick.major.pad'])
            dx = ypadding * np.cos(angle * np.pi / 180)
            dy = xpadding * np.sin(angle * np.pi / 180)
            transform = mtrans.offset_copy(
                self.axes.transData, self.axes.figure,
                x=dx, y=dy, units='dots')
            kw.update(transform=transform)

        return kw, loc

    def _update_labels_visibility(self, renderer):
        """Update the visibility of each plotted label

        The following rules apply:

        - Labels are plotted and checked by order of priority,
          with a high priority for longitude labels at the bottom and
          top of the map, and the reverse for latitude labels.
        - A label must not overlap another label marked as visible.
        - A label must not overlap the map boundary.
        - When a label is about to be hidden, other angles are tried in the
          absolute given limit of max_delta_angle by increments of delta_angle
          of difference from the original angle.
        """
        if renderer is None or not self._labels:
            return
        paths = []
        outline_path = None
        delta_angle = 22.5
        max_delta_angle = 45
        axes_children = self.axes.get_children()

        for lonlat, priority, artist in self._labels:

            if artist not in axes_children:
                warn('The labels of this gridliner do not belong'
                     'to the gridliner axes')

            # Compute angles to try
            orig_specs = {'rotation': artist.get_rotation(),
                          'ha': artist.get_ha(),
                          'va': artist.get_va()}
            angles = [None]
            for abs_delta_angle in np.arange(delta_angle, max_delta_angle+1,
                                             delta_angle):
                for sign_delta_angle in (1, -1):
                    angle = artist._angle + sign_delta_angle * abs_delta_angle
                    angles.append(angle)

            # Loop on angles until it works
            for angle in angles:
                if ((self.x_inline and lonlat == 'lon') or
                        (self.y_inline and lonlat == 'lat')):
                    angle = 0

                if angle is not None:
                    specs, _ = self._segment_angle_to_text_specs(angle, lonlat)
                    plt.setp(artist, **specs)

                artist.update_bbox_position_size(renderer)
                this_patch = artist.get_bbox_patch()
                this_path = this_patch.get_path().transformed(
                    this_patch.get_transform())
                visible = False

                for path in paths:

                    # Check it does not overlap another label
                    if this_path.intersects_path(path):
                        break

                else:

                    # Finally check that it does not overlap the map
                    if outline_path is None:
                        outline_path = self.axes.background_patch.get_path(
                        ).transformed(self.axes.transData)
                    visible = (not outline_path.intersects_path(this_path) or
                               (lonlat == 'lon' and self.x_inline) or
                               (lonlat == 'lat' and self.y_inline))

                    # Good
                    if visible:
                        break

                if ((self.x_inline and lonlat == 'lon') or
                        (self.y_inline and lonlat == 'lat')):
                    break

            # Action
            artist.set_visible(visible)
            if not visible:
                plt.setp(artist, **orig_specs)
            else:
                paths.append(this_path)

    def _assert_can_draw_ticks(self):
        """
        Check to see if ticks can be drawn. Either returns True or raises
        an exception.

        """
        # Check labelling is supported, currently a limited set of options.
        if not isinstance(self.crs, cartopy.crs.PlateCarree):
            raise TypeError('Cannot label {crs.__class__.__name__} gridlines.'
                            ' Only PlateCarree gridlines are currently '
                            'supported.'.format(crs=self.crs))
        return True

    def _axes_domain(self, nx=None, ny=None, background_patch=None):
        """Return lon_range, lat_range"""
        DEBUG = False

        transform = self._crs_transform()

        ax_transform = self.axes.transAxes
        desired_trans = ax_transform - transform

        nx = nx or 100
        ny = ny or 100
        x = np.linspace(1e-9, 1 - 1e-9, nx)
        y = np.linspace(1e-9, 1 - 1e-9, ny)
        x, y = np.meshgrid(x, y)

        coords = np.column_stack((x.ravel(), y.ravel()))

        in_data = desired_trans.transform(coords)

        ax_to_bkg_patch = self.axes.transAxes - \
            background_patch.get_transform()

        # convert the coordinates of the data to the background patches
        # coordinates
        background_coord = ax_to_bkg_patch.transform(coords)
        ok = background_patch.get_path().contains_points(background_coord)

        if DEBUG:
            import matplotlib.pyplot as plt
            plt.plot(coords[ok, 0], coords[ok, 1], 'or',
                     clip_on=False, transform=ax_transform)
            plt.plot(coords[~ok, 0], coords[~ok, 1], 'ob',
                     clip_on=False, transform=ax_transform)

        inside = in_data[ok, :]

        # If there were no data points in the axes we just use the x and y
        # range of the projection.
        if inside.size == 0:
            lon_range = self.crs.x_limits
            lat_range = self.crs.y_limits
        else:
            # np.isfinite must be used to prevent np.inf values that
            # not filtered by np.nanmax for some projections
            lat_max = np.compress(np.isfinite(inside[:, 1]),
                                  inside[:, 1]).max()
            lon_range = np.nanmin(inside[:, 0]), np.nanmax(inside[:, 0])
            lat_range = np.nanmin(inside[:, 1]), lat_max

        # XXX Cartopy specific thing. Perhaps make this bit a specialisation
        # in a subclass...
        crs = self.crs
        if isinstance(crs, Projection):
            lon_range = np.clip(lon_range, *crs.x_limits)
            lat_range = np.clip(lat_range, *crs.y_limits)

            # if the limit is >90% of the full x limit, then just use the full
            # x limit (this makes circular handling better)
            prct = np.abs(np.diff(lon_range) / np.diff(crs.x_limits))
            if prct > 0.9:
                lon_range = crs.x_limits

        return lon_range, lat_range
예제 #9
0
    def __init__(self, axes, crs, draw_labels=False, xlocator=None,
                 ylocator=None, collection_kwargs=None,
                 xformatter=None, yformatter=None, dms=False,
                 x_inline=None, y_inline=None, auto_inline=True,
                 xlim=None, ylim=None, rotate_labels=None,
                 xlabel_style=None, ylabel_style=None, labels_bbox_style=None,
                 xpadding=5, ypadding=5, offset_angle=25,
                 auto_update=False, formatter_kwargs=None):
        """
        Object used by :meth:`cartopy.mpl.geoaxes.GeoAxes.gridlines`
        to add gridlines and tick labels to a map.

        Parameters
        ----------
        axes
            The :class:`cartopy.mpl.geoaxes.GeoAxes` object to be drawn on.
        crs
            The :class:`cartopy.crs.CRS` defining the coordinate system that
            the gridlines are drawn in.
        draw_labels: optional
            Toggle whether to draw labels. For finer control, attributes of
            :class:`Gridliner` may be modified individually. Defaults to False.

            - string: "x" or "y" to only draw labels of the respective
              coordinate in the CRS.
            - list: Can contain the side identifiers and/or coordinate
              types to select which ones to draw.
              For all labels one would use
              `["x", "y", "top", "bottom", "left", "right", "geo"]`.
            - dict: The keys are the side identifiers
              ("top", "bottom", "left", "right") and the values are the
              coordinates ("x", "y"); this way you can precisely
              decide what kind of label to draw and where.
              For x labels on the bottom and y labels on the right you
              could pass in `{"bottom": "x", "left": "y"}`.

            Note that, by default, x and y labels are not drawn on left/right
            and top/bottom edges respectively, unless explicitly requested.

        xlocator: optional
            A :class:`matplotlib.ticker.Locator` instance which will be used
            to determine the locations of the gridlines in the x-coordinate of
            the given CRS. Defaults to None, which implies automatic locating
            of the gridlines.
        ylocator: optional
            A :class:`matplotlib.ticker.Locator` instance which will be used
            to determine the locations of the gridlines in the y-coordinate of
            the given CRS. Defaults to None, which implies automatic locating
            of the gridlines.
        xformatter: optional
            A :class:`matplotlib.ticker.Formatter` instance to format labels
            for x-coordinate gridlines. It defaults to None, which implies the
            use of a :class:`cartopy.mpl.ticker.LongitudeFormatter` initiated
            with the ``dms`` argument, if the crs is of
            :class:`~cartopy.crs.PlateCarree` type.
        yformatter: optional
            A :class:`matplotlib.ticker.Formatter` instance to format labels
            for y-coordinate gridlines. It defaults to None, which implies the
            use of a :class:`cartopy.mpl.ticker.LatitudeFormatter` initiated
            with the ``dms`` argument, if the crs is of
            :class:`~cartopy.crs.PlateCarree` type.
        collection_kwargs: optional
            Dictionary controlling line properties, passed to
            :class:`matplotlib.collections.Collection`. Defaults to None.
        dms: bool
            When default locators and formatters are used,
            ticks are able to stop on minutes and seconds if minutes
            is set to True, and not fraction of degrees.
        x_inline: optional
            Toggle whether the x labels drawn should be inline.
        y_inline: optional
            Toggle whether the y labels drawn should be inline.
        auto_inline: optional
            Set x_inline and y_inline automatically based on projection.
        xlim: optional
            Set a limit for the gridlines so that they do not go all the
            way to the edge of the boundary. xlim can be a single number or
            a (min, max) tuple. If a single number, the limits will be
            (-xlim, +xlim).
        ylim: optional
            Set a limit for the gridlines so that they do not go all the
            way to the edge of the boundary. ylim can be a single number or
            a (min, max) tuple. If a single number, the limits will be
            (-ylim, +ylim).
        rotate_labels: optional, bool, str
            Allow the rotation of non-inline labels.

            - False: Do not rotate the labels.
            - True: Rotate the labels parallel to the gridlines.
            - None: no rotation except for some projections (default).
            - A float: Rotate labels by this value in degrees.

        xlabel_style: dict
            A dictionary passed through to ``ax.text`` on x label creation
            for styling of the text labels.
        ylabel_style: dict
            A dictionary passed through to ``ax.text`` on y label creation
            for styling of the text labels.
        labels_bbox_style: dict
            bbox style for all text labels
        xpadding: float
            Padding for x labels. If negative, the labels are
            drawn inside the map.
        ypadding: float
            Padding for y labels. If negative, the labels are
            drawn inside the map.
        offset_angle: float
            Difference of angle in degrees from 90 to define when
            a label must be flipped to be more readable.
            For example, a value of 10 makes a vertical top label to be
            flipped only at 100 degrees.
        auto_update: bool
            Whether to redraw the gridlines and labels when the figure is
            updated.
        formatter_kwargs: dict, optional
            Options passed to the default formatters.
            See :class:`~cartopy.mpl.ticker.LongitudeFormatter` and
            :class:`~cartopy.mpl.ticker.LatitudeFormatter`

        Notes
        -----
        The "x" and "y" labels for locators and formatters do not necessarily
        correspond to X and Y, but to the first and second coordinates of the
        specified CRS. For the common case of PlateCarree gridlines, these
        correspond to longitudes and latitudes. Depending on the projection
        used for the map, meridians and parallels can cross both the X axis and
        the Y axis.
        """
        self.axes = axes

        #: The :class:`~matplotlib.ticker.Locator` to use for the x
        #: gridlines and labels.
        if xlocator is not None:
            if not isinstance(xlocator, mticker.Locator):
                xlocator = mticker.FixedLocator(xlocator)
            self.xlocator = xlocator
        elif isinstance(crs, PlateCarree):
            self.xlocator = LongitudeLocator(dms=dms)
        else:
            self.xlocator = classic_locator

        #: The :class:`~matplotlib.ticker.Locator` to use for the y
        #: gridlines and labels.
        if ylocator is not None:
            if not isinstance(ylocator, mticker.Locator):
                ylocator = mticker.FixedLocator(ylocator)
            self.ylocator = ylocator
        elif isinstance(crs, PlateCarree):
            self.ylocator = LatitudeLocator(dms=dms)
        else:
            self.ylocator = classic_locator

        formatter_kwargs = {
            **(formatter_kwargs or {}),
            "dms": dms,
        }

        if xformatter is None:
            if isinstance(crs, PlateCarree):
                xformatter = LongitudeFormatter(**formatter_kwargs)
            else:
                xformatter = classic_formatter()
        #: The :class:`~matplotlib.ticker.Formatter` to use for the lon labels.
        self.xformatter = xformatter

        if yformatter is None:
            if isinstance(crs, PlateCarree):
                yformatter = LatitudeFormatter(**formatter_kwargs)
            else:
                yformatter = classic_formatter()
        #: The :class:`~matplotlib.ticker.Formatter` to use for the lat labels.
        self.yformatter = yformatter

        # Draw label argument
        if isinstance(draw_labels, list):

            # Select to which coordinate it is applied
            if 'x' not in draw_labels and 'y' not in draw_labels:
                value = True
            elif 'x' in draw_labels and 'y' in draw_labels:
                value = ['x', 'y']
            elif 'x' in draw_labels:
                value = 'x'
            else:
                value = 'y'

            #: Whether to draw labels on the top of the map.
            self.top_labels = value if 'top' in draw_labels else False

            #: Whether to draw labels on the bottom of the map.
            self.bottom_labels = value if 'bottom' in draw_labels else False

            #: Whether to draw labels on the left hand side of the map.
            self.left_labels = value if 'left' in draw_labels else False

            #: Whether to draw labels on the right hand side of the map.
            self.right_labels = value if 'right' in draw_labels else False

            #: Whether to draw labels near the geographic limits of the map.
            self.geo_labels = value if 'geo' in draw_labels else False

        elif isinstance(draw_labels, dict):

            self.top_labels = draw_labels.get('top', False)
            self.bottom_labels = draw_labels.get('bottom', False)
            self.left_labels = draw_labels.get('left', False)
            self.right_labels = draw_labels.get('right', False)
            self.geo_labels = draw_labels.get('geo', False)

        else:

            self.top_labels = draw_labels
            self.bottom_labels = draw_labels
            self.left_labels = draw_labels
            self.right_labels = draw_labels
            self.geo_labels = draw_labels

        for loc in 'top', 'bottom', 'left', 'right', 'geo':
            value = getattr(self, f'{loc}_labels')
            if isinstance(value, str):
                value = value.lower()
            if (not isinstance(value, (list, bool)) and
                    value not in ('x', 'y')):
                raise ValueError(f"Invalid draw_labels argument: {value}")

        if auto_inline:
            if isinstance(self.axes.projection, _X_INLINE_PROJS):
                self.x_inline = True
                self.y_inline = False
            elif isinstance(self.axes.projection, _POLAR_PROJS):
                self.x_inline = False
                self.y_inline = True
            else:
                self.x_inline = False
                self.y_inline = False

        # overwrite auto_inline if necessary
        if x_inline is not None:
            #: Whether to draw x labels inline
            self.x_inline = x_inline
        elif not auto_inline:
            self.x_inline = False

        if y_inline is not None:
            #: Whether to draw y labels inline
            self.y_inline = y_inline
        elif not auto_inline:
            self.y_inline = False

        # Apply inline args
        if not draw_labels:
            self.inline_labels = False
        elif self.x_inline and self.y_inline:
            self.inline_labels = True
        elif self.x_inline:
            self.inline_labels = "x"
        elif self.y_inline:
            self.inline_labels = "y"
        else:
            self.inline_labels = False

        # Gridline limits so that the gridlines don't extend all the way
        # to the edge of the boundary
        self.xlim = xlim
        self.ylim = ylim

        #: Whether to draw the x gridlines.
        self.xlines = True

        #: Whether to draw the y gridlines.
        self.ylines = True

        #: A dictionary passed through to ``ax.text`` on x label creation
        #: for styling of the text labels.
        self.xlabel_style = xlabel_style or {}

        #: A dictionary passed through to ``ax.text`` on y label creation
        #: for styling of the text labels.
        self.ylabel_style = ylabel_style or {}

        #: bbox style for grid labels
        self.labels_bbox_style = (
            labels_bbox_style or {'pad': 0, 'visible': False})

        #: The padding from the map edge to the x labels in points.
        self.xpadding = xpadding

        #: The padding from the map edge to the y labels in points.
        self.ypadding = ypadding

        #: Control the rotation of labels.
        if rotate_labels is None:
            rotate_labels = (
                self.axes.projection.__class__ in _ROTATE_LABEL_PROJS)
        if not isinstance(rotate_labels, (bool, float, int)):
            raise ValueError("Invalid rotate_labels argument")
        self.rotate_labels = rotate_labels

        self.offset_angle = offset_angle

        # Current transform
        self.crs = crs

        # if the user specifies tick labels at this point, check if they can
        # be drawn. The same check will take place at draw time in case
        # public attributes are changed after instantiation.
        if draw_labels and not (x_inline or y_inline or auto_inline):
            self._assert_can_draw_ticks()

        #: The number of interpolation points which are used to draw the
        #: gridlines.
        self.n_steps = 100

        #: A dictionary passed through to
        #: ``matplotlib.collections.LineCollection`` on grid line creation.
        self.collection_kwargs = collection_kwargs

        #: The x gridlines which were created at draw time.
        self.xline_artists = []

        #: The y gridlines which were created at draw time.
        self.yline_artists = []

        # List of all labels (Label objects)
        self._labels = []

        # Draw status
        self._drawn = False
        self._auto_update = auto_update

        # Check visibility of labels at each draw event
        # (or once drawn, only at resize event ?)
        self.axes.figure.canvas.mpl_connect('draw_event', self._draw_event)
예제 #10
0
class Gridliner:
    # NOTE: In future, one of these objects will be add-able to a GeoAxes (and
    # maybe even a plain old mpl axes) and it will call the "_draw_gridliner"
    # method on draw. This will enable automatic gridline resolution
    # determination on zoom/pan.
    def __init__(self, axes, crs, draw_labels=False, xlocator=None,
                 ylocator=None, collection_kwargs=None,
                 xformatter=None, yformatter=None, dms=False,
                 x_inline=None, y_inline=None, auto_inline=True,
                 xlim=None, ylim=None, rotate_labels=None,
                 xlabel_style=None, ylabel_style=None, labels_bbox_style=None,
                 xpadding=5, ypadding=5, offset_angle=25,
                 auto_update=False, formatter_kwargs=None):
        """
        Object used by :meth:`cartopy.mpl.geoaxes.GeoAxes.gridlines`
        to add gridlines and tick labels to a map.

        Parameters
        ----------
        axes
            The :class:`cartopy.mpl.geoaxes.GeoAxes` object to be drawn on.
        crs
            The :class:`cartopy.crs.CRS` defining the coordinate system that
            the gridlines are drawn in.
        draw_labels: optional
            Toggle whether to draw labels. For finer control, attributes of
            :class:`Gridliner` may be modified individually. Defaults to False.

            - string: "x" or "y" to only draw labels of the respective
              coordinate in the CRS.
            - list: Can contain the side identifiers and/or coordinate
              types to select which ones to draw.
              For all labels one would use
              `["x", "y", "top", "bottom", "left", "right", "geo"]`.
            - dict: The keys are the side identifiers
              ("top", "bottom", "left", "right") and the values are the
              coordinates ("x", "y"); this way you can precisely
              decide what kind of label to draw and where.
              For x labels on the bottom and y labels on the right you
              could pass in `{"bottom": "x", "left": "y"}`.

            Note that, by default, x and y labels are not drawn on left/right
            and top/bottom edges respectively, unless explicitly requested.

        xlocator: optional
            A :class:`matplotlib.ticker.Locator` instance which will be used
            to determine the locations of the gridlines in the x-coordinate of
            the given CRS. Defaults to None, which implies automatic locating
            of the gridlines.
        ylocator: optional
            A :class:`matplotlib.ticker.Locator` instance which will be used
            to determine the locations of the gridlines in the y-coordinate of
            the given CRS. Defaults to None, which implies automatic locating
            of the gridlines.
        xformatter: optional
            A :class:`matplotlib.ticker.Formatter` instance to format labels
            for x-coordinate gridlines. It defaults to None, which implies the
            use of a :class:`cartopy.mpl.ticker.LongitudeFormatter` initiated
            with the ``dms`` argument, if the crs is of
            :class:`~cartopy.crs.PlateCarree` type.
        yformatter: optional
            A :class:`matplotlib.ticker.Formatter` instance to format labels
            for y-coordinate gridlines. It defaults to None, which implies the
            use of a :class:`cartopy.mpl.ticker.LatitudeFormatter` initiated
            with the ``dms`` argument, if the crs is of
            :class:`~cartopy.crs.PlateCarree` type.
        collection_kwargs: optional
            Dictionary controlling line properties, passed to
            :class:`matplotlib.collections.Collection`. Defaults to None.
        dms: bool
            When default locators and formatters are used,
            ticks are able to stop on minutes and seconds if minutes
            is set to True, and not fraction of degrees.
        x_inline: optional
            Toggle whether the x labels drawn should be inline.
        y_inline: optional
            Toggle whether the y labels drawn should be inline.
        auto_inline: optional
            Set x_inline and y_inline automatically based on projection.
        xlim: optional
            Set a limit for the gridlines so that they do not go all the
            way to the edge of the boundary. xlim can be a single number or
            a (min, max) tuple. If a single number, the limits will be
            (-xlim, +xlim).
        ylim: optional
            Set a limit for the gridlines so that they do not go all the
            way to the edge of the boundary. ylim can be a single number or
            a (min, max) tuple. If a single number, the limits will be
            (-ylim, +ylim).
        rotate_labels: optional, bool, str
            Allow the rotation of non-inline labels.

            - False: Do not rotate the labels.
            - True: Rotate the labels parallel to the gridlines.
            - None: no rotation except for some projections (default).
            - A float: Rotate labels by this value in degrees.

        xlabel_style: dict
            A dictionary passed through to ``ax.text`` on x label creation
            for styling of the text labels.
        ylabel_style: dict
            A dictionary passed through to ``ax.text`` on y label creation
            for styling of the text labels.
        labels_bbox_style: dict
            bbox style for all text labels
        xpadding: float
            Padding for x labels. If negative, the labels are
            drawn inside the map.
        ypadding: float
            Padding for y labels. If negative, the labels are
            drawn inside the map.
        offset_angle: float
            Difference of angle in degrees from 90 to define when
            a label must be flipped to be more readable.
            For example, a value of 10 makes a vertical top label to be
            flipped only at 100 degrees.
        auto_update: bool
            Whether to redraw the gridlines and labels when the figure is
            updated.
        formatter_kwargs: dict, optional
            Options passed to the default formatters.
            See :class:`~cartopy.mpl.ticker.LongitudeFormatter` and
            :class:`~cartopy.mpl.ticker.LatitudeFormatter`

        Notes
        -----
        The "x" and "y" labels for locators and formatters do not necessarily
        correspond to X and Y, but to the first and second coordinates of the
        specified CRS. For the common case of PlateCarree gridlines, these
        correspond to longitudes and latitudes. Depending on the projection
        used for the map, meridians and parallels can cross both the X axis and
        the Y axis.
        """
        self.axes = axes

        #: The :class:`~matplotlib.ticker.Locator` to use for the x
        #: gridlines and labels.
        if xlocator is not None:
            if not isinstance(xlocator, mticker.Locator):
                xlocator = mticker.FixedLocator(xlocator)
            self.xlocator = xlocator
        elif isinstance(crs, PlateCarree):
            self.xlocator = LongitudeLocator(dms=dms)
        else:
            self.xlocator = classic_locator

        #: The :class:`~matplotlib.ticker.Locator` to use for the y
        #: gridlines and labels.
        if ylocator is not None:
            if not isinstance(ylocator, mticker.Locator):
                ylocator = mticker.FixedLocator(ylocator)
            self.ylocator = ylocator
        elif isinstance(crs, PlateCarree):
            self.ylocator = LatitudeLocator(dms=dms)
        else:
            self.ylocator = classic_locator

        formatter_kwargs = {
            **(formatter_kwargs or {}),
            "dms": dms,
        }

        if xformatter is None:
            if isinstance(crs, PlateCarree):
                xformatter = LongitudeFormatter(**formatter_kwargs)
            else:
                xformatter = classic_formatter()
        #: The :class:`~matplotlib.ticker.Formatter` to use for the lon labels.
        self.xformatter = xformatter

        if yformatter is None:
            if isinstance(crs, PlateCarree):
                yformatter = LatitudeFormatter(**formatter_kwargs)
            else:
                yformatter = classic_formatter()
        #: The :class:`~matplotlib.ticker.Formatter` to use for the lat labels.
        self.yformatter = yformatter

        # Draw label argument
        if isinstance(draw_labels, list):

            # Select to which coordinate it is applied
            if 'x' not in draw_labels and 'y' not in draw_labels:
                value = True
            elif 'x' in draw_labels and 'y' in draw_labels:
                value = ['x', 'y']
            elif 'x' in draw_labels:
                value = 'x'
            else:
                value = 'y'

            #: Whether to draw labels on the top of the map.
            self.top_labels = value if 'top' in draw_labels else False

            #: Whether to draw labels on the bottom of the map.
            self.bottom_labels = value if 'bottom' in draw_labels else False

            #: Whether to draw labels on the left hand side of the map.
            self.left_labels = value if 'left' in draw_labels else False

            #: Whether to draw labels on the right hand side of the map.
            self.right_labels = value if 'right' in draw_labels else False

            #: Whether to draw labels near the geographic limits of the map.
            self.geo_labels = value if 'geo' in draw_labels else False

        elif isinstance(draw_labels, dict):

            self.top_labels = draw_labels.get('top', False)
            self.bottom_labels = draw_labels.get('bottom', False)
            self.left_labels = draw_labels.get('left', False)
            self.right_labels = draw_labels.get('right', False)
            self.geo_labels = draw_labels.get('geo', False)

        else:

            self.top_labels = draw_labels
            self.bottom_labels = draw_labels
            self.left_labels = draw_labels
            self.right_labels = draw_labels
            self.geo_labels = draw_labels

        for loc in 'top', 'bottom', 'left', 'right', 'geo':
            value = getattr(self, f'{loc}_labels')
            if isinstance(value, str):
                value = value.lower()
            if (not isinstance(value, (list, bool)) and
                    value not in ('x', 'y')):
                raise ValueError(f"Invalid draw_labels argument: {value}")

        if auto_inline:
            if isinstance(self.axes.projection, _X_INLINE_PROJS):
                self.x_inline = True
                self.y_inline = False
            elif isinstance(self.axes.projection, _POLAR_PROJS):
                self.x_inline = False
                self.y_inline = True
            else:
                self.x_inline = False
                self.y_inline = False

        # overwrite auto_inline if necessary
        if x_inline is not None:
            #: Whether to draw x labels inline
            self.x_inline = x_inline
        elif not auto_inline:
            self.x_inline = False

        if y_inline is not None:
            #: Whether to draw y labels inline
            self.y_inline = y_inline
        elif not auto_inline:
            self.y_inline = False

        # Apply inline args
        if not draw_labels:
            self.inline_labels = False
        elif self.x_inline and self.y_inline:
            self.inline_labels = True
        elif self.x_inline:
            self.inline_labels = "x"
        elif self.y_inline:
            self.inline_labels = "y"
        else:
            self.inline_labels = False

        # Gridline limits so that the gridlines don't extend all the way
        # to the edge of the boundary
        self.xlim = xlim
        self.ylim = ylim

        #: Whether to draw the x gridlines.
        self.xlines = True

        #: Whether to draw the y gridlines.
        self.ylines = True

        #: A dictionary passed through to ``ax.text`` on x label creation
        #: for styling of the text labels.
        self.xlabel_style = xlabel_style or {}

        #: A dictionary passed through to ``ax.text`` on y label creation
        #: for styling of the text labels.
        self.ylabel_style = ylabel_style or {}

        #: bbox style for grid labels
        self.labels_bbox_style = (
            labels_bbox_style or {'pad': 0, 'visible': False})

        #: The padding from the map edge to the x labels in points.
        self.xpadding = xpadding

        #: The padding from the map edge to the y labels in points.
        self.ypadding = ypadding

        #: Control the rotation of labels.
        if rotate_labels is None:
            rotate_labels = (
                self.axes.projection.__class__ in _ROTATE_LABEL_PROJS)
        if not isinstance(rotate_labels, (bool, float, int)):
            raise ValueError("Invalid rotate_labels argument")
        self.rotate_labels = rotate_labels

        self.offset_angle = offset_angle

        # Current transform
        self.crs = crs

        # if the user specifies tick labels at this point, check if they can
        # be drawn. The same check will take place at draw time in case
        # public attributes are changed after instantiation.
        if draw_labels and not (x_inline or y_inline or auto_inline):
            self._assert_can_draw_ticks()

        #: The number of interpolation points which are used to draw the
        #: gridlines.
        self.n_steps = 100

        #: A dictionary passed through to
        #: ``matplotlib.collections.LineCollection`` on grid line creation.
        self.collection_kwargs = collection_kwargs

        #: The x gridlines which were created at draw time.
        self.xline_artists = []

        #: The y gridlines which were created at draw time.
        self.yline_artists = []

        # List of all labels (Label objects)
        self._labels = []

        # Draw status
        self._drawn = False
        self._auto_update = auto_update

        # Check visibility of labels at each draw event
        # (or once drawn, only at resize event ?)
        self.axes.figure.canvas.mpl_connect('draw_event', self._draw_event)

    @property
    def xlabels_top(self):
        warnings.warn('The .xlabels_top attribute is deprecated. Please '
                      'use .top_labels to toggle visibility instead.')
        return self.top_labels

    @xlabels_top.setter
    def xlabels_top(self, value):
        warnings.warn('The .xlabels_top attribute is deprecated. Please '
                      'use .top_labels to toggle visibility instead.')
        self.top_labels = value

    @property
    def xlabels_bottom(self):
        warnings.warn('The .xlabels_bottom attribute is deprecated. Please '
                      'use .bottom_labels to toggle visibility instead.')
        return self.bottom_labels

    @xlabels_bottom.setter
    def xlabels_bottom(self, value):
        warnings.warn('The .xlabels_bottom attribute is deprecated. Please '
                      'use .bottom_labels to toggle visibility instead.')
        self.bottom_labels = value

    @property
    def ylabels_left(self):
        warnings.warn('The .ylabels_left attribute is deprecated. Please '
                      'use .left_labels to toggle visibility instead.')
        return self.left_labels

    @ylabels_left.setter
    def ylabels_left(self, value):
        warnings.warn('The .ylabels_left attribute is deprecated. Please '
                      'use .left_labels to toggle visibility instead.')
        self.left_labels = value

    @property
    def ylabels_right(self):
        warnings.warn('The .ylabels_right attribute is deprecated. Please '
                      'use .right_labels to toggle visibility instead.')
        return self.right_labels

    @ylabels_right.setter
    def ylabels_right(self, value):
        warnings.warn('The .ylabels_right attribute is deprecated. Please '
                      'use .right_labels to toggle visibility instead.')
        self.right_labels = value

    def _draw_event(self, event):
        self._draw_gridliner(renderer=event.renderer)

    def has_labels(self):
        return len(self._labels) != 0

    @property
    def label_artists(self):
        """All the labels which were created at draw time"""
        return [label.artist for label in self._labels]

    @property
    def top_label_artists(self):
        """The top labels which were created at draw time"""
        return [label.artist for label in self._labels
                if label.loc == "top"]

    @property
    def bottom_label_artists(self):
        """The bottom labels which were created at draw time"""
        return [label.artist for label in self._labels
                if label.loc == "bottom"]

    @property
    def left_label_artists(self):
        """The left labels which were created at draw time"""
        return [label.artist for label in self._labels
                if label.loc == "left"]

    @property
    def right_label_artists(self):
        """The right labels which were created at draw time"""
        return [label.artist for label in self._labels
                if label.loc == "right"]

    @property
    def geo_label_artists(self):
        """The geo spine labels which were created at draw time"""
        return [label.artist for label in self._labels
                if label.loc == "geo"]

    @property
    def x_inline_label_artists(self):
        """The x-coordinate inline labels which were created at draw time"""
        return [label.artist for label in self._labels
                if label.loc == "x_inline"]

    @property
    def y_inline_label_artists(self):
        """The y-coordinate inline labels which were created at draw time"""
        return [label.artist for label in self._labels
                if label.loc == "y_inline"]

    @property
    def xlabel_artists(self):
        """The x-coordinate labels which were created at draw time"""
        return [label.artist for label in self._labels
                if label.xy == "x"]

    @property
    def ylabel_artists(self):
        """The y-coordinate labels which were created at draw time"""
        return [label.artist for label in self._labels
                if label.xy == "y"]

    def _crs_transform(self):
        """
        Get the drawing transform for our gridlines.

        Note
        ----
            The drawing transform depends on the transform of our 'axes', so
            it may change dynamically.

        """
        transform = self.crs
        if not isinstance(transform, mtrans.Transform):
            transform = transform._as_mpl_transform(self.axes)
        return transform

    @staticmethod
    def _round(x, base=5):
        if np.isnan(base):
            base = 5
        return int(base * round(x / base))

    def _find_midpoints(self, lim, ticks):
        # Find the center point between each lat gridline.
        if len(ticks) > 1:
            cent = np.diff(ticks).mean() / 2
        else:
            cent = np.nan
        if isinstance(self.axes.projection, _POLAR_PROJS):
            lq = 90
            uq = 90
        else:
            lq = 25
            uq = 75
        midpoints = (self._round(np.percentile(lim, lq), cent),
                     self._round(np.percentile(lim, uq), cent))
        return midpoints

    def _draw_this_label(self, xylabel, loc):
        """Should I draw this kind of label here?"""
        draw_labels = getattr(self, loc + '_labels')

        # By default, only x on top/bottom and only y on left/right
        if draw_labels is True and loc != 'geo':
            draw_labels = "x" if loc in ["top", "bottom"] else "y"

        # Don't draw
        if not draw_labels:
            return False

        # Explicit x or y
        if isinstance(draw_labels, str):
            draw_labels = [draw_labels]

        # Explicit list of x and/or y
        if isinstance(draw_labels, list) and xylabel not in draw_labels:
            return False

        return True

    def _draw_gridliner(self, nx=None, ny=None, renderer=None):
        """Create Artists for all visible elements and add to our Axes.

        The following rules apply for the visibility of labels:

        - X-type labels are plotted along the bottom, top and geo spines.
        - Y-type labels are plotted along the left, right and geo spines.
        - A label must not overlap another label marked as visible.
        - A label must not overlap the map boundary.
        - When a label is about to be hidden, its padding is slightly
          increase until it can be drawn or until a padding limit is reached.
        """
        # Update only when needed or requested
        if self._drawn and not self._auto_update:
            return
        self._drawn = True

        # Clear lists of artists
        for lines in [*self.xline_artists, *self.yline_artists]:
            lines.remove()
        self.xline_artists.clear()
        self.yline_artists.clear()
        for label in self._labels:
            label.artist.remove()
        self._labels.clear()

        # Inits
        lon_lim, lat_lim = self._axes_domain(nx=nx, ny=ny)
        transform = self._crs_transform()
        n_steps = self.n_steps
        crs = self.crs

        # Get nice ticks within crs domain
        lon_ticks = self.xlocator.tick_values(lon_lim[0], lon_lim[1])
        lat_ticks = self.ylocator.tick_values(lat_lim[0], lat_lim[1])

        inf = max(lon_lim[0], crs.x_limits[0])
        sup = min(lon_lim[1], crs.x_limits[1])
        lon_ticks = [value for value in lon_ticks if inf <= value <= sup]
        inf = max(lat_lim[0], crs.y_limits[0])
        sup = min(lat_lim[1], crs.y_limits[1])
        lat_ticks = [value for value in lat_ticks if inf <= value <= sup]

        #####################
        # Gridlines drawing #
        #####################

        collection_kwargs = self.collection_kwargs
        if collection_kwargs is None:
            collection_kwargs = {}
        collection_kwargs = collection_kwargs.copy()
        collection_kwargs['transform'] = transform
        if not any(x in collection_kwargs for x in ['c', 'color']):
            collection_kwargs.setdefault('color',
                                         matplotlib.rcParams['grid.color'])
        if not any(x in collection_kwargs for x in ['ls', 'linestyle']):
            collection_kwargs.setdefault('linestyle',
                                         matplotlib.rcParams['grid.linestyle'])
        if not any(x in collection_kwargs for x in ['lw', 'linewidth']):
            collection_kwargs.setdefault('linewidth',
                                         matplotlib.rcParams['grid.linewidth'])

        # Meridians
        lat_min, lat_max = lat_lim
        if lat_ticks:
            lat_min = min(lat_min, min(lat_ticks))
            lat_max = max(lat_max, max(lat_ticks))
        lon_lines = np.empty((len(lon_ticks), n_steps, 2))
        lon_lines[:, :, 0] = np.array(lon_ticks)[:, np.newaxis]
        lon_lines[:, :, 1] = np.linspace(
            lat_min, lat_max, n_steps)[np.newaxis, :]

        if self.xlines:
            nx = len(lon_lines) + 1
            # XXX this bit is cartopy specific. (for circular longitudes)
            # Purpose: omit plotting the last x line,
            # as it may overlap the first.
            if (isinstance(crs, Projection) and
                    isinstance(crs, _RectangularProjection) and
                    abs(np.diff(lon_lim)) == abs(np.diff(crs.x_limits))):
                nx -= 1
            lon_lc = mcollections.LineCollection(lon_lines,
                                                 **collection_kwargs)
            self.xline_artists.append(lon_lc)
            self.axes.add_collection(lon_lc, autolim=False)

        # Parallels
        lon_min, lon_max = lon_lim
        if lon_ticks:
            lon_min = min(lon_min, min(lon_ticks))
            lon_max = max(lon_max, max(lon_ticks))
        lat_lines = np.empty((len(lat_ticks), n_steps, 2))
        lat_lines[:, :, 0] = np.linspace(lon_min, lon_max,
                                         n_steps)[np.newaxis, :]
        lat_lines[:, :, 1] = np.array(lat_ticks)[:, np.newaxis]
        if self.ylines:
            lat_lc = mcollections.LineCollection(lat_lines,
                                                 **collection_kwargs)
            self.yline_artists.append(lat_lc)
            self.axes.add_collection(lat_lc, autolim=False)

        #################
        # Label drawing #
        #################

        if not any((self.left_labels, self.right_labels, self.bottom_labels,
                    self.top_labels, self.inline_labels, self.geo_labels)):
            return
        self._assert_can_draw_ticks()

        # Inits for labels
        max_padding_factor = 5
        delta_padding_factor = 0.2
        spines_specs = {
            'left': {
                'index': 0,
                'coord_type': "x",
                'opcmp': operator.le,
                'opval': max,
            },
            'bottom': {
                'index': 1,
                'coord_type': "y",
                'opcmp': operator.le,
                'opval': max,
            },
            'right': {
                'index': 0,
                'coord_type': "x",
                'opcmp': operator.ge,
                'opval': min,
            },
            'top': {
                'index': 1,
                'coord_type': "y",
                'opcmp': operator.ge,
                'opval': min,
            },
        }
        for side, specs in spines_specs.items():
            bbox = self.axes.spines[side].get_window_extent(renderer)
            specs['coords'] = [
                getattr(bbox, specs['coord_type'] + idx) for idx in "01"]

        def remove_path_dupes(path):
            """
            Remove duplicate points in a path (zero-length segments).

            This is necessary only for Matplotlib 3.1.0 -- 3.1.2, because
            Path.intersects_path incorrectly returns True for any paths with
            such segments.
            """
            segment_length = np.diff(path.vertices, axis=0)
            mask = np.logical_or.reduce(segment_length != 0, axis=1)
            mask = np.append(mask, True)
            path = mpath.Path(np.compress(mask, path.vertices, axis=0),
                              np.compress(mask, path.codes, axis=0))
            return path

        def update_artist(artist, renderer):
            artist.update_bbox_position_size(renderer)
            this_patch = artist.get_bbox_patch()
            this_path = this_patch.get_path().transformed(
                this_patch.get_transform())
            if '3.1.0' <= matplotlib.__version__ <= '3.1.2':
                this_path = remove_path_dupes(this_path)
            return this_path

        # Get the real map boundaries
        self.axes.spines["geo"].get_window_extent(renderer)  # update coords
        map_boundary_path = self.axes.spines["geo"].get_path().transformed(
            self.axes.spines["geo"].get_transform())
        if '3.1.0' <= matplotlib.__version__ <= '3.1.2':
            map_boundary_path = remove_path_dupes(map_boundary_path)
        map_boundary = sgeom.Polygon(map_boundary_path.vertices)

        if self.x_inline:
            y_midpoints = self._find_midpoints(lat_lim, lat_ticks)
        if self.y_inline:
            x_midpoints = self._find_midpoints(lon_lim, lon_ticks)

        # Cache a few things so they aren't re-calculated in the loops.
        crs_transform = self._crs_transform().transform
        inverse_data_transform = self.axes.transData.inverted().transform_point

        for xylabel, lines, line_ticks, formatter, label_style in (
                ('x', lon_lines, lon_ticks,
                 self.xformatter, self.xlabel_style.copy()),
                ('y', lat_lines, lat_ticks,
                 self.yformatter, self.ylabel_style.copy())):

            x_inline = self.x_inline and xylabel == 'x'
            y_inline = self.y_inline and xylabel == 'y'
            padding = getattr(self, f'{xylabel}padding')
            bbox_style = self.labels_bbox_style.copy()
            if "bbox" in label_style:
                bbox_style.update(label_style["bbox"])
            label_style["bbox"] = bbox_style

            formatter.set_locs(line_ticks)

            for line_coords, tick_value in zip(lines, line_ticks):
                # Intersection of line with map boundary
                line_coords = crs_transform(line_coords)
                infs = np.isnan(line_coords).any(axis=1)
                line_coords = line_coords.compress(~infs, axis=0)
                if line_coords.size == 0:
                    continue
                line = sgeom.LineString(line_coords)
                if not line.intersects(map_boundary):
                    continue
                intersection = line.intersection(map_boundary)
                del line
                if intersection.is_empty:
                    continue
                if isinstance(intersection, sgeom.MultiPoint):
                    if len(intersection) < 2:
                        continue
                    n2 = min(len(intersection), 3)
                    tails = [[(pt.x, pt.y)
                              for pt in intersection[:n2:n2 - 1]]]
                    heads = [[(pt.x, pt.y)
                              for pt in intersection[-1:-n2 - 1:-n2 + 1]]]
                elif isinstance(intersection, (sgeom.LineString,
                                               sgeom.MultiLineString)):
                    if isinstance(intersection, sgeom.LineString):
                        intersection = [intersection]
                    elif len(intersection.geoms) > 4:
                        # Gridline and map boundary are parallel and they
                        # intersect themselves too much it results in a
                        # multiline string that must be converted to a single
                        # linestring. This is an empirical workaround for a
                        # problem that can probably be solved in a cleaner way.
                        xy = np.append(
                            intersection.geoms[0].coords,
                            intersection.geoms[-1].coords,
                            axis=0,
                        )
                        intersection = [sgeom.LineString(xy)]
                    else:
                        intersection = intersection.geoms
                    tails = []
                    heads = []
                    for inter in intersection:
                        if len(inter.coords) < 2:
                            continue
                        n2 = min(len(inter.coords), 8)
                        tails.append(inter.coords[:n2:n2 - 1])
                        heads.append(inter.coords[-1:-n2 - 1:-n2 + 1])
                    if not tails:
                        continue
                elif isinstance(intersection, sgeom.GeometryCollection):
                    # This is a collection of Point and LineString that
                    # represent the same gridline.  We only consider the first
                    # geometries, merge their coordinates and keep first two
                    # points to get only one tail ...
                    xy = []
                    for geom in intersection.geoms:
                        for coord in geom.coords:
                            xy.append(coord)
                            if len(xy) == 2:
                                break
                        if len(xy) == 2:
                            break
                    tails = [xy]
                    # ... and the last geometries, merge their coordinates and
                    # keep last two points to get only one head.
                    xy = []
                    for geom in reversed(intersection.geoms):
                        for coord in reversed(geom.coords):
                            xy.append(coord)
                            if len(xy) == 2:
                                break
                        if len(xy) == 2:
                            break
                    heads = [xy]
                else:
                    warnings.warn(
                        'Unsupported intersection geometry for gridline '
                        f'labels: {intersection.__class__.__name__}')
                    continue
                del intersection

                # Loop on head and tail and plot label by extrapolation
                for i, (pt0, pt1) in itertools.chain.from_iterable(
                        enumerate(pair) for pair in zip(tails, heads)):

                    # Initial text specs
                    x0, y0 = pt0
                    if x_inline or y_inline:
                        kw = {'rotation': 0, 'transform': self.crs,
                              'ha': 'center', 'va': 'center'}
                        loc = 'inline'
                    else:
                        x1, y1 = pt1
                        segment_angle = np.arctan2(y0 - y1,
                                                   x0 - x1) * 180 / np.pi
                        loc = self._get_loc_from_spine_intersection(
                            spines_specs, xylabel, x0, y0)
                        if not self._draw_this_label(xylabel, loc):
                            visible = False
                        kw = self._get_text_specs(segment_angle, loc, xylabel)
                        kw['transform'] = self._get_padding_transform(
                            segment_angle, loc, xylabel)
                    kw.update(label_style)

                    # Get x and y in data coords
                    pt0 = inverse_data_transform(pt0)
                    if y_inline:
                        # 180 degrees isn't formatted with a suffix and adds
                        # confusion if it's inline.
                        if abs(tick_value) == 180:
                            continue
                        x = x_midpoints[i]
                        y = tick_value
                        kw.update(clip_on=True)
                        y_set = True
                    else:
                        x = pt0[0]
                        y_set = False

                    if x_inline:
                        if abs(tick_value) == 180:
                            continue
                        x = tick_value
                        y = y_midpoints[i]
                        kw.update(clip_on=True)
                    elif not y_set:
                        y = pt0[1]

                    # Add text to the plot
                    text = formatter(tick_value)
                    artist = self.axes.text(x, y, text, **kw)

                    # Update loc from spine overlapping now that we have a bbox
                    # of the label.
                    this_path = update_artist(artist, renderer)
                    if not x_inline and not y_inline and loc == 'geo':
                        new_loc = self._get_loc_from_spine_overlapping(
                            spines_specs, xylabel, this_path)
                        if new_loc and loc != new_loc:
                            loc = new_loc
                            transform = self._get_padding_transform(
                                segment_angle, loc, xylabel)
                            artist.set_transform(transform)
                            artist.update(
                                self._get_text_specs(
                                    segment_angle, loc, xylabel))
                            artist.update(label_style.copy())
                            this_path = update_artist(artist, renderer)

                    # Is this kind label allowed to be drawn?
                    if not self._draw_this_label(xylabel, loc):
                        visible = False

                    elif x_inline or y_inline:
                        # Check that it does not overlap the map.
                        # Inline must be within the map.
                        # TODO: When Matplotlib clip path works on text, this
                        # clipping can be left to it.
                        center = (artist
                                  .get_transform()
                                  .transform_point(artist.get_position()))
                        visible = map_boundary_path.contains_point(center)
                    else:
                        # Now loop on padding factors until it does not overlap
                        # the boundary.
                        visible = False
                        padding_factor = 1
                        while padding_factor < max_padding_factor:

                            # Non-inline must not run through the outline.
                            if map_boundary_path.intersects_path(
                                    this_path, filled=padding > 0):

                                # Apply new padding.
                                transform = self._get_padding_transform(
                                    segment_angle, loc, xylabel,
                                    padding_factor)
                                artist.set_transform(transform)
                                this_path = update_artist(artist, renderer)
                                padding_factor += delta_padding_factor

                            else:
                                visible = True
                                break

                    # Updates
                    label = Label(artist, this_path, xylabel, loc)
                    label.set_visible(visible)
                    self._labels.append(label)

        # Now check overlapping of ordered visible labels
        if self._labels:
            self._labels.sort(
                key=operator.attrgetter("priority"), reverse=True)
            visible_labels = []
            for label in self._labels:
                if label.get_visible():
                    for other_label in visible_labels:
                        if label.check_overlapping(other_label):
                            break
                    else:
                        visible_labels.append(label)

    def _get_loc_from_angle(self, angle):
        angle %= 360
        if angle > 180:
            angle -= 360
        if abs(angle) <= 45:
            loc = 'right'
        elif abs(angle) >= 135:
            loc = 'left'
        elif angle > 45:
            loc = 'top'
        else:  # (-135, -45)
            loc = 'bottom'
        return loc

    def _get_loc_from_spine_overlapping(
            self, spines_specs, xylabel, label_path):
        """Try to get the location from side spines and label path

        Returns None if it does not apply

        For instance, for each side, if any of label_path x coordinates
        are beyond this side, the distance to this side is computed.
        If several sides are matching (max 2), then the one with a greater
        distance is kept.

        This helps finding the side of labels for non-rectangular projection
        with a rectangular map boundary.

        """
        side_max = dist_max = None
        for side, specs in spines_specs.items():
            if specs['coord_type'] == xylabel:
                continue

            label_coords = label_path.vertices[:-1, specs['index']]

            spine_coord = specs['opval'](specs['coords'])
            if not specs['opcmp'](label_coords, spine_coord).any():
                continue
            if specs['opcmp'] is operator.ge:  # top, right
                dist = label_coords.min() - spine_coord
            else:
                dist = spine_coord - label_coords.max()

            if side_max is None or dist > dist_max:
                side_max = side
                dist_max = dist
        if side_max is None:
            return "geo"
        return side_max

    def _get_loc_from_spine_intersection(self, spines_specs, xylabel, x, y):
        """Get the loc the intersection of a gridline with a spine

        Defaults to "geo".
        """
        if xylabel == "x":
            sides = ["bottom", "top", "left", "right"]
        else:
            sides = ["left", "right", "bottom", "top"]
        for side in sides:
            xy = x if side in ["left", "right"] else y
            coords = np.round(spines_specs[side]["coords"], 2)
            if round(xy, 2) in coords:
                return side
        return "geo"

    def _get_text_specs(self, angle, loc, xylabel):
        """Get rotation and alignments specs for a single label"""

        # Angle from -180 to 180
        if angle > 180:
            angle -= 360

        # Fake for geo spine
        if loc == "geo":
            loc = self._get_loc_from_angle(angle)

        # Check rotation
        if not self.rotate_labels:

            # No rotation
            kw = {'rotation': 0, "ha": "center", "va": "center"}
            if loc == 'right':
                kw.update(ha='left')
            elif loc == 'left':
                kw.update(ha='right')
            elif loc == 'top':
                kw.update(va='bottom')
            elif loc == 'bottom':
                kw.update(va='top')

        else:

            # Rotation along gridlines
            if (isinstance(self.rotate_labels, (float, int)) and
                    not isinstance(self.rotate_labels, bool)):
                angle = self.rotate_labels
            kw = {'rotation': angle, 'rotation_mode': 'anchor', 'va': 'center'}
            if (angle < 90 + self.offset_angle and
                    angle > -90 + self.offset_angle):
                kw.update(ha="left", rotation=angle)
            else:
                kw.update(ha="right", rotation=angle + 180)

        # Inside labels
        if getattr(self, xylabel + "padding") < 0:
            if "ha" in kw:
                if kw["ha"] == "left":
                    kw["ha"] = "right"
                elif kw["ha"] == "right":
                    kw["ha"] = "left"
            if "va" in kw:
                if kw["va"] == "top":
                    kw["va"] = "bottom"
                elif kw["va"] == "bottom":
                    kw["va"] = "top"

        return kw

    def _get_padding_transform(
            self, padding_angle, loc, xylabel, padding_factor=1):
        """Get transform from angle and padding for non-inline labels"""

        # No rotation
        if self.rotate_labels is False and loc != "geo":
            padding_angle = {
                'top': 90., 'right': 0., 'bottom': -90., 'left': 180.}[loc]

        # Padding
        if xylabel == "x":
            padding = (self.xpadding if self.xpadding is not None
                       else matplotlib.rcParams['xtick.major.pad'])
        else:
            padding = (self.ypadding if self.ypadding is not None
                       else matplotlib.rcParams['ytick.major.pad'])
        dx = padding_factor * padding * np.cos(padding_angle * np.pi / 180)
        dy = padding_factor * padding * np.sin(padding_angle * np.pi / 180)

        # Final transform
        return mtrans.offset_copy(
            self.axes.transData, fig=self.axes.figure,
            x=dx, y=dy, units='points')

    def _assert_can_draw_ticks(self):
        """
        Check to see if ticks can be drawn. Either returns True or raises
        an exception.

        """
        # Check labelling is supported, currently a limited set of options.
        if not isinstance(self.crs, PlateCarree):
            raise TypeError(f'Cannot label {self.crs.__class__.__name__} '
                            'gridlines. Only PlateCarree gridlines are '
                            'currently supported.')
        return True

    def _axes_domain(self, nx=None, ny=None):
        """Return lon_range, lat_range"""
        DEBUG = False

        transform = self._crs_transform()

        ax_transform = self.axes.transAxes
        desired_trans = ax_transform - transform

        nx = nx or 100
        ny = ny or 100
        x = np.linspace(1e-9, 1 - 1e-9, nx)
        y = np.linspace(1e-9, 1 - 1e-9, ny)
        x, y = np.meshgrid(x, y)

        coords = np.column_stack((x.ravel(), y.ravel()))

        in_data = desired_trans.transform(coords)

        ax_to_bkg_patch = self.axes.transAxes - self.axes.patch.get_transform()

        # convert the coordinates of the data to the background patches
        # coordinates
        background_coord = ax_to_bkg_patch.transform(coords)
        ok = self.axes.patch.get_path().contains_points(background_coord)

        if DEBUG:
            import matplotlib.pyplot as plt
            plt.plot(coords[ok, 0], coords[ok, 1], 'or',
                     clip_on=False, transform=ax_transform)
            plt.plot(coords[~ok, 0], coords[~ok, 1], 'ob',
                     clip_on=False, transform=ax_transform)

        inside = in_data[ok, :]

        # If there were no data points in the axes we just use the x and y
        # range of the projection.
        if inside.size == 0:
            lon_range = self.crs.x_limits
            lat_range = self.crs.y_limits
        else:
            # np.isfinite must be used to prevent np.inf values that
            # not filtered by np.nanmax for some projections
            lat_max = np.compress(np.isfinite(inside[:, 1]),
                                  inside[:, 1])
            if lat_max.size == 0:
                lon_range = self.crs.x_limits
                lat_range = self.crs.y_limits
            else:
                lat_max = lat_max.max()
                lon_range = np.nanmin(inside[:, 0]), np.nanmax(inside[:, 0])
                lat_range = np.nanmin(inside[:, 1]), lat_max

        # XXX Cartopy specific thing. Perhaps make this bit a specialisation
        # in a subclass...
        crs = self.crs
        if isinstance(crs, Projection):
            lon_range = np.clip(lon_range, *crs.x_limits)
            lat_range = np.clip(lat_range, *crs.y_limits)

            # if the limit is >90% of the full x limit, then just use the full
            # x limit (this makes circular handling better)
            prct = np.abs(np.diff(lon_range) / np.diff(crs.x_limits))
            if prct > 0.9:
                lon_range = crs.x_limits

        if self.xlim is not None:
            if np.iterable(self.xlim):
                # tuple, list or ndarray was passed in: (-140, 160)
                lon_range = self.xlim
            else:
                # A single int/float was passed in: 140
                lon_range = (-self.xlim, self.xlim)

        if self.ylim is not None:
            if np.iterable(self.ylim):
                # tuple, list or ndarray was passed in: (-140, 160)
                lat_range = self.ylim
            else:
                # A single int/float was passed in: 140
                lat_range = (-self.ylim, self.ylim)

        return lon_range, lat_range
예제 #11
0
def plot_network_on_israel_map(G=None,
                               gis_path=gis_path,
                               fontsize=18,
                               save=True):
    import matplotlib.pyplot as plt
    import cartopy.crs as ccrs
    from cartopy.io.shapereader import Reader
    import networkx as nx
    import numpy as np
    import matplotlib.ticker as mticker
    import cartopy.feature as cfeature
    from cartopy.mpl.ticker import (LongitudeFormatter, LatitudeFormatter,
                                    LatitudeLocator)
    import geopandas as gpd
    #    isr_with_yosh = gpd.read_file(gis_path / 'Israel_and_Yosh.shp')

    fname = gis_path / 'Israel_and_Yosh.shp'
    east = 36
    west = 34
    north = 34
    south = 29
    fig = plt.figure(figsize=(10, 20))
    ax = fig.add_subplot(projection=ccrs.PlateCarree())
    ax.set_extent([west, east, south, north], crs=ccrs.PlateCarree())
    #    ax.add_geometries(Reader(fname).geometries(),
    #                      ccrs.PlateCarree(), zorder=0,
    #                      edgecolor='k', facecolor='w')
    # Put a background image on for nice sea rendering.

    ax.add_feature(cfeature.LAND.with_scale('10m'))
    ax.add_feature(cfeature.COASTLINE.with_scale('10m'))
    ax.add_feature(cfeature.OCEAN.with_scale('10m'))
    ax.add_feature(cfeature.LAKES.with_scale('10m'))
    ax.add_feature(cfeature.BORDERS.with_scale('10m'))
    #    fig, ax = plt.subplots(figsize=(7, 20))
    #    ax = isr_with_yosh.plot(ax=ax)
    #    ax.xaxis.set_major_locator(mticker.MaxNLocator(2))
    #    ax.yaxis.set_major_locator(mticker.MaxNLocator(5))
    #    ax.yaxis.set_major_formatter(lat_formatter)
    #    ax.xaxis.set_major_formatter(lon_formatter)
    #    ax.tick_params(top=True, bottom=True, left=True, right=True,
    #                   direction='out', labelsize=ticklabelsize)

    deg = nx.degree(G)
    labels = {node: node if deg[node] >= 200 else '' for node in G.nodes}
    pos = {
        key: (value['LON'], value['LAT'])
        for (key, value) in G.nodes().items()
    }
    pop_sizes = np.array([G.nodes()[x]['size'] for x in G.nodes()])
    pop_sizes = linear_map(pop_sizes, 10, 50)
    popularity = np.array(
        [G.nodes()[x].get('popularity', 0) for x in G.nodes()])
    popularity = linear_map(popularity, 0, 100)
    total = np.array([G.nodes()[x].get('total_in', 0) for x in G.nodes()])
    total_width = linear_map(total, 0.1, 5)
    number = np.array([G.edges()[x].get('number', 0) for x in G.edges()])
    bins = [0, 250, 500, 1000, 2500]
    subgraphs = get_subgraph_list(G, attr={'edge': 'number'}, bins=bins)
    evenly_spaced_interval = np.linspace(0, 1, len(bins))
    colors = [plt.cm.gist_rainbow(x) for x in evenly_spaced_interval]
    widths = np.linspace(0.045, 4, len(bins))
    for i, subgraph in enumerate(subgraphs):
        pos = {
            key: (value['LON'], value['LAT'])
            for (key, value) in subgraph.nodes().items()
        }
        nx.draw_networkx_edges(subgraph,
                               ax=ax,
                               pos=pos,
                               alpha=1.0,
                               width=widths[i],
                               edge_color=colors[i],
                               arrows=False,
                               edge_cmap=None)
    leg_labels = get_bins_legend(bins)
    leg = plt.legend(leg_labels, loc='upper left', fontsize=fontsize)
    leg.set_title('Number of immegrants', prop={'size': fontsize - 2})
    # ec = nx.draw_networkx_edges(G, ax=ax, pos=pos, alpha=0.5, width=total_width,
    #                             edge_color='k', arrows=False, edge_cmap=plt.cm.plasma)
    # nc = nx.draw_networkx_nodes(G, ax=ax, pos=pos, nodelist=G.nodes(),
    #                             node_size=pop_sizes, node_color=total,
    #                         cmap=plt.cm.autumn)
    # nc.set_zorder(2)
    # ec.set_zorder(1)
    # plt.colorbar(nc)
    #    nx.draw_networkx(G, ax=ax,
    #                     font_size=10,
    #                     alpha=.5,
    #                     width=.045,
    #                     edge_color='r',
    #                     node_size=pop_sizes,
    #                     labels=labels,
    #                     pos=pos,
    #                     node_color=popularity,
    #                     cmap=plt.cm.autumn)
    year = G.graph['year']
    name = G.graph['name']
    fig.suptitle('{} for year {}'.format(name, year), fontsize=fontsize)
    #    ax.coastlines(resolution='50m')
    gl = ax.gridlines(crs=ccrs.PlateCarree(),
                      draw_labels=True,
                      linewidth=0,
                      color='gray',
                      alpha=0.5,
                      linestyle='--')
    gl.top_labels = False
    gl.right_labels = False
    # gl.left_labels=False
    # gl.bottom_labels=False
    gl.ylocator = LatitudeLocator()
    gl.xlocator = mticker.MaxNLocator(2)
    gl.xformatter = LongitudeFormatter()
    gl.yformatter = LatitudeFormatter()
    gl.xlabel_style = {'size': fontsize}
    gl.ylabel_style = {'size': fontsize}
    fig.canvas.draw()
    ysegs = gl.yline_artists[0].get_segments()
    yticks = [yseg[0, 1] for yseg in ysegs]
    xsegs = gl.xline_artists[0].get_segments()
    xticks = [xseg[0, 0] for xseg in xsegs]
    ax.set_xticks(xticks, crs=ccrs.PlateCarree())
    ax.set_yticks(yticks, crs=ccrs.PlateCarree())
    # gl.xlabel_style = {'color': 'red', 'weight': 'bold'}

    # ax.xaxis.set_major_locator(mticker.MaxNLocator(2))
    # ax.set_xticks(ax.get_xticks(), crs=ccrs.PlateCarree())
    # ax.set_xticks(ax.get_xticks(), crs=ccrs.PlateCarree())
    #    ax.set_yticks([29, 30, 31, 32, 33], crs=ccrs.PlateCarree())
    #    lon_formatter = LongitudeFormatter(zero_direction_label=True)
    #    lat_formatter = LatitudeFormatter()
    #    ax.xaxis.set_major_formatter(lon_formatter)
    #    ax.yaxis.set_major_formatter(lat_formatter)
    #    ax.xaxis.set_major_locator(ticker.MaxNLocator(2))
    #    ax.yaxis.set_major_locator(ticker.MaxNLocator(5))
    #    ax.yaxis.set_major_formatter(lat_formatter)
    #    ax.xaxis.set_major_formatter(lon_formatter)
    ax.tick_params(top=True,
                   bottom=True,
                   left=True,
                   right=False,
                   direction='out',
                   labelbottom=False,
                   labelleft=False,
                   labelsize=fontsize)

    #    ax.figure.tight_layout()

    fig.tight_layout()
    fig.subplots_adjust(top=0.943,
                        bottom=0.038,
                        left=0.008,
                        right=0.885,
                        hspace=0.2,
                        wspace=0.2)
    if save:
        filename = 'Migration_israel_map_{}.png'.format(year)
        plt.savefig(savefig_path / filename,
                    bbox_inches='tight',
                    orientation='portrait')
    return gl