Python matplotlib.cbook() Examples

The following are 30 code examples for showing how to use matplotlib.cbook(). 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: Computable   Author: ktraunmueller   File: font_manager.py    License: MIT License 6 votes vote down vote up
def OSXInstalledFonts(directories=None, fontext='ttf'):
    """
    Get list of font files on OS X - ignores font suffix by default.
    """
    if directories is None:
        directories = OSXFontDirectories

    fontext = get_fontext_synonyms(fontext)

    files = []
    for path in directories:
        if fontext is None:
            files.extend(cbook.listFiles(path, '*'))
        else:
            files.extend(list_fonts(path, fontext))
    return files 
Example 2
Project: Computable   Author: ktraunmueller   File: backend_gdk.py    License: MIT License 6 votes vote down vote up
def _print_image(self, filename, format, *args, **kwargs):
        width, height = self.get_width_height()
        pixmap = gtk.gdk.Pixmap (None, width, height, depth=24)
        self._render_figure(pixmap, width, height)

        # jpg colors don't match the display very well, png colors match
        # better
        pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, 0, 8,
                                width, height)
        pixbuf.get_from_drawable(pixmap, pixmap.get_colormap(),
                                 0, 0, 0, 0, width, height)

        # set the default quality, if we are writing a JPEG.
        # http://www.pygtk.org/docs/pygtk/class-gdkpixbuf.html#method-gdkpixbuf--save
        options = cbook.restrict_dict(kwargs, ['quality'])
        if format in ['jpg','jpeg']:
           if 'quality' not in options:
              options['quality'] = rcParams['savefig.jpeg_quality']
           options['quality'] = str(options['quality'])
            
        pixbuf.save(filename, format, options=options) 
Example 3
Project: Computable   Author: ktraunmueller   File: spines.py    License: MIT License 6 votes vote down vote up
def is_frame_like(self):
        """return True if directly on axes frame

        This is useful for determining if a spine is the edge of an
        old style MPL plot. If so, this function will return True.
        """
        self._ensure_position_is_set()
        position = self._position
        if cbook.is_string_like(position):
            if position == 'center':
                position = ('axes', 0.5)
            elif position == 'zero':
                position = ('data', 0)
        assert len(position) == 2, "position should be 2-tuple"
        position_type, amount = position
        if position_type == 'outward' and amount == 0:
            return True
        else:
            return False 
Example 4
Project: Computable   Author: ktraunmueller   File: cbook.py    License: MIT License 6 votes vote down vote up
def get_split_ind(seq, N):
    """
    *seq* is a list of words.  Return the index into seq such that::

        len(' '.join(seq[:ind])<=N

    .
    """

    sLen = 0
    # todo: use Alex's xrange pattern from the cbook for efficiency
    for (word, ind) in zip(seq, xrange(len(seq))):
        sLen += len(word) + 1  # +1 to account for the len(' ')
        if sLen >= N:
            return ind
    return len(seq) 
Example 5
Project: Computable   Author: ktraunmueller   File: artist.py    License: MIT License 6 votes vote down vote up
def __init__(self, o):
        """
        Initialize the artist inspector with an
        :class:`~matplotlib.artist.Artist` or sequence of :class:`Artists`.
        If a sequence is used, we assume it is a homogeneous sequence (all
        :class:`Artists` are of the same type) and it is your responsibility
        to make sure this is so.
        """
        if cbook.iterable(o) and len(o):
            o = o[0]

        self.oorig = o
        if not isinstance(o, type):
            o = type(o)
        self.o = o

        self.aliasd = self.get_aliases() 
Example 6
Project: Computable   Author: ktraunmueller   File: dates.py    License: MIT License 6 votes vote down vote up
def num2date(x, tz=None):
    """
    *x* is a float value which gives the number of days
    (fraction part represents hours, minutes, seconds) since
    0001-01-01 00:00:00 UTC *plus* *one*.
    The addition of one here is a historical artifact.  Also, note
    that the Gregorian calendar is assumed; this is not universal
    practice.  For details, see the module docstring.

    Return value is a :class:`datetime` instance in timezone *tz* (default to
    rcparams TZ value).

    If *x* is a sequence, a sequence of :class:`datetime` objects will
    be returned.
    """
    if tz is None:
        tz = _get_rc_timezone()
    if not cbook.iterable(x):
        return _from_ordinalf(x, tz)
    else:
        return [_from_ordinalf(val, tz) for val in x] 
Example 7
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: __init__.py    License: MIT License 6 votes vote down vote up
def flatten(seq, scalarp=is_scalar_or_string):
    """
    Return a generator of flattened nested containers

    For example:

        >>> from matplotlib.cbook import flatten
        >>> l = (('John', ['Hunter']), (1, 23), [[([42, (5, 23)], )]])
        >>> print(list(flatten(l)))
        ['John', 'Hunter', 1, 23, 42, 5, 23]

    By: Composite of Holger Krekel and Luther Blissett
    From: https://code.activestate.com/recipes/121294/
    and Recipe 1.12 in cookbook
    """
    for item in seq:
        if scalarp(item) or item is None:
            yield item
        else:
            yield from flatten(item, scalarp) 
Example 8
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: __init__.py    License: MIT License 6 votes vote down vote up
def _warn_external(message, category=None):
    """
    `warnings.warn` wrapper that sets *stacklevel* to "outside Matplotlib".

    The original emitter of the warning can be obtained by patching this
    function back to `warnings.warn`, i.e. ``cbook._warn_external =
    warnings.warn`` (or ``functools.partial(warnings.warn, stacklevel=2)``,
    etc.).
    """
    frame = sys._getframe()
    for stacklevel in itertools.count(1):  # lgtm[py/unused-loop-variable]
        if frame is None:
            # when called in embedded context may hit frame is None
            break
        if not re.match(r"\A(matplotlib|mpl_toolkits)(\Z|\.)",
                        # Work around sphinx-gallery not setting __name__.
                        frame.f_globals.get("__name__", "")):
            break
        frame = frame.f_back
    warnings.warn(message, category, stacklevel) 
Example 9
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: font_manager.py    License: MIT License 6 votes vote down vote up
def OSXInstalledFonts(directories=None, fontext='ttf'):
    """
    Get list of font files on OS X - ignores font suffix by default.
    """
    if directories is None:
        directories = OSXFontDirectories

    fontext = get_fontext_synonyms(fontext)

    files = []
    for path in directories:
        if fontext is None:
            files.extend(cbook.listFiles(path, '*'))
        else:
            files.extend(list_fonts(path, fontext))
    return files 
Example 10
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: backend_gdk.py    License: MIT License 6 votes vote down vote up
def _print_image(self, filename, format, *args, **kwargs):
        width, height = self.get_width_height()
        pixmap = gtk.gdk.Pixmap (None, width, height, depth=24)
        self._render_figure(pixmap, width, height)

        # jpg colors don't match the display very well, png colors match
        # better
        pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, 0, 8,
                                width, height)
        pixbuf.get_from_drawable(pixmap, pixmap.get_colormap(),
                                 0, 0, 0, 0, width, height)

        # set the default quality, if we are writing a JPEG.
        # http://www.pygtk.org/docs/pygtk/class-gdkpixbuf.html#method-gdkpixbuf--save
        options = cbook.restrict_dict(kwargs, ['quality'])
        if format in ['jpg','jpeg']:
           if 'quality' not in options:
              options['quality'] = rcParams['savefig.jpeg_quality']
           options['quality'] = str(options['quality'])
            
        pixbuf.save(filename, format, options=options) 
Example 11
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: spines.py    License: MIT License 6 votes vote down vote up
def is_frame_like(self):
        """return True if directly on axes frame

        This is useful for determining if a spine is the edge of an
        old style MPL plot. If so, this function will return True.
        """
        self._ensure_position_is_set()
        position = self._position
        if cbook.is_string_like(position):
            if position == 'center':
                position = ('axes', 0.5)
            elif position == 'zero':
                position = ('data', 0)
        assert len(position) == 2, "position should be 2-tuple"
        position_type, amount = position
        if position_type == 'outward' and amount == 0:
            return True
        else:
            return False 
Example 12
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: cbook.py    License: MIT License 6 votes vote down vote up
def get_split_ind(seq, N):
    """
    *seq* is a list of words.  Return the index into seq such that::

        len(' '.join(seq[:ind])<=N

    .
    """

    sLen = 0
    # todo: use Alex's xrange pattern from the cbook for efficiency
    for (word, ind) in zip(seq, xrange(len(seq))):
        sLen += len(word) + 1  # +1 to account for the len(' ')
        if sLen >= N:
            return ind
    return len(seq) 
Example 13
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: artist.py    License: MIT License 6 votes vote down vote up
def __init__(self, o):
        """
        Initialize the artist inspector with an
        :class:`~matplotlib.artist.Artist` or sequence of :class:`Artists`.
        If a sequence is used, we assume it is a homogeneous sequence (all
        :class:`Artists` are of the same type) and it is your responsibility
        to make sure this is so.
        """
        if cbook.iterable(o) and len(o):
            o = o[0]

        self.oorig = o
        if not isinstance(o, type):
            o = type(o)
        self.o = o

        self.aliasd = self.get_aliases() 
Example 14
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: dates.py    License: MIT License 6 votes vote down vote up
def num2date(x, tz=None):
    """
    *x* is a float value which gives the number of days
    (fraction part represents hours, minutes, seconds) since
    0001-01-01 00:00:00 UTC *plus* *one*.
    The addition of one here is a historical artifact.  Also, note
    that the Gregorian calendar is assumed; this is not universal
    practice.  For details, see the module docstring.

    Return value is a :class:`datetime` instance in timezone *tz* (default to
    rcparams TZ value).

    If *x* is a sequence, a sequence of :class:`datetime` objects will
    be returned.
    """
    if tz is None:
        tz = _get_rc_timezone()
    if not cbook.iterable(x):
        return _from_ordinalf(x, tz)
    else:
        return [_from_ordinalf(val, tz) for val in x] 
Example 15
Project: neural-network-animation   Author: miloharper   File: font_manager.py    License: MIT License 6 votes vote down vote up
def OSXInstalledFonts(directories=None, fontext='ttf'):
    """
    Get list of font files on OS X - ignores font suffix by default.
    """
    if directories is None:
        directories = OSXFontDirectories

    fontext = get_fontext_synonyms(fontext)

    files = []
    for path in directories:
        if fontext is None:
            files.extend(cbook.listFiles(path, '*'))
        else:
            files.extend(list_fonts(path, fontext))
    return files 
Example 16
Project: neural-network-animation   Author: miloharper   File: backend_gdk.py    License: MIT License 6 votes vote down vote up
def _print_image(self, filename, format, *args, **kwargs):
        width, height = self.get_width_height()
        pixmap = gtk.gdk.Pixmap (None, width, height, depth=24)
        self._render_figure(pixmap, width, height)

        # jpg colors don't match the display very well, png colors match
        # better
        pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, 0, 8,
                                width, height)
        pixbuf.get_from_drawable(pixmap, pixmap.get_colormap(),
                                 0, 0, 0, 0, width, height)

        # set the default quality, if we are writing a JPEG.
        # http://www.pygtk.org/docs/pygtk/class-gdkpixbuf.html#method-gdkpixbuf--save
        options = cbook.restrict_dict(kwargs, ['quality'])
        if format in ['jpg','jpeg']:
           if 'quality' not in options:
              options['quality'] = rcParams['savefig.jpeg_quality']
           options['quality'] = str(options['quality'])

        pixbuf.save(filename, format, options=options) 
Example 17
Project: neural-network-animation   Author: miloharper   File: spines.py    License: MIT License 6 votes vote down vote up
def is_frame_like(self):
        """return True if directly on axes frame

        This is useful for determining if a spine is the edge of an
        old style MPL plot. If so, this function will return True.
        """
        self._ensure_position_is_set()
        position = self._position
        if cbook.is_string_like(position):
            if position == 'center':
                position = ('axes', 0.5)
            elif position == 'zero':
                position = ('data', 0)
        assert len(position) == 2, "position should be 2-tuple"
        position_type, amount = position
        if position_type == 'outward' and amount == 0:
            return True
        else:
            return False 
Example 18
Project: neural-network-animation   Author: miloharper   File: cbook.py    License: MIT License 6 votes vote down vote up
def get_split_ind(seq, N):
    """
    *seq* is a list of words.  Return the index into seq such that::

        len(' '.join(seq[:ind])<=N

    .
    """

    sLen = 0
    # todo: use Alex's xrange pattern from the cbook for efficiency
    for (word, ind) in zip(seq, xrange(len(seq))):
        sLen += len(word) + 1  # +1 to account for the len(' ')
        if sLen >= N:
            return ind
    return len(seq) 
Example 19
Project: neural-network-animation   Author: miloharper   File: _base.py    License: MIT License 6 votes vote down vote up
def get_xticklabels(self, minor=False, which=None):
        """
        Get the x tick labels as a list of :class:`~matplotlib.text.Text`
        instances.

        Parameters
        ----------
        minor : bool
           If True return the minor ticklabels,
           else return the major ticklabels

        which : None, ('minor', 'major', 'both')
           Overrides `minor`.

           Selects which ticklabels to return

        Returns
        -------
        ret : list
           List of :class:`~matplotlib.text.Text` instances.
        """
        return cbook.silent_list('Text xticklabel',
                                 self.xaxis.get_ticklabels(minor=minor,
                                                           which=which)) 
Example 20
Project: neural-network-animation   Author: miloharper   File: _base.py    License: MIT License 6 votes vote down vote up
def get_yticklabels(self, minor=False, which=None):
        """
        Get the x tick labels as a list of :class:`~matplotlib.text.Text`
        instances.

        Parameters
        ----------
        minor : bool
           If True return the minor ticklabels,
           else return the major ticklabels

        which : None, ('minor', 'major', 'both')
           Overrides `minor`.

           Selects which ticklabels to return

        Returns
        -------
        ret : list
           List of :class:`~matplotlib.text.Text` instances.
        """
        return cbook.silent_list('Text yticklabel',
                                  self.yaxis.get_ticklabels(minor=minor,
                                                            which=which)) 
Example 21
Project: neural-network-animation   Author: miloharper   File: _base.py    License: MIT License 6 votes vote down vote up
def start_pan(self, x, y, button):
        """
        Called when a pan operation has started.

        *x*, *y* are the mouse coordinates in display coords.
        button is the mouse button number:

        * 1: LEFT
        * 2: MIDDLE
        * 3: RIGHT

        .. note::

            Intended to be overridden by new projection types.

        """
        self._pan_start = cbook.Bunch(
            lim=self.viewLim.frozen(),
            trans=self.transData.frozen(),
            trans_inverse=self.transData.inverted().frozen(),
            bbox=self.bbox.frozen(),
            x=x,
            y=y) 
Example 22
Project: neural-network-animation   Author: miloharper   File: artist.py    License: MIT License 6 votes vote down vote up
def __init__(self, o):
        """
        Initialize the artist inspector with an
        :class:`~matplotlib.artist.Artist` or sequence of :class:`Artists`.
        If a sequence is used, we assume it is a homogeneous sequence (all
        :class:`Artists` are of the same type) and it is your responsibility
        to make sure this is so.
        """
        if cbook.iterable(o) and len(o):
            o = o[0]

        self.oorig = o
        if not isinstance(o, type):
            o = type(o)
        self.o = o

        self.aliasd = self.get_aliases() 
Example 23
Project: neural-network-animation   Author: miloharper   File: dates.py    License: MIT License 6 votes vote down vote up
def date2num(d):
    """
    *d* is either a :class:`datetime` instance or a sequence of datetimes.

    Return value is a floating point number (or sequence of floats)
    which gives the number of days (fraction part represents hours,
    minutes, seconds) since 0001-01-01 00:00:00 UTC, *plus* *one*.
    The addition of one here is a historical artifact.  Also, note
    that the Gregorian calendar is assumed; this is not universal
    practice.  For details, see the module docstring.
    """
    if not cbook.iterable(d):
        return _to_ordinalf(d)
    else:
        d = np.asarray(d)
        if not d.size:
            return d
        return _to_ordinalf_np_vectorized(d) 
Example 24
Project: neural-network-animation   Author: miloharper   File: dates.py    License: MIT License 6 votes vote down vote up
def num2date(x, tz=None):
    """
    *x* is a float value which gives the number of days
    (fraction part represents hours, minutes, seconds) since
    0001-01-01 00:00:00 UTC *plus* *one*.
    The addition of one here is a historical artifact.  Also, note
    that the Gregorian calendar is assumed; this is not universal
    practice.  For details, see the module docstring.

    Return value is a :class:`datetime` instance in timezone *tz* (default to
    rcparams TZ value).

    If *x* is a sequence, a sequence of :class:`datetime` objects will
    be returned.
    """
    if tz is None:
        tz = _get_rc_timezone()
    if not cbook.iterable(x):
        return _from_ordinalf(x, tz)
    else:
        x = np.asarray(x)
        if not x.size:
            return x
        return _from_ordinalf_np_vectorized(x, tz).tolist() 
Example 25
Project: GraphicDesignPatternByPython   Author: Relph1119   File: __init__.py    License: MIT License 6 votes vote down vote up
def flatten(seq, scalarp=is_scalar_or_string):
    """
    Returns a generator of flattened nested containers

    For example:

        >>> from matplotlib.cbook import flatten
        >>> l = (('John', ['Hunter']), (1, 23), [[([42, (5, 23)], )]])
        >>> print(list(flatten(l)))
        ['John', 'Hunter', 1, 23, 42, 5, 23]

    By: Composite of Holger Krekel and Luther Blissett
    From: https://code.activestate.com/recipes/121294/
    and Recipe 1.12 in cookbook
    """
    for item in seq:
        if scalarp(item) or item is None:
            yield item
        else:
            yield from flatten(item, scalarp) 
Example 26
Project: GraphicDesignPatternByPython   Author: Relph1119   File: __init__.py    License: MIT License 6 votes vote down vote up
def _warn_external(message, category=None):
    """
    `warnings.warn` wrapper that sets *stacklevel* to "outside Matplotlib".

    The original emitter of the warning can be obtained by patching this
    function back to `warnings.warn`, i.e. ``cbook._warn_external =
    warnings.warn`` (or ``functools.partial(warnings.warn, stacklevel=2)``,
    etc.).
    """
    frame = sys._getframe()
    for stacklevel in itertools.count(1):
        if not re.match(r"\A(matplotlib|mpl_toolkits)(\Z|\.)",
                        frame.f_globals["__name__"]):
            break
        frame = frame.f_back
    warnings.warn(message, category, stacklevel) 
Example 27
Project: GraphicDesignPatternByPython   Author: Relph1119   File: _base.py    License: MIT License 6 votes vote down vote up
def get_xticklabels(self, minor=False, which=None):
        """
        Get the x tick labels as a list of :class:`~matplotlib.text.Text`
        instances.

        Parameters
        ----------
        minor : bool, optional
           If True return the minor ticklabels,
           else return the major ticklabels.

        which : None, ('minor', 'major', 'both')
           Overrides `minor`.

           Selects which ticklabels to return

        Returns
        -------
        ret : list
           List of :class:`~matplotlib.text.Text` instances.
        """
        return cbook.silent_list('Text xticklabel',
                                 self.xaxis.get_ticklabels(minor=minor,
                                                           which=which)) 
Example 28
Project: GraphicDesignPatternByPython   Author: Relph1119   File: dates.py    License: MIT License 6 votes vote down vote up
def julian2num(j):
    """
    Convert a Julian date (or sequence) to a Matplotlib date (or sequence).

    Parameters
    ----------
    j : float or sequence of floats
        Julian date(s)

    Returns
    -------
    float or sequence of floats
        Matplotlib date(s)
    """
    if cbook.iterable(j):
        j = np.asarray(j)
    return j - JULIAN_OFFSET 
Example 29
Project: GraphicDesignPatternByPython   Author: Relph1119   File: dates.py    License: MIT License 6 votes vote down vote up
def num2julian(n):
    """
    Convert a Matplotlib date (or sequence) to a Julian date (or sequence).

    Parameters
    ----------
    n : float or sequence of floats
        Matplotlib date(s)

    Returns
    -------
    float or sequence of floats
        Julian date(s)
    """
    if cbook.iterable(n):
        n = np.asarray(n)
    return n + JULIAN_OFFSET 
Example 30
Project: GraphicDesignPatternByPython   Author: Relph1119   File: dates.py    License: MIT License 6 votes vote down vote up
def num2timedelta(x):
    """
    Convert number of days to a `~datetime.timedelta` object.

    If *x* is a sequence, a sequence of `~datetime.timedelta` objects will
    be returned.

    Parameters
    ----------
    x : float, sequence of floats
        Number of days. The fraction part represents hours, minutes, seconds.

    Returns
    -------
    `datetime.timedelta` or list[`datetime.timedelta`]

    """
    if not cbook.iterable(x):
        return _ordinalf_to_timedelta(x)
    else:
        x = np.asarray(x)
        if not x.size:
            return x
        return _ordinalf_to_timedelta_np_vectorized(x).tolist()