Python matplotlib.__version__() Examples

The following are 30 code examples for showing how to use matplotlib.__version__(). 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: king-phisher   Author: rsmusllp   File: graphs.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def add_legend_patch(self, legend_rows, fontsize=None):
		if matplotlib.__version__ == '3.0.2':
			self.logger.warning('skipping legend patch with matplotlib v3.0.2 for compatibility')
			return
		if self._legend is not None:
			self._legend.remove()
			self._legend = None
		fontsize = fontsize or self.fontsize_scale
		legend_bbox = self.figure.legend(
			tuple(patches.Patch(color=patch_color) for patch_color, _ in legend_rows),
			tuple(label for _, label in legend_rows),
			borderaxespad=1.25,
			fontsize=fontsize,
			frameon=True,
			handlelength=1.5,
			handletextpad=0.75,
			labelspacing=0.3,
			loc='lower right'
		)
		legend_bbox.legendPatch.set_linewidth(0)
		self._legend = legend_bbox 
Example 2
Project: king-phisher   Author: rsmusllp   File: graphs.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def add_legend_patch(self, legend_rows, fontsize=None):
		if matplotlib.__version__ == '3.0.2':
			self.logger.warning('skipping legend patch with matplotlib v3.0.2 for compatibility')
			return
		if self._legend is not None:
			self._legend.remove()
			self._legend = None
		legend_bbox = self.figure.legend(
			tuple(lines.Line2D([], [], color=patch_color, lw=3, ls=style) for patch_color, style, _ in legend_rows),
			tuple(label for _, _, label in legend_rows),
			borderaxespad=1,
			columnspacing=1.5,
			fontsize=self.fontsize_scale,
			ncol=3,
			frameon=True,
			handlelength=2,
			handletextpad=0.5,
			labelspacing=0.5,
			loc='upper right'
		)
		legend_bbox.get_frame().set_facecolor(self.get_color('line_bg', ColorHexCode.GRAY))
		for text in legend_bbox.get_texts():
			text.set_color('white')
		legend_bbox.legendPatch.set_linewidth(0)
		self._legend = legend_bbox 
Example 3
Project: pmdarima   Author: alkaline-ml   File: matplotlib.py    License: MIT License 6 votes vote down vote up
def mpl_hist_arg(value=True):
    """Find the appropriate `density` kwarg for our given matplotlib version.

    This will determine if we should use `normed` or `density`. Additionally,
    since this is a kwarg, the user can supply a value (True or False) that
    they would like in the output dictionary.

    Parameters
    ----------
    value : bool, optional (default=True)
        The boolean value of density/normed

    Returns
    -------
    density_kwarg : dict
        A dictionary containing the appropriate density kwarg for the
        installed  matplotlib version, mapped to the provided or default
        value
    """
    import matplotlib

    density_kwarg = 'density' if matplotlib.__version__ >= '2.1.0'\
        else 'normed'
    return {density_kwarg: value} 
Example 4
Project: Computable   Author: ktraunmueller   File: figure.py    License: MIT License 6 votes vote down vote up
def __getstate__(self):
        state = self.__dict__.copy()
        # the axobservers cannot currently be pickled.
        # Additionally, the canvas cannot currently be pickled, but this has
        # the benefit of meaning that a figure can be detached from one canvas,
        # and re-attached to another.
        for attr_to_pop in ('_axobservers', 'show',
                            'canvas', '_cachedRenderer'):
            state.pop(attr_to_pop, None)

        # add version information to the state
        state['__mpl_version__'] = _mpl_version

        # check to see if the figure has a manager and whether it is registered
        # with pyplot
        if getattr(self.canvas, 'manager', None) is not None:
            manager = self.canvas.manager
            import matplotlib._pylab_helpers
            if manager in matplotlib._pylab_helpers.Gcf.figs.values():
                state['_restore_to_pylab'] = True

        return state 
Example 5
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: figure.py    License: MIT License 6 votes vote down vote up
def __getstate__(self):
        state = self.__dict__.copy()
        # the axobservers cannot currently be pickled.
        # Additionally, the canvas cannot currently be pickled, but this has
        # the benefit of meaning that a figure can be detached from one canvas,
        # and re-attached to another.
        for attr_to_pop in ('_axobservers', 'show',
                            'canvas', '_cachedRenderer'):
            state.pop(attr_to_pop, None)

        # add version information to the state
        state['__mpl_version__'] = _mpl_version

        # check to see if the figure has a manager and whether it is registered
        # with pyplot
        if getattr(self.canvas, 'manager', None) is not None:
            manager = self.canvas.manager
            import matplotlib._pylab_helpers
            if manager in matplotlib._pylab_helpers.Gcf.figs.values():
                state['_restore_to_pylab'] = True

        return state 
Example 6
Project: mplexporter   Author: mpld3   File: base.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _iter_path_collection(paths, path_transforms, offsets, styles):
        """Build an iterator over the elements of the path collection"""
        N = max(len(paths), len(offsets))

        # Before mpl 1.4.0, path_transform can be a false-y value, not a valid
        # transformation matrix.
        if LooseVersion(mpl.__version__) < LooseVersion('1.4.0'):
            if path_transforms is None:
                path_transforms = [np.eye(3)]

        edgecolor = styles['edgecolor']
        if np.size(edgecolor) == 0:
            edgecolor = ['none']
        facecolor = styles['facecolor']
        if np.size(facecolor) == 0:
            facecolor = ['none']

        elements = [paths, path_transforms, offsets,
                    edgecolor, styles['linewidth'], facecolor]

        it = itertools
        return it.islice(py3k.zip(*py3k.map(it.cycle, elements)), N) 
Example 7
Project: mplexporter   Author: mpld3   File: test_basic.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_image():
    # Test fails for matplotlib 1.5+ because the size of the image
    # generated by matplotlib has changed.
    if LooseVersion(matplotlib.__version__) >= LooseVersion('1.5.0'):
        raise SkipTest("Test fails for matplotlib version > 1.5.0");
    np.random.seed(0)  # image size depends on the seed
    fig, ax = plt.subplots(figsize=(2, 2))
    ax.imshow(np.random.random((10, 10)),
              cmap=plt.cm.jet, interpolation='nearest')
    _assert_output_equal(fake_renderer_output(fig, FakeRenderer),
                         """
                         opening figure
                         opening axes
                         draw image of size 1240 
                         closing axes
                         closing figure
                         """) 
Example 8
Project: neural-network-animation   Author: miloharper   File: figure.py    License: MIT License 6 votes vote down vote up
def __getstate__(self):
        state = self.__dict__.copy()
        # the axobservers cannot currently be pickled.
        # Additionally, the canvas cannot currently be pickled, but this has
        # the benefit of meaning that a figure can be detached from one canvas,
        # and re-attached to another.
        for attr_to_pop in ('_axobservers', 'show',
                            'canvas', '_cachedRenderer'):
            state.pop(attr_to_pop, None)

        # add version information to the state
        state['__mpl_version__'] = _mpl_version

        # check to see if the figure has a manager and whether it is registered
        # with pyplot
        if getattr(self.canvas, 'manager', None) is not None:
            manager = self.canvas.manager
            import matplotlib._pylab_helpers
            if manager in list(six.itervalues(
                    matplotlib._pylab_helpers.Gcf.figs)):
                state['_restore_to_pylab'] = True

        return state 
Example 9
Project: RF-Monitor   Author: EarToEarOak   File: navigation_toolbar.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, canvas, legend):
        NavigationToolbar2Wx.__init__(self, canvas)
        self._canvas = canvas
        self._legend = legend
        self._autoScale = True

        if matplotlib.__version__ >= '1.2':
            panId = self.wx_ids['Pan']
        else:
            panId = self.FindById(self._NTB2_PAN).GetId()
        self.ToggleTool(panId, True)
        self.pan()

        checkLegend = wx.CheckBox(self, label='Legend')
        checkLegend.SetValue(legend.get_visible())
        self.AddControl(checkLegend)
        self.Bind(wx.EVT_CHECKBOX, self.__on_legend, checkLegend, id)

        if wx.__version__ >= '2.9.1':
            self.AddStretchableSpace()
        else:
            self.AddSeparator()

        self._textCursor = wx.StaticText(self, style=wx.ALL | wx.ALIGN_RIGHT)
        font = self._textCursor.GetFont()
        if wx.__version__ >= '2.9.1':
            font.MakeSmaller()
        font.SetFamily(wx.FONTFAMILY_TELETYPE)
        self._textCursor.SetFont(font)
        w, _h = get_text_size(' ' * 18, font)
        self._textCursor.SetSize((w, -1))

        self.AddControl(self._textCursor)

        self.Realize() 
Example 10
Project: ASPP-2018-numpy   Author: ASPP   File: tools.py    License: MIT License 5 votes vote down vote up
def sysinfo():
    import sys
    import time
    import numpy as np
    import scipy as sp
    import matplotlib

    print("Date:       %s" % (time.strftime("%D")))
    version = sys.version_info
    major, minor, micro = version.major, version.minor, version.micro
    print("Python:     %d.%d.%d" % (major, minor, micro))
    print("Numpy:     ", np.__version__)
    print("Scipy:     ", sp.__version__)
    print("Matplotlib:", matplotlib.__version__) 
Example 11
Project: recruit   Author: Frank-qlu   File: _compat.py    License: Apache License 2.0 5 votes vote down vote up
def _mpl_version(version, op):
    def inner():
        try:
            import matplotlib as mpl
        except ImportError:
            return False
        return (op(LooseVersion(mpl.__version__), LooseVersion(version)) and
                str(mpl.__version__)[0] != '0')

    return inner 
Example 12
Project: matplotlib-style-gallery   Author: tonysyu   File: app.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _rendering_kwargs(self):
        return dict(
            allow_inputs=self._allow_inputs,
            column_headers=self._plot_names,
            input_status=self._input_status,
            input_stylesheet=self._input_stylesheet,
            matplotlib_version=matplotlib.__version__,
        ) 
Example 13
Project: skutil   Author: tgsmith61591   File: setup.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_pandas_status():
    try:
        import pandas as pd
        return _check_version(pd.__version__, pandas_min_version)
    except ImportError:
        traceback.print_exc()
        return default_status 
Example 14
Project: skutil   Author: tgsmith61591   File: setup.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_sklearn_status():
    try:
        import sklearn as sk
        return _check_version(sk.__version__, sklearn_min_version)
    except ImportError:
        traceback.print_exc()
        return default_status 
Example 15
Project: skutil   Author: tgsmith61591   File: setup.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_numpy_status():
    try:
        import numpy as np
        return _check_version(np.__version__, numpy_min_version)
    except ImportError:
        traceback.print_exc()
        return default_status 
Example 16
Project: skutil   Author: tgsmith61591   File: setup.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_scipy_status():
    try:
        import scipy as sc
        return _check_version(sc.__version__, scipy_min_version)
    except ImportError:
        traceback.print_exc()
        return default_status 
Example 17
Project: skutil   Author: tgsmith61591   File: setup.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_h2o_status():
    try:
        import h2o
        return _check_version(h2o.__version__, h2o_min_version)
    except ImportError:
        traceback.print_exc()
        return default_status 
Example 18
Project: vnpy_crypto   Author: birforce   File: _compat.py    License: MIT License 5 votes vote down vote up
def _mpl_version(version, op):
    def inner():
        try:
            import matplotlib as mpl
        except ImportError:
            return False
        return (op(LooseVersion(mpl.__version__), LooseVersion(version)) and
                str(mpl.__version__)[0] != '0')

    return inner 
Example 19
Project: vnpy_crypto   Author: birforce   File: _misc.py    License: MIT License 5 votes vote down vote up
def _get_marker_compat(marker):
    import matplotlib.lines as mlines
    import matplotlib as mpl
    if mpl.__version__ < '1.1.0' and marker == '.':
        return 'o'
    if marker not in mlines.lineMarkers:
        return 'o'
    return marker 
Example 20
Project: vnpy_crypto   Author: birforce   File: test_boxplot_method.py    License: MIT License 5 votes vote down vote up
def _skip_if_mpl_14_or_dev_boxplot():
    # GH 8382
    # Boxplot failures on 1.4 and 1.4.1
    # Don't need try / except since that's done at class level
    import matplotlib
    if LooseVersion(matplotlib.__version__) >= LooseVersion('1.4'):
        pytest.skip("Matplotlib Regression in 1.4 and current dev.") 
Example 21
Project: Computable   Author: ktraunmueller   File: figure.py    License: MIT License 5 votes vote down vote up
def __setstate__(self, state):
        version = state.pop('__mpl_version__')
        restore_to_pylab = state.pop('_restore_to_pylab', False)

        if version != _mpl_version:
            import warnings
            warnings.warn("This figure was saved with matplotlib version %s "
                          "and is unlikely to function correctly." %
                          (version, ))

        self.__dict__ = state

        # re-initialise some of the unstored state information
        self._axobservers = []
        self.canvas = None

        if restore_to_pylab:
            # lazy import to avoid circularity
            import matplotlib.pyplot as plt
            import matplotlib._pylab_helpers as pylab_helpers
            allnums = plt.get_fignums()
            num = max(allnums) + 1 if allnums else 1
            mgr = plt._backend_mod.new_figure_manager_given_figure(num, self)

            # XXX The following is a copy and paste from pyplot. Consider
            # factoring to pylab_helpers

            if self.get_label():
                mgr.set_window_title(self.get_label())

            # make this figure current on button press event
            def make_active(event):
                pylab_helpers.Gcf.set_active(mgr)

            mgr._cidgcf = mgr.canvas.mpl_connect('button_press_event',
                                                 make_active)

            pylab_helpers.Gcf.set_active(mgr)
            self.number = num

            plt.draw_if_interactive() 
Example 22
Project: Computable   Author: ktraunmueller   File: plotting.py    License: MIT License 5 votes vote down vote up
def _get_marker_compat(marker):
    import matplotlib.lines as mlines
    import matplotlib as mpl
    if mpl.__version__ < '1.1.0' and marker == '.':
        return 'o'
    if marker not in mlines.lineMarkers:
        return 'o'
    return marker 
Example 23
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: plot_directive.py    License: MIT License 5 votes vote down vote up
def setup(app):
    import matplotlib
    setup.app = app
    setup.config = app.config
    setup.confdir = app.confdir
    app.add_directive('plot', PlotDirective)
    app.add_config_value('plot_pre_code', None, True)
    app.add_config_value('plot_include_source', False, True)
    app.add_config_value('plot_html_show_source_link', True, True)
    app.add_config_value('plot_formats', ['png', 'hires.png', 'pdf'], True)
    app.add_config_value('plot_basedir', None, True)
    app.add_config_value('plot_html_show_formats', True, True)
    app.add_config_value('plot_rcparams', {}, True)
    app.add_config_value('plot_apply_rcparams', False, True)
    app.add_config_value('plot_working_directory', None, True)
    app.add_config_value('plot_template', None, True)

    app.connect('doctree-read', mark_plot_labels)

    metadata = {'parallel_read_safe': True, 'parallel_write_safe': True,
                'version': matplotlib.__version__}
    return metadata


# -----------------------------------------------------------------------------
# Doctest handling
# ----------------------------------------------------------------------------- 
Example 24
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: figure.py    License: MIT License 5 votes vote down vote up
def __setstate__(self, state):
        version = state.pop('__mpl_version__')
        restore_to_pylab = state.pop('_restore_to_pylab', False)

        if version != _mpl_version:
            import warnings
            warnings.warn("This figure was saved with matplotlib version %s "
                          "and is unlikely to function correctly." %
                          (version, ))

        self.__dict__ = state

        # re-initialise some of the unstored state information
        self._axobservers = []
        self.canvas = None

        if restore_to_pylab:
            # lazy import to avoid circularity
            import matplotlib.pyplot as plt
            import matplotlib._pylab_helpers as pylab_helpers
            allnums = plt.get_fignums()
            num = max(allnums) + 1 if allnums else 1
            mgr = plt._backend_mod.new_figure_manager_given_figure(num, self)

            # XXX The following is a copy and paste from pyplot. Consider
            # factoring to pylab_helpers

            if self.get_label():
                mgr.set_window_title(self.get_label())

            # make this figure current on button press event
            def make_active(event):
                pylab_helpers.Gcf.set_active(mgr)

            mgr._cidgcf = mgr.canvas.mpl_connect('button_press_event',
                                                 make_active)

            pylab_helpers.Gcf.set_active(mgr)
            self.number = num

            plt.draw_if_interactive() 
Example 25
Project: scanpy   Author: theislab   File: _utils.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_projection_available(projection):
    avail_projections = {'2d', '3d'}
    if projection not in avail_projections:
        raise ValueError(f'choose projection from {avail_projections}')
    if projection == '2d':
        return

    from io import BytesIO
    from matplotlib import __version__ as mpl_version
    from mpl_toolkits.mplot3d import Axes3D

    fig = Figure()
    ax = Axes3D(fig)

    circles = PatchCollection([Circle((5, 1)), Circle((2, 2))])
    ax.add_collection3d(circles, zs=[1, 2])

    buf = BytesIO()
    try:
        fig.savefig(buf)
    except ValueError as e:
        if not 'operands could not be broadcast together' in str(e):
            raise e
        raise ValueError(
            'There is a known error with matplotlib 3d plotting, '
            f'and your version ({mpl_version}) seems to be affected. '
            'Please install matplotlib==3.0.2 or wait for '
            'https://github.com/matplotlib/matplotlib/issues/14298'
        ) 
Example 26
Project: neural-network-animation   Author: miloharper   File: figure.py    License: MIT License 5 votes vote down vote up
def __setstate__(self, state):
        version = state.pop('__mpl_version__')
        restore_to_pylab = state.pop('_restore_to_pylab', False)

        if version != _mpl_version:
            import warnings
            warnings.warn("This figure was saved with matplotlib version %s "
                          "and is unlikely to function correctly." %
                          (version, ))

        self.__dict__ = state

        # re-initialise some of the unstored state information
        self._axobservers = []
        self.canvas = None

        if restore_to_pylab:
            # lazy import to avoid circularity
            import matplotlib.pyplot as plt
            import matplotlib._pylab_helpers as pylab_helpers
            allnums = plt.get_fignums()
            num = max(allnums) + 1 if allnums else 1
            mgr = plt._backend_mod.new_figure_manager_given_figure(num, self)

            # XXX The following is a copy and paste from pyplot. Consider
            # factoring to pylab_helpers

            if self.get_label():
                mgr.set_window_title(self.get_label())

            # make this figure current on button press event
            def make_active(event):
                pylab_helpers.Gcf.set_active(mgr)

            mgr._cidgcf = mgr.canvas.mpl_connect('button_press_event',
                                                 make_active)

            pylab_helpers.Gcf.set_active(mgr)
            self.number = num

            plt.draw_if_interactive() 
Example 27
Project: oggm   Author: OGGM   File: conf.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def write_index():
    """This is to write the docs for the index automatically."""

    here = os.path.dirname(__file__)
    filename = os.path.join(here, '_generated', 'version_text.txt')

    try:
        os.makedirs(os.path.dirname(filename))
    except FileExistsError:
        pass

    text = text_version if '+' not in oggm.__version__ else text_dev

    with open(filename, 'w') as f:
        f.write(text) 
Example 28
Project: GraphicDesignPatternByPython   Author: Relph1119   File: figure.py    License: MIT License 5 votes vote down vote up
def __getstate__(self):
        state = super().__getstate__()

        # the axobservers cannot currently be pickled.
        # Additionally, the canvas cannot currently be pickled, but this has
        # the benefit of meaning that a figure can be detached from one canvas,
        # and re-attached to another.
        for attr_to_pop in ('_axobservers', 'show',
                            'canvas', '_cachedRenderer'):
            state.pop(attr_to_pop, None)

        # add version information to the state
        state['__mpl_version__'] = _mpl_version

        # check whether the figure manager (if any) is registered with pyplot
        from matplotlib import _pylab_helpers
        if getattr(self.canvas, 'manager', None) \
                in _pylab_helpers.Gcf.figs.values():
            state['_restore_to_pylab'] = True

        # set all the layoutbox information to None.  kiwisolver objects can't
        # be pickled, so we lose the layout options at this point.
        state.pop('_layoutbox', None)
        # suptitle:
        if self._suptitle is not None:
            self._suptitle._layoutbox = None

        return state 
Example 29
Project: python3_ios   Author: holzschu   File: figure.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __getstate__(self):
        state = super().__getstate__()

        # the axobservers cannot currently be pickled.
        # Additionally, the canvas cannot currently be pickled, but this has
        # the benefit of meaning that a figure can be detached from one canvas,
        # and re-attached to another.
        for attr_to_pop in ('_axobservers', 'show',
                            'canvas', '_cachedRenderer'):
            state.pop(attr_to_pop, None)

        # add version information to the state
        state['__mpl_version__'] = _mpl_version

        # check whether the figure manager (if any) is registered with pyplot
        from matplotlib import _pylab_helpers
        if getattr(self.canvas, 'manager', None) \
                in _pylab_helpers.Gcf.figs.values():
            state['_restore_to_pylab'] = True

        # set all the layoutbox information to None.  kiwisolver objects can't
        # be pickled, so we lose the layout options at this point.
        state.pop('_layoutbox', None)
        # suptitle:
        if self._suptitle is not None:
            self._suptitle._layoutbox = None

        return state 
Example 30
Project: beat   Author: hvasbath   File: plotting.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_matplotlib_version():
    from matplotlib import __version__ as mplversion
    return float(mplversion[0]), float(mplversion[2:])