本文整理汇总了Python中matplotlib.cbook._setattr_cm方法的典型用法代码示例。如果您正苦于以下问题:Python cbook._setattr_cm方法的具体用法?Python cbook._setattr_cm怎么用?Python cbook._setattr_cm使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.cbook
的用法示例。
在下文中一共展示了cbook._setattr_cm方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: mpl_image_comparison_parameters
# 需要导入模块: from matplotlib import cbook [as 别名]
# 或者: from matplotlib.cbook import _setattr_cm [as 别名]
def mpl_image_comparison_parameters(request, extension):
# This fixture is applied automatically by the image_comparison decorator.
#
# The sole purpose of this fixture is to provide an indirect method of
# obtaining parameters *without* modifying the decorated function
# signature. In this way, the function signature can stay the same and
# pytest won't get confused.
# We annotate the decorated function with any parameters captured by this
# fixture so that they can be used by the wrapper in image_comparison.
baseline_images = request.keywords['baseline_images'].args[0]
if baseline_images is None:
# Allow baseline image list to be produced on the fly based on current
# parametrization.
baseline_images = request.getfixturevalue('baseline_images')
func = request.function
with cbook._setattr_cm(func.__wrapped__,
parameters=(baseline_images, extension)):
yield
示例2: test_tilde_in_tempfilename
# 需要导入模块: from matplotlib import cbook [as 别名]
# 或者: from matplotlib.cbook import _setattr_cm [as 别名]
def test_tilde_in_tempfilename(tmpdir):
# Tilde ~ in the tempdir path (e.g. TMPDIR, TMP or TEMP on windows
# when the username is very long and windows uses a short name) breaks
# latex before https://github.com/matplotlib/matplotlib/pull/5928
base_tempdir = Path(str(tmpdir), "short-1")
base_tempdir.mkdir()
# Change the path for new tempdirs, which is used internally by the ps
# backend to write a file.
with cbook._setattr_cm(tempfile, tempdir=str(base_tempdir)):
# usetex results in the latex call, which does not like the ~
plt.rc('text', usetex=True)
plt.plot([1, 2, 3, 4])
plt.xlabel(r'\textbf{time} (s)')
output_eps = os.path.join(str(base_tempdir), 'tex_demo.eps')
# use the PS backend to write the file...
plt.savefig(output_eps, format="ps")
示例3: print_raw
# 需要导入模块: from matplotlib import cbook [as 别名]
# 或者: from matplotlib.cbook import _setattr_cm [as 别名]
def print_raw(self, filename_or_obj, *args, **kwargs):
FigureCanvasAgg.draw(self)
renderer = self.get_renderer()
with cbook._setattr_cm(renderer, dpi=self.figure.dpi), \
cbook.open_file_cm(filename_or_obj, "wb") as fh:
fh.write(renderer._renderer.buffer_rgba())
示例4: print_to_buffer
# 需要导入模块: from matplotlib import cbook [as 别名]
# 或者: from matplotlib.cbook import _setattr_cm [as 别名]
def print_to_buffer(self):
FigureCanvasAgg.draw(self)
renderer = self.get_renderer()
with cbook._setattr_cm(renderer, dpi=self.figure.dpi):
return (renderer._renderer.buffer_rgba(),
(int(renderer.width), int(renderer.height)))
示例5: _allow_super_init
# 需要导入模块: from matplotlib import cbook [as 别名]
# 或者: from matplotlib.cbook import _setattr_cm [as 别名]
def _allow_super_init(__init__):
"""
Decorator for ``__init__`` to allow ``super().__init__`` on PyQt4/PySide2.
"""
if QT_API == "PyQt5":
return __init__
else:
# To work around lack of cooperative inheritance in PyQt4, PySide,
# and PySide2, when calling FigureCanvasQT.__init__, we temporarily
# patch QWidget.__init__ by a cooperative version, that first calls
# QWidget.__init__ with no additional arguments, and then finds the
# next class in the MRO with an __init__ that does support cooperative
# inheritance (i.e., not defined by the PyQt4, PySide, PySide2, sip
# or Shiboken packages), and manually call its `__init__`, once again
# passing the additional arguments.
qwidget_init = QtWidgets.QWidget.__init__
def cooperative_qwidget_init(self, *args, **kwargs):
qwidget_init(self)
mro = type(self).__mro__
next_coop_init = next(
cls for cls in mro[mro.index(QtWidgets.QWidget) + 1:]
if cls.__module__.split(".")[0] not in [
"PyQt4", "sip", "PySide", "PySide2", "Shiboken"])
next_coop_init.__init__(self, *args, **kwargs)
@functools.wraps(__init__)
def wrapper(self, *args, **kwargs):
with cbook._setattr_cm(QtWidgets.QWidget,
__init__=cooperative_qwidget_init):
__init__(self, *args, **kwargs)
return wrapper
示例6: draw
# 需要导入模块: from matplotlib import cbook [as 别名]
# 或者: from matplotlib.cbook import _setattr_cm [as 别名]
def draw(self):
"""Render the figure, and queue a request for a Qt draw.
"""
# The renderer draw is done here; delaying causes problems with code
# that uses the result of the draw() to update plot elements.
if self._is_drawing:
return
with cbook._setattr_cm(self, _is_drawing=True):
super().draw()
self.update()
示例7: run_code
# 需要导入模块: from matplotlib import cbook [as 别名]
# 或者: from matplotlib.cbook import _setattr_cm [as 别名]
def run_code(code, code_path, ns=None, function_name=None):
"""
Import a Python module from a path, and run the function given by
name, if function_name is not None.
"""
# Change the working directory to the directory of the example, so
# it can get at its data files, if any. Add its path to sys.path
# so it can import any helper modules sitting beside it.
pwd = os.getcwd()
if setup.config.plot_working_directory is not None:
try:
os.chdir(setup.config.plot_working_directory)
except OSError as err:
raise OSError(str(err) + '\n`plot_working_directory` option in'
'Sphinx configuration file must be a valid '
'directory path')
except TypeError as err:
raise TypeError(str(err) + '\n`plot_working_directory` option in '
'Sphinx configuration file must be a string or '
'None')
elif code_path is not None:
dirname = os.path.abspath(os.path.dirname(code_path))
os.chdir(dirname)
with cbook._setattr_cm(
sys, argv=[code_path], path=[os.getcwd(), *sys.path]), \
contextlib.redirect_stdout(StringIO()):
try:
code = unescape_doctest(code)
if ns is None:
ns = {}
if not ns:
if setup.config.plot_pre_code is None:
exec('import numpy as np\n'
'from matplotlib import pyplot as plt\n', ns)
else:
exec(str(setup.config.plot_pre_code), ns)
if "__main__" in code:
ns['__name__'] = '__main__'
# Patch out non-interactive show() to avoid triggering a warning.
with cbook._setattr_cm(FigureManagerBase, show=lambda self: None):
exec(code, ns)
if function_name is not None:
exec(function_name + "()", ns)
except (Exception, SystemExit) as err:
raise PlotError(traceback.format_exc())
finally:
os.chdir(pwd)
return ns
示例8: print_png
# 需要导入模块: from matplotlib import cbook [as 别名]
# 或者: from matplotlib.cbook import _setattr_cm [as 别名]
def print_png(self, filename_or_obj, *args, **kwargs):
"""
Write the figure to a PNG file.
Parameters
----------
filename_or_obj : str or PathLike or file-like object
The file to write to.
metadata : dict, optional
Metadata in the PNG file as key-value pairs of bytes or latin-1
encodable strings.
According to the PNG specification, keys must be shorter than 79
chars.
The `PNG specification`_ defines some common keywords that may be
used as appropriate:
- Title: Short (one line) title or caption for image.
- Author: Name of image's creator.
- Description: Description of image (possibly long).
- Copyright: Copyright notice.
- Creation Time: Time of original image creation
(usually RFC 1123 format).
- Software: Software used to create the image.
- Disclaimer: Legal disclaimer.
- Warning: Warning of nature of content.
- Source: Device used to create the image.
- Comment: Miscellaneous comment;
conversion from other image format.
Other keywords may be invented for other purposes.
If 'Software' is not given, an autogenerated value for matplotlib
will be used.
For more details see the `PNG specification`_.
.. _PNG specification: \
https://www.w3.org/TR/2003/REC-PNG-20031110/#11keywords
"""
FigureCanvasAgg.draw(self)
renderer = self.get_renderer()
version_str = (
'matplotlib version ' + __version__ + ', http://matplotlib.org/')
metadata = OrderedDict({'Software': version_str})
user_metadata = kwargs.pop("metadata", None)
if user_metadata is not None:
metadata.update(user_metadata)
with cbook._setattr_cm(renderer, dpi=self.figure.dpi), \
cbook.open_file_cm(filename_or_obj, "wb") as fh:
_png.write_png(renderer._renderer, fh,
self.figure.dpi, metadata=metadata)