本文整理汇总了Python中matplotlib.cbook._warn_external函数的典型用法代码示例。如果您正苦于以下问题:Python _warn_external函数的具体用法?Python _warn_external怎么用?Python _warn_external使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了_warn_external函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, toolmanager, name):
cbook._warn_external(
'The new Tool classes introduced in v1.5 are experimental; their '
'API (including names) will likely change in future versions.')
self._name = name
self._toolmanager = toolmanager
self._figure = None
示例2: __init__
def __init__(self, figure, fh, dummy=False):
"""
Creates a new PGF renderer that translates any drawing instruction
into text commands to be interpreted in a latex pgfpicture environment.
Attributes
----------
figure : `matplotlib.figure.Figure`
Matplotlib figure to initialize height, width and dpi from.
fh : file-like
File handle for the output of the drawing commands.
"""
RendererBase.__init__(self)
self.dpi = figure.dpi
self.fh = fh
self.figure = figure
self.image_counter = 0
# get LatexManager instance
self.latexManager = LatexManager._get_cached_or_new()
if dummy:
# dummy==True deactivate all methods
for m in RendererPgf.__dict__:
if m.startswith("draw_"):
self.__dict__[m] = lambda *args, **kwargs: None
else:
# if fh does not belong to a filename, deactivate draw_image
if not hasattr(fh, 'name') or not os.path.exists(fh.name):
cbook._warn_external("streamed pgf-code does not support "
"raster graphics, consider using the "
"pgf-to-pdf option", UserWarning)
self.__dict__["draw_image"] = lambda *args, **kwargs: None
示例3: tight_layout
def tight_layout(self, figure, renderer=None,
pad=1.08, h_pad=None, w_pad=None, rect=None):
"""
Adjust subplot parameters to give specified padding.
Parameters
----------
pad : float
Padding between the figure edge and the edges of subplots, as a
fraction of the font-size.
h_pad, w_pad : float, optional
Padding (height/width) between edges of adjacent subplots.
Defaults to ``pad_inches``.
rect : tuple of 4 floats, optional
(left, bottom, right, top) rectangle in normalized figure
coordinates that the whole subplots area (including labels) will
fit into. Default is (0, 0, 1, 1).
"""
subplotspec_list = tight_layout.get_subplotspec_list(
figure.axes, grid_spec=self)
if None in subplotspec_list:
cbook._warn_external("This figure includes Axes that are not "
"compatible with tight_layout, so results "
"might be incorrect.")
if renderer is None:
renderer = tight_layout.get_renderer(figure)
kwargs = tight_layout.get_tight_layout_figure(
figure, figure.axes, subplotspec_list, renderer,
pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
if kwargs:
self.update(**kwargs)
示例4: test_warn_external_frame_embedded_python
def test_warn_external_frame_embedded_python():
with patch.object(cbook, "sys") as mock_sys:
mock_sys._getframe = Mock(return_value=None)
with warnings.catch_warnings(record=True) as w:
cbook._warn_external("dummy")
assert len(w) == 1
assert str(w[0].message) == "dummy"
示例5: to_qcolor
def to_qcolor(color):
"""Create a QColor from a matplotlib color"""
qcolor = QtGui.QColor()
try:
rgba = mcolors.to_rgba(color)
except ValueError:
cbook._warn_external('Ignoring invalid color %r' % color)
return qcolor # return invalid QColor
qcolor.setRgbF(*rgba)
return qcolor
示例6: add_tool
def add_tool(self, name, tool, *args, **kwargs):
"""
Add *tool* to `ToolManager`.
If successful, adds a new event ``tool_trigger_{name}`` where
``{name}`` is the *name* of the tool; the event is fired everytime the
tool is triggered.
Parameters
----------
name : str
Name of the tool, treated as the ID, has to be unique.
tool : class_like, i.e. str or type
Reference to find the class of the Tool to added.
Notes
-----
args and kwargs get passed directly to the tools constructor.
See Also
--------
matplotlib.backend_tools.ToolBase : The base class for tools.
"""
tool_cls = self._get_cls_to_instantiate(tool)
if not tool_cls:
raise ValueError('Impossible to find class for %s' % str(tool))
if name in self._tools:
cbook._warn_external('A "Tool class" with the same name already '
'exists, not added')
return self._tools[name]
tool_obj = tool_cls(self, name, *args, **kwargs)
self._tools[name] = tool_obj
if tool_cls.default_keymap is not None:
self.update_keymap(name, tool_cls.default_keymap)
# For toggle tools init the radio_group in self._toggled
if isinstance(tool_obj, tools.ToolToggleBase):
# None group is not mutually exclusive, a set is used to keep track
# of all toggled tools in this group
if tool_obj.radio_group is None:
self._toggled.setdefault(None, set())
else:
self._toggled.setdefault(tool_obj.radio_group, None)
# If initially toggled
if tool_obj.toggled:
self._handle_toggle(tool_obj, None, None, None)
tool_obj.set_figure(self.figure)
self._tool_added_event(tool_obj)
return tool_obj
示例7: _remove_blacklisted_style_params
def _remove_blacklisted_style_params(d, warn=True):
o = {}
for key, val in d.items():
if key in STYLE_BLACKLIST:
if warn:
cbook._warn_external(
"Style includes a parameter, '{0}', that is not related "
"to style. Ignoring".format(key))
else:
o[key] = val
return o
示例8: _parse_legend_args
def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs):
"""
Get the handles and labels from the calls to either ``figure.legend``
or ``axes.legend``.
``axs`` is a list of axes (to get legend artists from)
"""
log = logging.getLogger(__name__)
handlers = kwargs.get('handler_map', {}) or {}
extra_args = ()
if (handles is not None or labels is not None) and args:
cbook._warn_external("You have mixed positional and keyword "
"arguments, some input may be discarded.")
# if got both handles and labels as kwargs, make same length
if handles and labels:
handles, labels = zip(*zip(handles, labels))
elif handles is not None and labels is None:
labels = [handle.get_label() for handle in handles]
elif labels is not None and handles is None:
# Get as many handles as there are labels.
handles = [handle for handle, label
in zip(_get_legend_handles(axs, handlers), labels)]
# No arguments - automatically detect labels and handles.
elif len(args) == 0:
handles, labels = _get_legend_handles_labels(axs, handlers)
if not handles:
log.warning('No handles with labels found to put in legend.')
# One argument. User defined labels - automatic handle detection.
elif len(args) == 1:
labels, = args
# Get as many handles as there are labels.
handles = [handle for handle, label
in zip(_get_legend_handles(axs, handlers), labels)]
# Two arguments:
# * user defined handles and labels
elif len(args) >= 2:
handles, labels = args[:2]
extra_args = args[2:]
else:
raise TypeError('Invalid arguments to legend.')
return handles, labels, extra_args, kwargs
示例9: get_renderer
def get_renderer(fig):
if fig._cachedRenderer:
renderer = fig._cachedRenderer
else:
canvas = fig.canvas
if canvas and hasattr(canvas, "get_renderer"):
renderer = canvas.get_renderer()
else:
# not sure if this can happen
cbook._warn_external("tight_layout : falling back to Agg renderer")
from matplotlib.backends.backend_agg import FigureCanvasAgg
canvas = FigureCanvasAgg(fig)
renderer = canvas.get_renderer()
return renderer
示例10: latex2png
def latex2png(latex, filename, fontset='cm'):
latex = "$%s$" % latex
orig_fontset = rcParams['mathtext.fontset']
rcParams['mathtext.fontset'] = fontset
if os.path.exists(filename):
depth = mathtext_parser.get_depth(latex, dpi=100)
else:
try:
depth = mathtext_parser.to_png(filename, latex, dpi=100)
except Exception:
cbook._warn_external("Could not render math expression %s" % latex,
Warning)
depth = 0
rcParams['mathtext.fontset'] = orig_fontset
sys.stdout.write("#")
sys.stdout.flush()
return depth
示例11: new_floating_axis
def new_floating_axis(self, nth_coord, value,
axis_direction="bottom",
axes=None,
):
if axes is None:
cbook._warn_external(
"'new_floating_axis' explicitly requires the axes keyword.")
axes = self.axes
_helper = AxisArtistHelperRectlinear.Floating(
axes, nth_coord, value, axis_direction)
axisline = AxisArtist(axes, _helper)
axisline.line.set_clip_on(True)
axisline.line.set_clip_box(axisline.axes.bbox)
return axisline
示例12: _find_best_position
def _find_best_position(self, width, height, renderer, consider=None):
"""
Determine the best location to place the legend.
*consider* is a list of ``(x, y)`` pairs to consider as a potential
lower-left corner of the legend. All are display coords.
"""
# should always hold because function is only called internally
assert self.isaxes
verts, bboxes, lines, offsets = self._auto_legend_data()
if self._loc_used_default and verts.shape[0] > 200000:
# this size results in a 3+ second render time on a good machine
cbook._warn_external(
'Creating legend with loc="best" can be slow with large '
'amounts of data.'
)
bbox = Bbox.from_bounds(0, 0, width, height)
if consider is None:
consider = [self._get_anchored_bbox(x, bbox,
self.get_bbox_to_anchor(),
renderer)
for x in range(1, len(self.codes))]
candidates = []
for idx, (l, b) in enumerate(consider):
legendBox = Bbox.from_bounds(l, b, width, height)
badness = 0
# XXX TODO: If markers are present, it would be good to
# take them into account when checking vertex overlaps in
# the next line.
badness = (legendBox.count_contains(verts)
+ legendBox.count_contains(offsets)
+ legendBox.count_overlaps(bboxes)
+ sum(line.intersects_bbox(legendBox, filled=False)
for line in lines))
if badness == 0:
return l, b
# Include the index to favor lower codes in case of a tie.
candidates.append((badness, idx, (l, b)))
_, _, (l, b) = min(candidates)
return l, b
示例13: get_tool
def get_tool(self, name, warn=True):
"""
Return the tool object, also accepts the actual tool for convenience.
Parameters
----------
name : str, ToolBase
Name of the tool, or the tool itself
warn : bool, optional
If this method should give warnings.
"""
if isinstance(name, tools.ToolBase) and name.name in self._tools:
return name
if name not in self._tools:
if warn:
cbook._warn_external("ToolManager does not control tool "
"%s" % name)
return None
return self._tools[name]
示例14: new_fixed_axis
def new_fixed_axis(self, loc,
nth_coord=None,
axis_direction=None,
offset=None,
axes=None,
):
if axes is None:
cbook._warn_external(
"'new_fixed_axis' explicitly requires the axes keyword.")
axes = self.axes
_helper = AxisArtistHelperRectlinear.Fixed(axes, loc, nth_coord)
if axis_direction is None:
axis_direction = loc
axisline = AxisArtist(axes, _helper, offset=offset,
axis_direction=axis_direction,
)
return axisline
示例15: update_keymap
def update_keymap(self, name, *keys):
"""
Set the keymap to associate with the specified tool.
Parameters
----------
name : string
Name of the Tool
keys : keys to associate with the Tool
"""
if name not in self._tools:
raise KeyError('%s not in Tools' % name)
self._remove_keys(name)
for key in keys:
for k in validate_stringlist(key):
if k in self._keys:
cbook._warn_external('Key %s changed from %s to %s' %
(k, self._keys[k], name))
self._keys[k] = name