本文整理汇总了Python中matplotlib.cbook._setattr_cm函数的典型用法代码示例。如果您正苦于以下问题:Python _setattr_cm函数的具体用法?Python _setattr_cm怎么用?Python _setattr_cm使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了_setattr_cm函数的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_code
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
示例2: draw
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()
示例3: print_png
def print_png(self, filename_or_obj, *args, **kwargs):
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)
示例4: test_tilde_in_tempfilename
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(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 ~
mpl.rcParams['text.usetex'] = True
plt.plot([1, 2, 3, 4])
plt.xlabel(r'\textbf{time} (s)')
# use the PS backend to write the file...
plt.savefig(base_tempdir / 'tex_demo.eps', format="ps")
示例5: mpl_image_comparison_parameters
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.node.get_closest_marker('baseline_images').args
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
示例6: wrapper
def wrapper(self, **kwargs):
with cbook._setattr_cm(QtWidgets.QWidget,
__init__=cooperative_qwidget_init):
__init__(self, **kwargs)
示例7: print_png
def print_png(self, filename_or_obj, *args,
metadata=None, pil_kwargs=None,
**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
pil_kwargs : dict, optional
If set to a non-None value, use Pillow to save the figure instead
of Matplotlib's builtin PNG support, and pass these keyword
arguments to `PIL.Image.save`.
If the 'pnginfo' key is present, it completely overrides
*metadata*, including the default 'Software' key.
"""
from matplotlib import _png
if metadata is None:
metadata = {}
metadata = {
"Software":
f"matplotlib version{__version__}, http://matplotlib.org/",
**metadata,
}
if pil_kwargs is not None:
from PIL import Image
from PIL.PngImagePlugin import PngInfo
buf, size = self.print_to_buffer()
# Only use the metadata kwarg if pnginfo is not set, because the
# semantics of duplicate keys in pnginfo is unclear.
if "pnginfo" not in pil_kwargs:
pnginfo = PngInfo()
for k, v in metadata.items():
pnginfo.add_text(k, v)
pil_kwargs["pnginfo"] = pnginfo
pil_kwargs.setdefault("dpi", (self.figure.dpi, self.figure.dpi))
(Image.frombuffer("RGBA", size, buf, "raw", "RGBA", 0, 1)
.save(filename_or_obj, format="png", **pil_kwargs))
else:
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:
_png.write_png(renderer._renderer, fh,
self.figure.dpi, metadata=metadata)