Python matplotlib.axes.Axes() Examples

The following are 30 code examples of matplotlib.axes.Axes(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.axes , or try the search function .
Example #1
Source File: _utils.py    From scanpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def scatter_single(ax: Axes, Y: np.ndarray, *args, **kwargs):
    """Plot scatter plot of data.

    Parameters
    ----------
    ax
        Axis to plot on.
    Y
        Data array, data to be plotted needs to be in the first two columns.
    """
    if 's' not in kwargs:
        kwargs['s'] = 2 if Y.shape[0] > 500 else 10
    if 'edgecolors' not in kwargs:
        kwargs['edgecolors'] = 'face'
    ax.scatter(Y[:, 0], Y[:, 1], **kwargs, rasterized=settings._vector_friendly)
    ax.set_xticks([])
    ax.set_yticks([]) 
Example #2
Source File: axislines.py    From Computable with MIT License 6 votes vote down vote up
def new_gridlines(self, ax):
        """
        Create and return a new GridlineCollection instance.

        *which* : "major" or "minor"
        *axis* : "both", "x" or "y"

        """
        gridlines = GridlinesCollection(None, transform=ax.transData,
                                        colors=rcParams['grid.color'],
                                        linestyles=rcParams['grid.linestyle'],
                                        linewidths=rcParams['grid.linewidth'])
        ax._set_artist_props(gridlines)
        gridlines.set_grid_helper(self)

        ax.axes._set_artist_props(gridlines)
        # gridlines.set_clip_path(self.axes.patch)
        # set_clip_path need to be deferred after Axes.cla is completed.
        # It is done inside the cla.

        return gridlines 
Example #3
Source File: figure.py    From Computable with MIT License 6 votes vote down vote up
def _gci(self):
        """
        helper for :func:`~matplotlib.pyplot.gci`;
        do not use elsewhere.
        """
        # Look first for an image in the current Axes:
        cax = self._axstack.current_key_axes()[1]
        if cax is None:
            return None
        im = cax._gci()
        if im is not None:
            return im

        # If there is no image in the current Axes, search for
        # one in a previously created Axes.  Whether this makes
        # sense is debatable, but it is the documented behavior.
        for ax in reversed(self.axes):
            im = ax._gci()
            if im is not None:
                return im
        return None 
Example #4
Source File: legend.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def _findoffset(self, width, height, xdescent, ydescent, renderer):
        "Helper function to locate the legend."

        if self._loc == 0:  # "best".
            x, y = self._find_best_position(width, height, renderer)
        elif self._loc in Legend.codes.values():  # Fixed location.
            bbox = Bbox.from_bounds(0, 0, width, height)
            x, y = self._get_anchored_bbox(self._loc, bbox,
                                           self.get_bbox_to_anchor(),
                                           renderer)
        else:  # Axes or figure coordinates.
            fx, fy = self._loc
            bbox = self.get_bbox_to_anchor()
            x, y = bbox.x0 + bbox.width * fx, bbox.y0 + bbox.height * fy

        return x + xdescent, y + ydescent 
Example #5
Source File: pl.py    From scanpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def trimap(adata, **kwargs) -> Union[Axes, List[Axes], None]:
    """\
    Scatter plot in TriMap basis.

    Parameters
    ----------
    {adata_color_etc}
    {edges_arrows}
    {scatter_bulk}
    {show_save_ax}

    Returns
    -------
    If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
    """
    return embedding(adata, 'trimap', **kwargs) 
Example #6
Source File: scatterplots.py    From scanpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def tsne(adata, **kwargs) -> Union[Axes, List[Axes], None]:
    """\
    Scatter plot in tSNE basis.

    Parameters
    ----------
    {adata_color_etc}
    {edges_arrows}
    {scatter_bulk}
    {show_save_ax}

    Returns
    -------
    If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
    """
    return embedding(adata, 'tsne', **kwargs) 
Example #7
Source File: scatterplots.py    From scanpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def umap(adata, **kwargs) -> Union[Axes, List[Axes], None]:
    """\
    Scatter plot in UMAP basis.

    Parameters
    ----------
    {adata_color_etc}
    {edges_arrows}
    {scatter_bulk}
    {show_save_ax}

    Returns
    -------
    If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
    """
    return embedding(adata, 'umap', **kwargs) 
Example #8
Source File: _baseplot_class.py    From scanpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _plot_colorbar(self, color_legend_ax: Axes, normalize):
        """
        Plots a horizontal colorbar given the ax an normalize values

        Parameters
        ----------
        color_legend_ax
        normalize

        Returns
        -------
        None, updates color_legend_ax

        """
        cmap = pl.get_cmap(self.cmap)
        import matplotlib.colorbar

        matplotlib.colorbar.ColorbarBase(
            color_legend_ax, orientation='horizontal', cmap=cmap, norm=normalize
        )

        color_legend_ax.set_title(self.color_legend_title, fontsize='small')

        color_legend_ax.xaxis.set_tick_params(labelsize='small') 
Example #9
Source File: common.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def _check_ax_scales(self, axes, xaxis='linear', yaxis='linear'):
        """
        Check each axes has expected scales

        Parameters
        ----------
        axes : matplotlib Axes object, or its list-like
        xaxis : {'linear', 'log'}
            expected xaxis scale
        yaxis :  {'linear', 'log'}
            expected yaxis scale
        """
        axes = self._flatten_visible(axes)
        for ax in axes:
            assert ax.xaxis.get_scale() == xaxis
            assert ax.yaxis.get_scale() == yaxis 
Example #10
Source File: figure.py    From neural-network-animation with MIT License 6 votes vote down vote up
def _gci(self):
        """
        helper for :func:`~matplotlib.pyplot.gci`;
        do not use elsewhere.
        """
        # Look first for an image in the current Axes:
        cax = self._axstack.current_key_axes()[1]
        if cax is None:
            return None
        im = cax._gci()
        if im is not None:
            return im

        # If there is no image in the current Axes, search for
        # one in a previously created Axes.  Whether this makes
        # sense is debatable, but it is the documented behavior.
        for ax in reversed(self.axes):
            im = ax._gci()
            if im is not None:
                return im
        return None 
Example #11
Source File: common.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def _check_data(self, xp, rs):
        """
        Check each axes has identical lines

        Parameters
        ----------
        xp : matplotlib Axes object
        rs : matplotlib Axes object
        """
        xp_lines = xp.get_lines()
        rs_lines = rs.get_lines()

        def check_line(xpl, rsl):
            xpdata = xpl.get_xydata()
            rsdata = rsl.get_xydata()
            tm.assert_almost_equal(xpdata, rsdata)

        assert len(xp_lines) == len(rs_lines)
        [check_line(xpl, rsl) for xpl, rsl in zip(xp_lines, rs_lines)]
        tm.close() 
Example #12
Source File: legend.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def _findoffset(self, width, height, xdescent, ydescent, renderer):
        "Helper function to locate the legend."

        if self._loc == 0:  # "best".
            x, y = self._find_best_position(width, height, renderer)
        elif self._loc in Legend.codes.values():  # Fixed location.
            bbox = Bbox.from_bounds(0, 0, width, height)
            x, y = self._get_anchored_bbox(self._loc, bbox,
                                           self.get_bbox_to_anchor(),
                                           renderer)
        else:  # Axes or figure coordinates.
            fx, fy = self._loc
            bbox = self.get_bbox_to_anchor()
            x, y = bbox.x0 + bbox.width * fx, bbox.y0 + bbox.height * fy

        return x + xdescent, y + ydescent 
Example #13
Source File: figure.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def _gci(self):
        """
        helper for :func:`~matplotlib.pyplot.gci`;
        do not use elsewhere.
        """
        # Look first for an image in the current Axes:
        cax = self._axstack.current_key_axes()[1]
        if cax is None:
            return None
        im = cax._gci()
        if im is not None:
            return im

        # If there is no image in the current Axes, search for
        # one in a previously created Axes.  Whether this makes
        # sense is debatable, but it is the documented behavior.
        for ax in reversed(self.axes):
            im = ax._gci()
            if im is not None:
                return im
        return None 
Example #14
Source File: common.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def _check_legend_labels(self, axes, labels=None, visible=True):
        """
        Check each axes has expected legend labels

        Parameters
        ----------
        axes : matplotlib Axes object, or its list-like
        labels : list-like
            expected legend labels
        visible : bool
            expected legend visibility. labels are checked only when visible is
            True
        """

        if visible and (labels is None):
            raise ValueError('labels must be specified when visible is True')
        axes = self._flatten_visible(axes)
        for ax in axes:
            if visible:
                assert ax.get_legend() is not None
                self._check_text_labels(ax.get_legend().get_texts(), labels)
            else:
                assert ax.get_legend() is None 
Example #15
Source File: figure.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def get(self, key):
        """
        Return the Axes instance that was added with *key*.
        If it is not present, return *None*.
        """
        item = dict(self._elements).get(key)
        if item is None:
            return None
        cbook.warn_deprecated(
            "2.1",
            "Adding an axes using the same arguments as a previous axes "
            "currently reuses the earlier instance.  In a future version, "
            "a new instance will always be created and returned.  Meanwhile, "
            "this warning can be suppressed, and the future behavior ensured, "
            "by passing a unique label to each axes instance.")
        return item[1] 
Example #16
Source File: axislines.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def new_gridlines(self, ax):
        """
        Create and return a new GridlineCollection instance.

        *which* : "major" or "minor"
        *axis* : "both", "x" or "y"

        """
        gridlines = GridlinesCollection(None, transform=ax.transData,
                                        colors=rcParams['grid.color'],
                                        linestyles=rcParams['grid.linestyle'],
                                        linewidths=rcParams['grid.linewidth'])
        ax._set_artist_props(gridlines)
        gridlines.set_grid_helper(self)

        ax.axes._set_artist_props(gridlines)
        # gridlines.set_clip_path(self.axes.patch)
        # set_clip_path need to be deferred after Axes.cla is completed.
        # It is done inside the cla.

        return gridlines 
Example #17
Source File: common.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _check_ax_scales(self, axes, xaxis='linear', yaxis='linear'):
        """
        Check each axes has expected scales

        Parameters
        ----------
        axes : matplotlib Axes object, or its list-like
        xaxis : {'linear', 'log'}
            expected xaxis scale
        yaxis :  {'linear', 'log'}
            expected yaxis scale
        """
        axes = self._flatten_visible(axes)
        for ax in axes:
            assert ax.xaxis.get_scale() == xaxis
            assert ax.yaxis.get_scale() == yaxis 
Example #18
Source File: common.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _check_data(self, xp, rs):
        """
        Check each axes has identical lines

        Parameters
        ----------
        xp : matplotlib Axes object
        rs : matplotlib Axes object
        """
        xp_lines = xp.get_lines()
        rs_lines = rs.get_lines()

        def check_line(xpl, rsl):
            xpdata = xpl.get_xydata()
            rsdata = rsl.get_xydata()
            tm.assert_almost_equal(xpdata, rsdata)

        assert len(xp_lines) == len(rs_lines)
        [check_line(xpl, rsl) for xpl, rsl in zip(xp_lines, rs_lines)]
        tm.close() 
Example #19
Source File: common.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _check_legend_labels(self, axes, labels=None, visible=True):
        """
        Check each axes has expected legend labels

        Parameters
        ----------
        axes : matplotlib Axes object, or its list-like
        labels : list-like
            expected legend labels
        visible : bool
            expected legend visibility. labels are checked only when visible is
            True
        """

        if visible and (labels is None):
            raise ValueError('labels must be specified when visible is True')
        axes = self._flatten_visible(axes)
        for ax in axes:
            if visible:
                assert ax.get_legend() is not None
                self._check_text_labels(ax.get_legend().get_texts(), labels)
            else:
                assert ax.get_legend() is None 
Example #20
Source File: axislines.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def get_tightbbox(self, renderer, call_axes_locator=True):

        bb0 = super(Axes, self).get_tightbbox(renderer, call_axes_locator)

        if not self._axisline_on:
            return bb0

        bb = [bb0]

        for axisline in self._axislines.values():
            if not axisline.get_visible():
                continue

            bb.append(axisline.get_tightbbox(renderer))
            # if axisline.label.get_visible():
            #     bb.append(axisline.label.get_window_extent(renderer))


            # if axisline.major_ticklabels.get_visible():
            #     bb.extend(axisline.major_ticklabels.get_window_extents(renderer))
            # if axisline.minor_ticklabels.get_visible():
            #     bb.extend(axisline.minor_ticklabels.get_window_extents(renderer))
            # if axisline.major_ticklabels.get_visible() or \
            #    axisline.minor_ticklabels.get_visible():
            #     bb.append(axisline.offsetText.get_window_extent(renderer))

        #bb.extend([c.get_window_extent(renderer) for c in artists \
        #           if c.get_visible()])

        _bbox = Bbox.union([b for b in bb if b and (b.width!=0 or b.height!=0)])

        return _bbox 
Example #21
Source File: axislines.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def draw(self, renderer, inframe=False):

        if not self._axisline_on:
            super(Axes, self).draw(renderer, inframe)
            return

        orig_artists = self.artists
        self.artists = self.artists + list(self._axislines.values()) + [self.gridlines]

        super(Axes, self).draw(renderer, inframe)

        self.artists = orig_artists 
Example #22
Source File: mpl_axes.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def __init__(self, axes):
            self.axes = axes
            super(Axes.AxisDict, self).__init__() 
Example #23
Source File: axislines.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def grid(self, b=None, which='major', axis="both", **kwargs):
        """
        Toggle the gridlines, and optionally set the properties of the lines.
        """
        # their are some discrepancy between the behavior of grid in
        # axes_grid and the original mpl's grid, because axes_grid
        # explicitly set the visibility of the gridlines.

        super(Axes, self).grid(b, which=which, axis=axis, **kwargs)
        if not self._axisline_on:
            return

        if b is None:

            if self.axes.xaxis._gridOnMinor or self.axes.xaxis._gridOnMajor or \
                   self.axes.yaxis._gridOnMinor or self.axes.yaxis._gridOnMajor:
                b=True
            else:
                b=False

        self.gridlines.set_which(which)
        self.gridlines.set_axis(axis)
        self.gridlines.set_visible(b)

        if len(kwargs):
            martist.setp(self.gridlines, **kwargs) 
Example #24
Source File: axislines.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def _init_axis(self):
        super(Axes, self)._init_axis() 
Example #25
Source File: figure.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def add_artist(self, artist, clip=False):
        """
        Add any :class:`~matplotlib.artist.Artist` to the figure.

        Usually artists are added to axes objects using
        :meth:`matplotlib.axes.Axes.add_artist`, but use this method in the
        rare cases that adding directly to the figure is necessary.

        Parameters
        ----------
        artist : `~matplotlib.artist.Artist`
            The artist to add to the figure. If the added artist has no
            transform previously set, its transform will be set to
            ``figure.transFigure``.
        clip : bool, optional, default ``False``
            An optional parameter ``clip`` determines whether the added artist
            should be clipped by the figure patch. Default is *False*,
            i.e. no clipping.

        Returns
        -------
        artist : The added `~matplotlib.artist.Artist`
        """
        artist.set_figure(self)
        self.artists.append(artist)
        artist._remove_method = self.artists.remove

        if not artist.is_transform_set():
            artist.set_transform(self.transFigure)

        if clip:
            artist.set_clip_path(self.patch)

        self.stale = True
        return artist 
Example #26
Source File: axislines.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def __init__(self, *kl, **kw):


        helper = kw.pop("grid_helper", None)

        self._axisline_on = True

        if helper:
            self._grid_helper = helper
        else:
            self._grid_helper = GridHelperRectlinear(self)

        super(Axes, self).__init__(*kl, **kw)

        self.toggle_axisline(True) 
Example #27
Source File: axislines.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def get_children(self):
        if self._axisline_on:
            children = self._axislines.values()+[self.gridlines]
        else:
            children = []
        children.extend(super(Axes, self).get_children())
        return children 
Example #28
Source File: mpl_axes.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def __init__(self, *kl, **kw):
        super(Axes, self).__init__(*kl, **kw) 
Example #29
Source File: axes_size.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def __init__(self, ax, direction):
        if isinstance(ax, Axes):
            self._ax_list = [ax]
        else:
            self._ax_list = ax

        try:
            self._get_func = self._get_func_map[direction]
        except KeyError:
            raise KeyError("direction must be one of left, right, bottom, top") 
Example #30
Source File: mpl_axes.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def cla(self):

        super(Axes, self).cla()
        self._init_axis_artists()