Python matplotlib.transforms() Examples

The following are 30 code examples for showing how to use matplotlib.transforms(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module matplotlib , or try the search function .

Example 1
Project: neural-network-animation   Author: miloharper   File: test_axes.py    License: MIT License 6 votes vote down vote up
def test_imshow_clip():
    # As originally reported by Gellule Xg <gellule.xg@free.fr>

    #Create a NxN image
    N = 100
    (x, y) = np.indices((N, N))
    x -= N//2
    y -= N//2
    r = np.sqrt(x**2+y**2-x*y)

    #Create a contour plot at N/4 and extract both the clip path and transform
    fig = plt.figure()
    ax = fig.add_subplot(111)

    c = ax.contour(r, [N/4])
    x = c.collections[0]
    clipPath = x.get_paths()[0]
    clipTransform = x.get_transform()

    from matplotlib.transforms import TransformedPath
    clip_path = TransformedPath(clipPath, clipTransform)

    #Plot the image clipped by the contour
    ax.imshow(r, clip_path=clip_path) 
Example 2
Project: GraphicDesignPatternByPython   Author: Relph1119   File: _base.py    License: MIT License 6 votes vote down vote up
def set_position(self, pos, which='both'):
        """
        Set the axes position.

        Axes have two position attributes. The 'original' position is the
        position allocated for the Axes. The 'active' position is the
        position the Axes is actually drawn at. These positions are usually
        the same unless a fixed aspect is set to the Axes. See `.set_aspect`
        for details.

        Parameters
        ----------
        pos : [left, bottom, width, height] or `~matplotlib.transforms.Bbox`
            The new position of the in `.Figure` coordinates.

        which : {'both', 'active', 'original'}, optional
            Determines which position variables to change.

        """
        self._set_position(pos, which='both')
        # because this is being called externally to the library we
        # zero the constrained layout parts.
        self._layoutbox = None
        self._poslayoutbox = None 
Example 3
Project: python3_ios   Author: holzschu   File: test_axes.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_imshow_clip():
    # As originally reported by Gellule Xg <gellule.xg@free.fr>

    # Create a NxN image
    N = 100
    (x, y) = np.indices((N, N))
    x -= N//2
    y -= N//2
    r = np.sqrt(x**2+y**2-x*y)

    # Create a contour plot at N/4 and extract both the clip path and transform
    fig, ax = plt.subplots()

    c = ax.contour(r, [N/4])
    x = c.collections[0]
    clipPath = x.get_paths()[0]
    clipTransform = x.get_transform()

    from matplotlib.transforms import TransformedPath
    clip_path = TransformedPath(clipPath, clipTransform)

    # Plot the image clipped by the contour
    ax.imshow(r, clip_path=clip_path) 
Example 4
Project: ImageFusion   Author: pfchai   File: test_axes.py    License: MIT License 6 votes vote down vote up
def test_imshow_clip():
    # As originally reported by Gellule Xg <gellule.xg@free.fr>

    #Create a NxN image
    N = 100
    (x, y) = np.indices((N, N))
    x -= N//2
    y -= N//2
    r = np.sqrt(x**2+y**2-x*y)

    #Create a contour plot at N/4 and extract both the clip path and transform
    fig = plt.figure()
    ax = fig.add_subplot(111)

    c = ax.contour(r, [N/4])
    x = c.collections[0]
    clipPath = x.get_paths()[0]
    clipTransform = x.get_transform()

    from matplotlib.transforms import TransformedPath
    clip_path = TransformedPath(clipPath, clipTransform)

    #Plot the image clipped by the contour
    ax.imshow(r, clip_path=clip_path) 
Example 5
Project: coffeegrindsize   Author: jgagneastro   File: _base.py    License: MIT License 6 votes vote down vote up
def set_position(self, pos, which='both'):
        """
        Set the axes position.

        Axes have two position attributes. The 'original' position is the
        position allocated for the Axes. The 'active' position is the
        position the Axes is actually drawn at. These positions are usually
        the same unless a fixed aspect is set to the Axes. See `.set_aspect`
        for details.

        Parameters
        ----------
        pos : [left, bottom, width, height] or `~matplotlib.transforms.Bbox`
            The new position of the in `.Figure` coordinates.

        which : {'both', 'active', 'original'}, optional
            Determines which position variables to change.

        """
        self._set_position(pos, which=which)
        # because this is being called externally to the library we
        # zero the constrained layout parts.
        self._layoutbox = None
        self._poslayoutbox = None 
Example 6
Project: coffeegrindsize   Author: jgagneastro   File: test_axes.py    License: MIT License 6 votes vote down vote up
def test_imshow_clip():
    # As originally reported by Gellule Xg <gellule.xg@free.fr>

    # Create a NxN image
    N = 100
    (x, y) = np.indices((N, N))
    x -= N//2
    y -= N//2
    r = np.sqrt(x**2+y**2-x*y)

    # Create a contour plot at N/4 and extract both the clip path and transform
    fig, ax = plt.subplots()

    c = ax.contour(r, [N/4])
    x = c.collections[0]
    clipPath = x.get_paths()[0]
    clipTransform = x.get_transform()

    from matplotlib.transforms import TransformedPath
    clip_path = TransformedPath(clipPath, clipTransform)

    # Plot the image clipped by the contour
    ax.imshow(r, clip_path=clip_path) 
Example 7
Project: twitter-stock-recommendation   Author: alvarobartt   File: _base.py    License: MIT License 6 votes vote down vote up
def set_position(self, pos, which='both'):
        """
        Set the axes position.

        Axes have two position attributes. The 'original' position is the
        position allocated for the Axes. The 'active' position is the
        position the Axes is actually drawn at. These positions are usually
        the same unless a fixed aspect is set to the Axes. See `.set_aspect`
        for details.

        Parameters
        ----------
        pos : [left, bottom, width, height] or `~matplotlib.transforms.Bbox`
            The new position of the in `.Figure` coordinates.

        which : ['both' | 'active' | 'original'], optional
            Determines which position variables to change.

        """
        self._set_position(pos, which='both')
        # because this is being called externally to the library we
        # zero the constrained layout parts.
        self._layoutbox = None
        self._poslayoutbox = None 
Example 8
Project: twitter-stock-recommendation   Author: alvarobartt   File: test_axes.py    License: MIT License 6 votes vote down vote up
def test_imshow_clip():
    # As originally reported by Gellule Xg <gellule.xg@free.fr>

    # Create a NxN image
    N = 100
    (x, y) = np.indices((N, N))
    x -= N//2
    y -= N//2
    r = np.sqrt(x**2+y**2-x*y)

    # Create a contour plot at N/4 and extract both the clip path and transform
    fig, ax = plt.subplots()

    c = ax.contour(r, [N/4])
    x = c.collections[0]
    clipPath = x.get_paths()[0]
    clipTransform = x.get_transform()

    from matplotlib.transforms import TransformedPath
    clip_path = TransformedPath(clipPath, clipTransform)

    # Plot the image clipped by the contour
    ax.imshow(r, clip_path=clip_path) 
Example 9
Project: neural-network-animation   Author: miloharper   File: _base.py    License: MIT License 5 votes vote down vote up
def _set_lim_and_transforms(self):
        """
        set the *dataLim* and *viewLim*
        :class:`~matplotlib.transforms.Bbox` attributes and the
        *transScale*, *transData*, *transLimits* and *transAxes*
        transformations.

        .. note::

            This method is primarily used by rectilinear projections
            of the :class:`~matplotlib.axes.Axes` class, and is meant
            to be overridden by new kinds of projection axes that need
            different transformations and limits. (See
            :class:`~matplotlib.projections.polar.PolarAxes` for an
            example.

        """
        self.transAxes = mtransforms.BboxTransformTo(self.bbox)

        # Transforms the x and y axis separately by a scale factor.
        # It is assumed that this part will have non-linear components
        # (e.g., for a log scale).
        self.transScale = mtransforms.TransformWrapper(
            mtransforms.IdentityTransform())

        # An affine transformation on the data, generally to limit the
        # range of the axes
        self.transLimits = mtransforms.BboxTransformFrom(
            mtransforms.TransformedBbox(self.viewLim, self.transScale))

        # The parentheses are important for efficiency here -- they
        # group the last two (which are usually affines) separately
        # from the first (which, with log-scaling can be non-affine).
        self.transData = self.transScale + (self.transLimits + self.transAxes)

        self._xaxis_transform = mtransforms.blended_transform_factory(
            self.transData, self.transAxes)
        self._yaxis_transform = mtransforms.blended_transform_factory(
            self.transAxes, self.transData) 
Example 10
Project: neural-network-animation   Author: miloharper   File: _base.py    License: MIT License 5 votes vote down vote up
def set_position(self, pos, which='both'):
        """
        Set the axes position with::

          pos = [left, bottom, width, height]

        in relative 0,1 coords, or *pos* can be a
        :class:`~matplotlib.transforms.Bbox`

        There are two position variables: one which is ultimately
        used, but which may be modified by :meth:`apply_aspect`, and a
        second which is the starting point for :meth:`apply_aspect`.


        Optional keyword arguments:
          *which*

            ==========   ====================
            value        description
            ==========   ====================
            'active'     to change the first
            'original'   to change the second
            'both'       to change both
            ==========   ====================

        """
        if not isinstance(pos, mtransforms.BboxBase):
            pos = mtransforms.Bbox.from_bounds(*pos)
        if which in ('both', 'active'):
            self._position.set(pos)
        if which in ('both', 'original'):
            self._originalPosition.set(pos) 
Example 11
Project: neural-network-animation   Author: miloharper   File: _base.py    License: MIT License 5 votes vote down vote up
def update_datalim_bounds(self, bounds):
        """
        Update the datalim to include the given
        :class:`~matplotlib.transforms.Bbox` *bounds*
        """
        self.dataLim.set(mtransforms.Bbox.union([self.dataLim, bounds])) 
Example 12
Project: GraphicDesignPatternByPython   Author: Relph1119   File: spines.py    License: MIT License 5 votes vote down vote up
def get_window_extent(self, renderer=None):
        # make sure the location is updated so that transforms etc are
        # correct:
        self._adjust_location()
        return super().get_window_extent(renderer=renderer) 
Example 13
Project: GraphicDesignPatternByPython   Author: Relph1119   File: _base.py    License: MIT License 5 votes vote down vote up
def update_datalim_bounds(self, bounds):
        """
        Update the datalim to include the given
        :class:`~matplotlib.transforms.Bbox` *bounds*
        """
        self.dataLim.set(mtransforms.Bbox.union([self.dataLim, bounds])) 
Example 14
Project: python3_ios   Author: holzschu   File: skewt.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _need_lower(self):
        return (self._has_default_loc() or
                transforms.interval_contains(self.axes.lower_xlim,
                                             self.get_loc())) 
Example 15
Project: python3_ios   Author: holzschu   File: skewt.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _need_upper(self):
        return (self._has_default_loc() or
                transforms.interval_contains(self.axes.upper_xlim,
                                             self.get_loc())) 
Example 16
Project: python3_ios   Author: holzschu   File: skewt.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def gridOn(self):
        return (self._gridOn and (self._has_default_loc() or
                transforms.interval_contains(self.get_view_interval(),
                                             self.get_loc()))) 
Example 17
Project: python3_ios   Author: holzschu   File: skewt.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _set_lim_and_transforms(self):
        """
        This is called once when the plot is created to set up all the
        transforms for the data, text and grids.
        """
        rot = 30

        # Get the standard transform setup from the Axes base class
        Axes._set_lim_and_transforms(self)

        # Need to put the skew in the middle, after the scale and limits,
        # but before the transAxes. This way, the skew is done in Axes
        # coordinates thus performing the transform around the proper origin
        # We keep the pre-transAxes transform around for other users, like the
        # spines for finding bounds
        self.transDataToAxes = self.transScale + \
            self.transLimits + transforms.Affine2D().skew_deg(rot, 0)

        # Create the full transform from Data to Pixels
        self.transData = self.transDataToAxes + self.transAxes

        # Blended transforms like this need to have the skewing applied using
        # both axes, in axes coords like before.
        self._xaxis_transform = (transforms.blended_transform_factory(
            self.transScale + self.transLimits,
            transforms.IdentityTransform()) +
            transforms.Affine2D().skew_deg(rot, 0)) + self.transAxes 
Example 18
Project: python3_ios   Author: holzschu   File: spines.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_window_extent(self, renderer=None):
        # make sure the location is updated so that transforms etc are
        # correct:
        self._adjust_location()
        return super().get_window_extent(renderer=renderer) 
Example 19
Project: python3_ios   Author: holzschu   File: _base.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def update_datalim_bounds(self, bounds):
        """
        Extend the `~.Axes.datalim` BBox to include the given
        `~matplotlib.transforms.Bbox`.

        Parameters
        ----------
        bounds : `~matplotlib.transforms.Bbox`
        """
        self.dataLim.set(mtransforms.Bbox.union([self.dataLim, bounds])) 
Example 20
Project: FlowCal   Author: taborlab   File: plot.py    License: MIT License 5 votes vote down vote up
def __init__(self, transform, smin, smax, resolution=1000):
        # Call parent's constructor
        matplotlib.transforms.Transform.__init__(self)
        # Store transform object
        self._transform = transform

        # Generate input array
        self._s_range = np.linspace(smin, smax, resolution)
        # Evaluate provided transformation and store result
        self._x_range = transform.transform_non_affine(self._s_range)
        # Transform bounds and store
        self._xmin = transform.transform_non_affine(smin)
        self._xmax = transform.transform_non_affine(smax)
        if self._xmin > self._xmax:
            self._xmax, self._xmin = self._xmin, self._xmax 
Example 21
Project: FlowCal   Author: taborlab   File: plot.py    License: MIT License 5 votes vote down vote up
def inverted(self):
        """
        Get an object representing an inverse transformation to this class.

        Since this class implements the inverse of a given transformation,
        this function just returns the original transformation.

        Return
        ------
        matplotlib.transforms.Transform
            Object implementing the reverse transformation.

        """
        return self._transform 
Example 22
Project: FlowCal   Author: taborlab   File: plot.py    License: MIT License 5 votes vote down vote up
def view_limits(self, vmin, vmax):
        """
        Try to choose the view limits intelligently.

        """
        b = self._transform.base
        if vmax < vmin:
            vmin, vmax = vmax, vmin

        if not matplotlib.ticker.is_decade(abs(vmin), b):
            if vmin < 0:
                vmin = -_base_up(-vmin, b)
            else:
                vmin = _base_down(vmin, b)
        if not matplotlib.ticker.is_decade(abs(vmax), b):
            if vmax < 0:
                vmax = -_base_down(-vmax, b)
            else:
                vmax = _base_up(vmax, b)

        if vmin == vmax:
            if vmin < 0:
                vmin = -_base_up(-vmin, b)
                vmax = -_base_down(-vmax, b)
            else:
                vmin = _base_down(vmin, b)
                vmax = _base_up(vmax, b)
        result = matplotlib.transforms.nonsingular(vmin, vmax)
        return result 
Example 23
Project: ImageFusion   Author: pfchai   File: _base.py    License: MIT License 5 votes vote down vote up
def _set_lim_and_transforms(self):
        """
        set the *dataLim* and *viewLim*
        :class:`~matplotlib.transforms.Bbox` attributes and the
        *transScale*, *transData*, *transLimits* and *transAxes*
        transformations.

        .. note::

            This method is primarily used by rectilinear projections
            of the :class:`~matplotlib.axes.Axes` class, and is meant
            to be overridden by new kinds of projection axes that need
            different transformations and limits. (See
            :class:`~matplotlib.projections.polar.PolarAxes` for an
            example.

        """
        self.transAxes = mtransforms.BboxTransformTo(self.bbox)

        # Transforms the x and y axis separately by a scale factor.
        # It is assumed that this part will have non-linear components
        # (e.g., for a log scale).
        self.transScale = mtransforms.TransformWrapper(
            mtransforms.IdentityTransform())

        # An affine transformation on the data, generally to limit the
        # range of the axes
        self.transLimits = mtransforms.BboxTransformFrom(
            mtransforms.TransformedBbox(self.viewLim, self.transScale))

        # The parentheses are important for efficiency here -- they
        # group the last two (which are usually affines) separately
        # from the first (which, with log-scaling can be non-affine).
        self.transData = self.transScale + (self.transLimits + self.transAxes)

        self._xaxis_transform = mtransforms.blended_transform_factory(
            self.transData, self.transAxes)
        self._yaxis_transform = mtransforms.blended_transform_factory(
            self.transAxes, self.transData) 
Example 24
Project: ImageFusion   Author: pfchai   File: _base.py    License: MIT License 5 votes vote down vote up
def set_position(self, pos, which='both'):
        """
        Set the axes position with::

          pos = [left, bottom, width, height]

        in relative 0,1 coords, or *pos* can be a
        :class:`~matplotlib.transforms.Bbox`

        There are two position variables: one which is ultimately
        used, but which may be modified by :meth:`apply_aspect`, and a
        second which is the starting point for :meth:`apply_aspect`.


        Optional keyword arguments:
          *which*

            ==========   ====================
            value        description
            ==========   ====================
            'active'     to change the first
            'original'   to change the second
            'both'       to change both
            ==========   ====================

        """
        if not isinstance(pos, mtransforms.BboxBase):
            pos = mtransforms.Bbox.from_bounds(*pos)
        if which in ('both', 'active'):
            self._position.set(pos)
        if which in ('both', 'original'):
            self._originalPosition.set(pos) 
Example 25
Project: ImageFusion   Author: pfchai   File: _base.py    License: MIT License 5 votes vote down vote up
def update_datalim_bounds(self, bounds):
        """
        Update the datalim to include the given
        :class:`~matplotlib.transforms.Bbox` *bounds*
        """
        self.dataLim.set(mtransforms.Bbox.union([self.dataLim, bounds])) 
Example 26
Project: coffeegrindsize   Author: jgagneastro   File: spines.py    License: MIT License 5 votes vote down vote up
def get_window_extent(self, renderer=None):
        # make sure the location is updated so that transforms etc are
        # correct:
        self._adjust_location()
        return super().get_window_extent(renderer=renderer) 
Example 27
Project: coffeegrindsize   Author: jgagneastro   File: _base.py    License: MIT License 5 votes vote down vote up
def update_datalim_bounds(self, bounds):
        """
        Extend the `~.Axes.datalim` BBox to include the given
        `~matplotlib.transforms.Bbox`.

        Parameters
        ----------
        bounds : `~matplotlib.transforms.Bbox`
        """
        self.dataLim.set(mtransforms.Bbox.union([self.dataLim, bounds])) 
Example 28
Project: mmvt   Author: pelednoam   File: anatomy.py    License: GNU General Public License v3.0 5 votes vote down vote up
def cerebellum_segmentation(subject, remote_subject_dir, args, subregions_num=7, model='Buckner2011_7Networks'):
    # For cerebellum parcellation
    # http://www.freesurfer.net/fswiki/CerebellumParcellation_Buckner2011
    # First download the mask file and put it in the subject's mri folder
    # https://mail.nmr.mgh.harvard.edu/pipermail//freesurfer/2016-June/046380.html
    loose_tight = 'loose' if args.cerebellum_segmentation_loose else 'tight'
    bunker_atlas_fname = op.join(MMVT_DIR, 'templates', 'Buckner2011_atlas_{}_{}.nii.gz'.format(
        subregions_num, loose_tight))
    if not op.isfile(bunker_atlas_fname):
        print("Can't find Bunker atlas! Should be here: {}".format(bunker_atlas_fname))
        return False

    warp_buckner_atlas_fname = fu.warp_buckner_atlas_output_fname(subject, SUBJECTS_DIR,  subregions_num, loose_tight)
    if not op.isfile(warp_buckner_atlas_fname):
        prepare_subject_folder(subject, remote_subject_dir, args, {'mri:transforms' : ['talairach.m3z']})
        fu.warp_buckner_atlas(subject, SUBJECTS_DIR, bunker_atlas_fname, warp_buckner_atlas_fname)
    if not op.isfile(warp_buckner_atlas_fname):
        print('mask file does not exist! {}'.format(warp_buckner_atlas_fname))
        return False

    mask_data = nib.load(warp_buckner_atlas_fname).get_data()
    unique_values_num = len(np.unique(mask_data))
    if unique_values_num < subregions_num:
        print('subregions_num ({}) is bigger than the unique values num in the mask file ({})!'.format(
            subregions_num, unique_values_num))
        return False
    warp_buckner_hemis_atlas_fname = '{}_hemis.{}'.format(
        warp_buckner_atlas_fname.split('.')[0], '.'.join(warp_buckner_atlas_fname.split('.')[1:]))
    new_maks_fname = op.join(SUBJECTS_DIR, subject, 'mri', warp_buckner_hemis_atlas_fname)
    subregions_num = split_cerebellum_hemis(subject, warp_buckner_atlas_fname, new_maks_fname, subregions_num)
    subcortical_lookup = np.array([['{}_cerebellum_{}'.format(
        'right' if ind <= subregions_num/2 else 'left',  ind if ind <= subregions_num/2 else int(ind - subregions_num/2)), ind] for ind in range(1, subregions_num + 1)])
    lookup = {int(val): name for name, val in zip(subcortical_lookup[:, 0], subcortical_lookup[:, 1])}
    mmvt_subcorticals_fol_name = 'cerebellum'
    ret = subcortical_segmentation(subject, args.overwrite_subcorticals, lookup, warp_buckner_hemis_atlas_fname,
                                    mmvt_subcorticals_fol_name, subject)
    return ret 
Example 29
Project: mmvt   Author: pelednoam   File: anatomy.py    License: GNU General Public License v3.0 5 votes vote down vote up
def full_extent(ax, pad=0.0):
    from matplotlib.transforms import Bbox
    """Get the full extent of an axes, including axes labels, tick labels, and titles."""
    # For text objects, we need to draw the figure first, otherwise the extents
    # are undefined.
    ax.figure.canvas.draw()
    items = [ax, *ax.texts]
    bbox = Bbox.union([item.get_window_extent() for item in items])

    return bbox.expanded(1.0 + pad, 1.0 + pad)

# @utils.ignore_warnings 
Example 30
Project: mmvt   Author: pelednoam   File: anatomy.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_necessary_files():
    return {
        'mri': ['aseg.mgz', 'norm.mgz', 'ribbon.mgz', 'T1.mgz', 'orig.mgz', 'brain.mgz', 'brainmask.mgz',
                'aparc+aseg.mgz'],
        'surf': ['rh.pial', 'lh.pial', 'rh.inflated', 'lh.inflated', 'rh.white', 'lh.white', 'lh.curv', 'rh.curv',
                 'rh.sphere.reg', 'lh.sphere.reg', 'rh.sphere', 'lh.sphere', 'rh.smoothwm','lh.smoothwm',
                 'lh.sphere.reg', 'rh.sphere.reg', 'lh.thickness', 'rh.thickness'],
        'mri:transforms' :['talairach.xfm', 'talairach.m3z'],
        'label': ['lh.cortex.label', 'rh.cortex.label']}