def show(*args, block=None, **kwargs): if args or kwargs: cbook.warn_deprecated( "3.1", message="Passing arguments to show(), other than " "passing 'block' by keyword, is deprecated %(since)s, and " "support for it will be removed %(removal)s.") ## TODO: something to do when keyword block==False ? from matplotlib._pylab_helpers import Gcf managers = Gcf.get_all_fig_managers() if not managers: return interactive = is_interactive() for manager in managers: manager.show() # plt.figure adds an event which puts the figure in focus # in the activeQue. Disable this behaviour, as it results in # figures being put as the active figure after they have been # shown, even in non-interactive mode. if hasattr(manager, '_cidgcf'): manager.canvas.mpl_disconnect(manager._cidgcf) if not interactive and manager in Gcf._activeQue: Gcf._activeQue.remove(manager)
def draggable(self, state=None, use_blit=False, update="loc"): """ Set the draggable state -- if state is * None : toggle the current state * True : turn draggable on * False : turn draggable off If draggable is on, you can drag the legend on the canvas with the mouse. The `.DraggableLegend` helper instance is returned if draggable is on. The update parameter control which parameter of the legend changes when dragged. If update is "loc", the *loc* parameter of the legend is changed. If "bbox", the *bbox_to_anchor* parameter is changed. """ warn_deprecated("2.2", message="Legend.draggable() is drepecated in " "favor of Legend.set_draggable(). " "Legend.draggable may be reintroduced as a " "property in future releases.") if state is None: state = not self.get_draggable() # toggle state self.set_draggable(state, use_blit, update) return self._draggable
def remove_coding(text): r""" Remove the coding comment, which six.exec\_ doesn't like. """ cbook.warn_deprecated('3.0', name='remove_coding', removal='3.1') sub_re = re.compile("^#\s*-\*-\s*coding:\s*.*-\*-$", flags=re.MULTILINE) return sub_re.sub("", text)
def _deprecate_factor_none(factor): # After the deprecation period, calls to _deprecate_factor_none can just be # removed. if factor is None: cbook.warn_deprecated( "3.2", "factor=None is deprecated; use/return factor=1 instead") factor = 1 return factor
def __init__(self, figure): FigureCanvasBase.__init__(self, figure) if self.__class__ == matplotlib.backends.backend_gdk.FigureCanvasGDK: warn_deprecated('2.0', message="The GDK backend is " "deprecated. It is untested, known to be " "broken and will be removed in Matplotlib 2.2. " "Use the Agg backend instead. " "See Matplotlib usage FAQ for" " more info on backends.", alternative="Agg") self._renderer_init()
def new_horizontal(self, size, pad=None, pack_start=False, **kwargs): """ Add a new axes on the right (or left) side of the main axes. Parameters ---------- size : :mod:`~mpl_toolkits.axes_grid.axes_size` or float or string A width of the axes. If float or string is given, *from_any* function is used to create the size, with *ref_size* set to AxesX instance of the current axes. pad : :mod:`~mpl_toolkits.axes_grid.axes_size` or float or string Pad between the axes. It takes same argument as *size*. pack_start : bool If False, the new axes is appended at the end of the list, i.e., it became the right-most axes. If True, it is inserted at the start of the list, and becomes the left-most axes. **kwargs All extra keywords arguments are passed to the created axes. If *axes_class* is given, the new axes will be created as an instance of the given class. Otherwise, the same class of the main axes will be used. """ if pad is None: cbook.warn_deprecated( "3.2", message="In a future version, 'pad' will default to " "rcParams['figure.subplot.wspace']. Set pad=0 to keep the " "old behavior.") if pad: if not isinstance(pad, Size._Base): pad = Size.from_any(pad, fraction_ref=self._xref) if pack_start: self._horizontal.insert(0, pad) self._xrefindex += 1 else: self._horizontal.append(pad) if not isinstance(size, Size._Base): size = Size.from_any(size, fraction_ref=self._xref) if pack_start: self._horizontal.insert(0, size) self._xrefindex += 1 locator = self.new_locator(nx=0, ny=self._yrefindex) else: self._horizontal.append(size) locator = self.new_locator( nx=len(self._horizontal) - 1, ny=self._yrefindex) ax = self._get_new_axes(**kwargs) ax.set_axes_locator(locator) return ax
def resize(self, width, height=None): # before 09-12-22, the resize method takes a single *event* # parameter. On the other hand, the resize method of other # FigureManager class takes *width* and *height* parameter, # which is used to change the size of the window. For the # Figure.set_size_inches with forward=True work with Tk # backend, I changed the function signature but tried to keep # it backward compatible. -JJL # when a single parameter is given, consider it as a event if height is None: cbook.warn_deprecated("2.2", "FigureManagerTkAgg.resize now takes " "width and height as separate arguments") width = width.width else: self.canvas._tkcanvas.master.geometry("%dx%d" % (width, height)) if self.toolbar is not None: self.toolbar.configure(width=width)
def set_zsort(self, zsort): """ Sets the calculation method for the z-order. Parameters ---------- zsort : {'average', 'min', 'max'} The function applied on the z-coordinates of the vertices in the viewer's coordinate system, to determine the z-order. *True* is deprecated and equivalent to 'average'. """ if zsort is True: cbook.warn_deprecated( "3.1", message="Passing True to mean 'average' for set_zsort " "is deprecated and support will be removed in Matplotlib 3.3; " "pass 'average' instead.") zsort = 'average' self._zsortfunc = self._zsort_functions[zsort] self._sort_zpos = None self.stale = True
def _scale_norm(self, norm, vmin, vmax): """ Helper for initial scaling. Used by public functions that create a ScalarMappable and support parameters *vmin*, *vmax* and *norm*. This makes sure that a *norm* will take precedence over *vmin*, *vmax*. Note that this method does not set the norm. """ if vmin is not None or vmax is not None: self.set_clim(vmin, vmax) if norm is not None: cbook.warn_deprecated( "3.3", message="Passing parameters norm and vmin/vmax " "simultaneously is deprecated. Please pass " "vmin/vmax directly to the norm when creating it.") else: self.autoscale_None()
def get_subplot_params(self, figure=None, fig=None): """ Return a dictionary of subplot layout parameters. The default parameters are from rcParams unless a figure attribute is set. """ if fig is not None: cbook.warn_deprecated("2.2", "fig", obj_type="keyword argument", alternative="figure") if figure is None: figure = fig if figure is None: kw = {k: rcParams["figure.subplot."+k] for k in self._AllowedKeys} subplotpars = mpl.figure.SubplotParams(**kw) else: subplotpars = copy.copy(figure.subplotpars) subplotpars.update(**{k: getattr(self, k) for k in self._AllowedKeys}) return subplotpars
def __init__(self, axis, **kwargs): r""" Construct a new scale. Notes ----- The following note is for scale implementors. For back-compatibility reasons, scales take an `~matplotlib.axis.Axis` object as first argument. However, this argument should not be used: a single scale object should be usable by multiple `~matplotlib.axis.Axis`\es at the same time. """ if kwargs: warn_deprecated( '3.2', removal='3.4', message=(f"ScaleBase got an unexpected keyword argument " f"{next(iter(kwargs))!r}. This will become an error " "%(removal)s."))
def resize(self, width, height=None): # before 09-12-22, the resize method takes a single *event* # parameter. On the other hand, the resize method of other # FigureManager class takes *width* and *height* parameter, # which is used to change the size of the window. For the # Figure.set_size_inches with forward=True work with Tk # backend, I changed the function signature but tried to keep # it backward compatible. -JJL # when a single parameter is given, consider it as a event if height is None: cbook.warn_deprecated( "2.2", "FigureManagerTkAgg.resize now takes " "width and height as separate arguments") width = width.width else: self.canvas._tkcanvas.master.geometry("%dx%d" % (width, height)) if self.toolbar is not None: self.toolbar.configure(width=width)
def set_zsort(self, zsort): """ Sets the calculation method for the z-order. Parameters ---------- zsort : {'average', 'min', 'max'} The function applied on the z-coordinates of the vertices in the viewer's coordinate system, to determine the z-order. *True* is deprecated and equivalent to 'average'. """ if zsort is True: cbook.warn_deprecated( "3.1", "Passing True to mean 'average' for set_zsort is " "deprecated and support will be removed in Matplotlib 3.3; " "pass 'average' instead.") zsort = 'average' self._zsortfunc = self._zsort_functions[zsort] self._sort_zpos = None self.stale = True
def colorbar(self, mappable, *, ticks=None, **kwargs): if self.orientation in ["top", "bottom"]: orientation = "horizontal" else: orientation = "vertical" if mpl.rcParams["mpl_toolkits.legacy_colorbar"]: cbook.warn_deprecated( "3.2", message="Since %(since)s, mpl_toolkits's own colorbar " "implementation is deprecated; it will be removed " "%(removal)s. Set the 'mpl_toolkits.legacy_colorbar' rcParam " "to False to use Matplotlib's default colorbar implementation " "and suppress this deprecation warning.") if ticks is None: ticks = ticker.MaxNLocator(5) # For backcompat. from .colorbar import Colorbar else: from matplotlib.colorbar import Colorbar cb = Colorbar(self, mappable, orientation=orientation, ticks=ticks, **kwargs) self._config_axes() def on_changed(m): cb.set_cmap(m.get_cmap()) cb.set_clim(m.get_clim()) cb.update_bruteforce(m) self.cbid = mappable.callbacksSM.connect('changed', on_changed) mappable.colorbar = cb if mpl.rcParams["mpl_toolkits.legacy_colorbar"]: self.locator = cb.cbar_axis.get_major_locator() else: self.locator = cb.locator return cb
def __init__(self, figure): if self.__class__ == matplotlib.backends.backend_gtk.FigureCanvasGTK: warn_deprecated( "2.0", message="The GTK backend is " "deprecated. It is untested, known to be " "broken and will be removed in Matplotlib 2.2. " "Use the GTKAgg backend instead. " "See Matplotlib usage FAQ for" " more info on backends.", alternative="GTKAgg", ) if _debug: print("FigureCanvasGTK.%s" % fn_name()) FigureCanvasBase.__init__(self, figure) gtk.DrawingArea.__init__(self) self._idle_draw_id = 0 self._need_redraw = True self._pixmap_width = -1 self._pixmap_height = -1 self._lastCursor = None self.connect("scroll_event", self.scroll_event) self.connect("button_press_event", self.button_press_event) self.connect("button_release_event", self.button_release_event) self.connect("configure_event", self.configure_event) self.connect("expose_event", self.expose_event) self.connect("key_press_event", self.key_press_event) self.connect("key_release_event", self.key_release_event) self.connect("motion_notify_event", self.motion_notify_event) self.connect("leave_notify_event", self.leave_notify_event) self.connect("enter_notify_event", self.enter_notify_event) self.set_events(self.__class__.event_mask) self.set_double_buffered(False) self.set_flags(gtk.CAN_FOCUS) self._renderer_init() self.last_downclick = {}
def register_cmap(name=None, cmap=None, data=None, lut=None): """ Add a colormap to the set recognized by :func:`get_cmap`. It can be used in two ways:: register_cmap(name='swirly', cmap=swirly_cmap) register_cmap(name='choppy', data=choppydata, lut=128) In the first case, *cmap* must be a :class:`matplotlib.colors.Colormap` instance. The *name* is optional; if absent, the name will be the :attr:`~matplotlib.colors.Colormap.name` attribute of the *cmap*. The second case is deprecated. Here, the three arguments are passed to the :class:`~matplotlib.colors.LinearSegmentedColormap` initializer, and the resulting colormap is registered. Instead of this implicit colormap creation, create a `.LinearSegmentedColormap` and use the first case: ``register_cmap(cmap=LinearSegmentedColormap(name, data, lut))``. """ cbook._check_isinstance((str, None), name=name) if name is None: try: name = cmap.name except AttributeError: raise ValueError("Arguments must include a name or a Colormap") if isinstance(cmap, colors.Colormap): cmap_d[name] = cmap return if lut is not None or data is not None: cbook.warn_deprecated( "3.3", message="Passing raw data via parameters data and lut to " "register_cmap() is deprecated. Instead use: " "register_cmap(" "cmap=LinearSegmentedColormap(name, data, lut))") # For the remainder, let exceptions propagate. if lut is None: lut = mpl.rcParams['image.lut'] cmap = colors.LinearSegmentedColormap(name, data, lut) cmap_d[name] = cmap
def __init__(self, size=None, weight='normal'): self._version = self.__version__ self.__default_weight = weight self.default_size = size paths = [cbook._get_data_path('fonts', subdir) for subdir in ['ttf', 'afm', 'pdfcorefonts']] # Create list of font paths for pathname in ['TTFPATH', 'AFMPATH']: if pathname in os.environ: ttfpath = os.environ[pathname] if ttfpath.find(';') >= 0: # win32 style paths.extend(ttfpath.split(';')) elif ttfpath.find(':') >= 0: # unix style paths.extend(ttfpath.split(':')) else: paths.append(ttfpath) cbook.warn_deprecated( "3.3", name=pathname, obj_type="environment variable", alternative="FontManager.addfont()") _log.debug('font search path %s', str(paths)) # Load TrueType fonts and create font dictionary. self.defaultFamily = { 'ttf': 'DejaVu Sans', 'afm': 'Helvetica'} self.afmlist = [] self.ttflist = [] for fontext in ["afm", "ttf"]: for path in [*findSystemFonts(paths, fontext=fontext), *findSystemFonts(fontext=fontext)]: try: self.addfont(path) except OSError as exc: _log.info("Failed to open font file %s: %s", path, exc) except Exception as exc: _log.info("Failed to extract font properties from %s: %s", path, exc)
def _from_subplot_args(figure, args): """ Construct a `.SubplotSpec` from a parent `.Figure` and either - a `.SubplotSpec` -- returned as is; - one or three numbers -- a MATLAB-style subplot specifier. """ message = ("Passing non-integers as three-element position " "specification is deprecated since %(since)s and will be " "removed %(removal)s.") if len(args) == 1: arg, = args if isinstance(arg, SubplotSpec): return arg else: if not isinstance(arg, Integral): cbook.warn_deprecated("3.3", message=message) arg = str(arg) try: rows, cols, num = map(int, str(arg)) except ValueError: raise ValueError( f"Single argument to subplot must be a three-digit " f"integer, not {arg}") from None # num - 1 for converting from MATLAB to python indexing return GridSpec(rows, cols, figure=figure)[num - 1] elif len(args) == 3: rows, cols, num = args if not (isinstance(rows, Integral) and isinstance(cols, Integral)): cbook.warn_deprecated("3.3", message=message) rows, cols = map(int, [rows, cols]) gs = GridSpec(rows, cols, figure=figure) if isinstance(num, tuple) and len(num) == 2: if not all(isinstance(n, Integral) for n in num): cbook.warn_deprecated("3.3", message=message) i, j = map(int, num) else: i, j = num return gs[i-1:j] else: if not isinstance(num, Integral): cbook.warn_deprecated("3.3", message=message) num = int(num) if num < 1 or num > rows*cols: raise ValueError( f"num must be 1 <= num <= {rows*cols}, not {num}") return gs[num - 1] # -1 due to MATLAB indexing. else: raise TypeError(f"subplot() takes 1 or 3 positional arguments but " f"{len(args)} were given")
def get_subplot_params(self, figure=None, fig=None): """Return a dictionary of subplot layout parameters. """ if fig is not None: cbook.warn_deprecated("2.2", "fig", obj_type="keyword argument", alternative="figure") if figure is None: figure = fig hspace = (self._hspace if self._hspace is not None else figure.subplotpars.hspace if figure is not None else rcParams["figure.subplot.hspace"]) wspace = (self._wspace if self._wspace is not None else figure.subplotpars.wspace if figure is not None else rcParams["figure.subplot.wspace"]) figbox = self._subplot_spec.get_position(figure) left, bottom, right, top = figbox.extents return mpl.figure.SubplotParams(left=left, right=right, bottom=bottom, top=top, wspace=wspace, hspace=hspace)
def __init__(self, figure): if self.__class__ == matplotlib.backends.backend_gtk.FigureCanvasGTK: warn_deprecated('2.0', message="The GTK backend is " "deprecated. It is untested, known to be " "broken and will be removed in Matplotlib 2.2. " "Use the GTKAgg backend instead. " "See Matplotlib usage FAQ for" " more info on backends.", alternative="GTKAgg") if _debug: print('FigureCanvasGTK.%s' % fn_name()) FigureCanvasBase.__init__(self, figure) gtk.DrawingArea.__init__(self) self._idle_draw_id = 0 self._need_redraw = True self._pixmap_width = -1 self._pixmap_height = -1 self._lastCursor = None self.connect('scroll_event', self.scroll_event) self.connect('button_press_event', self.button_press_event) self.connect('button_release_event', self.button_release_event) self.connect('configure_event', self.configure_event) self.connect('expose_event', self.expose_event) self.connect('key_press_event', self.key_press_event) self.connect('key_release_event', self.key_release_event) self.connect('motion_notify_event', self.motion_notify_event) self.connect('leave_notify_event', self.leave_notify_event) self.connect('enter_notify_event', self.enter_notify_event) self.set_events(self.__class__.event_mask) self.set_double_buffered(False) self.set_flags(gtk.CAN_FOCUS) self._renderer_init() self.last_downclick = {}
def subplot_class_factory(axes_class=None): """ This makes a new class that inherits from `.SubplotBase` and the given axes_class (which is assumed to be a subclass of `.axes.Axes`). This is perhaps a little bit roundabout to make a new class on the fly like this, but it means that a new Subplot class does not have to be created for every type of Axes. """ if axes_class is None: cbook.warn_deprecated( "3.3", message="Support for passing None to subplot_class_factory " "is deprecated; explicitly pass the default Axes class instead.") axes_class = Axes try: # Avoid creating two different instances of GeoAxesSubplot... # Only a temporary backcompat fix. This should be removed in # 3.4 return next(cls for cls in SubplotBase.__subclasses__() if cls.__bases__ == (SubplotBase, axes_class)) except StopIteration: return type("%sSubplot" % axes_class.__name__, (SubplotBase, axes_class), {'_axes_class': axes_class})
def _scale_norm(self, norm, vmin, vmax): """ Helper for initial scaling. Used by public functions that create a ScalarMappable and support parameters *vmin*, *vmax* and *norm*. This makes sure that a *norm* will take precedence over *vmin*, *vmax*. Note that this method does not set the norm. """ if vmin is not None or vmax is not None: self.set_clim(vmin, vmax) if norm is not None: cbook.warn_deprecated( "3.3", message="Passing parameters norm and vmin/vmax " "simultaneously is deprecated since %(since)s and " "will become an error %(removal)s. Please pass " "vmin/vmax directly to the norm when creating it.") # always resolve the autoscaling so we have concrete limits # rather than deferring to draw time. self.autoscale_None()
def parse(self, s, dpi=72, prop=None, *, _force_standard_ps_fonts=False): """ Parse the given math expression *s* at the given *dpi*. If *prop* is provided, it is a `.FontProperties` object specifying the "default" font to use in the math expression, used for all non-math text. The results are cached, so multiple calls to `parse` with the same expression should be fast. """ if _force_standard_ps_fonts: cbook.warn_deprecated( "3.4", removal="3.5", message=( "Mathtext using only standard PostScript fonts has " "been likely to produce wrong output for a while, " "has been deprecated in %(since)s and will be removed " "in %(removal)s, after which ps.useafm will have no " "effect on mathtext.")) # lru_cache can't decorate parse() directly because the ps.useafm and # mathtext.fontset rcParams also affect the parse (e.g. by affecting # the glyph metrics). return self._parse_cached(s, dpi, prop, _force_standard_ps_fonts)
""" from __future__ import (absolute_import, division, print_function, unicode_literals) import six import copy import numpy as np import xlwt as excel import matplotlib.cbook as cbook import matplotlib.mlab as mlab cbook.warn_deprecated("2.0", name="mpl_toolkits.exceltools", alternative="openpyxl", obj_type="module") def xlformat_factory(format): """ copy the format, perform any overrides, and attach an xlstyle instance copied format is returned """ #if we have created an excel format already using this format, #don't recreate it; mlab.FormatObj override has to make objs with #the same props hash to the same value key = hash(format) fmt_ = xlformat_factory.created_formats.get(key) if fmt_ is not None: return fmt_
from . import axes_size as Size from .axes_divider import Divider, SubplotDivider, LocatableAxes, \ make_axes_locatable from .axes_grid import Grid, ImageGrid, AxesGrid #from axes_divider import make_axes_locatable from matplotlib.cbook import warn_deprecated warn_deprecated(since='2.1', name='mpl_toolkits.axes_grid', alternative='mpl_toolkits.axes_grid1 and' ' mpl_toolkits.axisartist provies the same' ' functionality', obj_type='module')
""" .. note:: Deprecated in 1.3 """ from __future__ import absolute_import, division, print_function, unicode_literals import warnings from matplotlib import cbook cbook.warn_deprecated('1.3', name='matplotlib.mpl', alternative='`import matplotlib as mpl`', obj_type='module') from matplotlib import artist from matplotlib import axis from matplotlib import axes from matplotlib import collections from matplotlib import colors from matplotlib import colorbar from matplotlib import contour from matplotlib import dates from matplotlib import figure from matplotlib import finance from matplotlib import font_manager from matplotlib import image from matplotlib import legend from matplotlib import lines from matplotlib import mlab from matplotlib import cm from matplotlib import patches from matplotlib import quiver from matplotlib import rcParams from matplotlib import table
import datetime import numpy as np from matplotlib import colors as mcolors, verbose, get_cachedir from matplotlib.dates import date2num from matplotlib.cbook import iterable, mkdirs, warn_deprecated from matplotlib.collections import LineCollection, PolyCollection from matplotlib.lines import Line2D, TICKLEFT, TICKRIGHT from matplotlib.patches import Rectangle from matplotlib.transforms import Affine2D warn_deprecated( since=2.0, message=("The finance module has been deprecated in mpl 2.0 and will " "be removed in mpl 2.2. Please use the module mpl_finance " "instead.")) if six.PY3: import hashlib def md5(x): return hashlib.md5(x.encode()) else: from hashlib import md5 cachedir = get_cachedir() # cachedir will be None if there is no writable directory. if cachedir is not None:
def __init__(self, xy, s, size=None, prop=None, _interpolation_steps=1, usetex=False, *args, **kwargs): r""" Create a path from the text. Note that it simply is a path, not an artist. You need to use the `~.PathPatch` (or other artists) to draw this path onto the canvas. Parameters ---------- xy : tuple or array of two float values Position of the text. For no offset, use ``xy=(0, 0)``. s : str The text to convert to a path. size : float, optional Font size in points. Defaults to the size specified via the font properties *prop*. prop : `matplotlib.font_manager.FontProperties`, optional Font property. If not provided, will use a default ``FontProperties`` with parameters from the :ref:`rcParams <matplotlib-rcparams>`. _interpolation_steps : int, optional (Currently ignored) usetex : bool, default: False Whether to use tex rendering. Examples -------- The following creates a path from the string "ABC" with Helvetica font face; and another path from the latex fraction 1/2:: from matplotlib.textpath import TextPath from matplotlib.font_manager import FontProperties fp = FontProperties(family="Helvetica", style="italic") path1 = TextPath((12,12), "ABC", size=12, prop=fp) path2 = TextPath((0,0), r"$\frac{1}{2}$", size=12, usetex=True) Also see :doc:`/gallery/text_labels_and_annotations/demo_text_path`. """ # Circular import. from matplotlib.text import Text if args or kwargs: cbook.warn_deprecated( "3.1", message="Additional arguments to TextPath used to be " "ignored, but will trigger a TypeError %(removal)s.") if prop is None: prop = FontProperties() if size is None: size = prop.get_size_in_points() self._xy = xy self.set_size(size) self._cached_vertices = None s, ismath = Text(usetex=usetex)._preprocess_math(s) self._vertices, self._codes = text_to_path.get_text_path(prop, s, ismath=ismath) self._should_simplify = False self._simplify_threshold = rcParams['path.simplify_threshold'] self._interpolation_steps = _interpolation_steps
import tkinter as tk import numpy as np from matplotlib import cbook from matplotlib.backends import _tkagg cbook.warn_deprecated("3.0", name=__name__, obj_type="module") def blit(photoimage, aggimage, bbox=None, colormode=1): tk = photoimage.tk if bbox is not None: bbox_array = bbox.__array__() # x1, x2, y1, y2 bboxptr = (bbox_array[0, 0], bbox_array[1, 0], bbox_array[0, 1], bbox_array[1, 1]) else: bboxptr = 0 data = np.asarray(aggimage) dataptr = (data.shape[0], data.shape[1], data.ctypes.data) try: tk.call( "PyAggImagePhoto", photoimage, dataptr, colormode, bboxptr) except tk.TclError: if hasattr(tk, 'interpaddr'): _tkagg.tkinit(tk.interpaddr(), 1) else:
def __init__(self, parent, handles, labels, loc=None, numpoints=None, # the number of points in the legend line markerscale=None, # the relative size of legend markers # vs. original markerfirst=True, # controls ordering (left-to-right) of # legend marker and label scatterpoints=None, # number of scatter points scatteryoffsets=None, prop=None, # properties for the legend texts fontsize=None, # keyword to set font size directly # spacing & pad defined as a fraction of the font-size borderpad=None, # the whitespace inside the legend border labelspacing=None, # the vertical space between the legend # entries handlelength=None, # the length of the legend handles handleheight=None, # the height of the legend handles handletextpad=None, # the pad between the legend handle # and text borderaxespad=None, # the pad between the axes and legend # border columnspacing=None, # spacing between columns ncol=1, # number of columns mode=None, # mode for horizontal distribution of columns. # None, "expand" fancybox=None, # True use a fancy box, false use a rounded # box, none use rc shadow=None, title=None, # set a title for the legend title_fontsize=None, # set to ax.fontsize if None framealpha=None, # set frame alpha edgecolor=None, # frame patch edgecolor facecolor=None, # frame patch facecolor bbox_to_anchor=None, # bbox that the legend will be anchored. bbox_transform=None, # transform for the bbox frameon=None, # draw frame handler_map=None, ): """ Parameters ---------- parent : `~matplotlib.axes.Axes` or `.Figure` The artist that contains the legend. handles : sequence of `.Artist` A list of Artists (lines, patches) to be added to the legend. labels : sequence of strings A list of labels to show next to the artists. The length of handles and labels should be the same. If they are not, they are truncated to the smaller of both lengths. Other Parameters ---------------- %(_legend_kw_doc)s Notes ----- Users can specify any arbitrary location for the legend using the *bbox_to_anchor* keyword argument. bbox_to_anchor can be an instance of BboxBase(or its derivatives) or a tuple of 2 or 4 floats. See :meth:`set_bbox_to_anchor` for more detail. The legend location can be specified by setting *loc* with a tuple of 2 floats, which is interpreted as the lower-left corner of the legend in the normalized axes coordinate. """ # local import only to avoid circularity from matplotlib.axes import Axes from matplotlib.figure import Figure Artist.__init__(self) if prop is None: if fontsize is not None: self.prop = FontProperties(size=fontsize) else: self.prop = FontProperties(size=rcParams["legend.fontsize"]) elif isinstance(prop, dict): self.prop = FontProperties(**prop) if "size" not in prop: self.prop.set_size(rcParams["legend.fontsize"]) else: self.prop = prop self._fontsize = self.prop.get_size_in_points() self.texts = [] self.legendHandles = [] self._legend_title_box = None #: A dictionary with the extra handler mappings for this Legend #: instance. self._custom_handler_map = handler_map locals_view = locals() for name in ["numpoints", "markerscale", "shadow", "columnspacing", "scatterpoints", "handleheight", 'borderpad', 'labelspacing', 'handlelength', 'handletextpad', 'borderaxespad']: if locals_view[name] is None: value = rcParams["legend." + name] else: value = locals_view[name] setattr(self, name, value) del locals_view # trim handles and labels if illegal label... _lab, _hand = [], [] for label, handle in zip(labels, handles): if isinstance(label, str) and label.startswith('_'): cbook._warn_external('The handle {!r} has a label of {!r} ' 'which cannot be automatically added to' ' the legend.'.format(handle, label)) else: _lab.append(label) _hand.append(handle) labels, handles = _lab, _hand handles = list(handles) if len(handles) < 2: ncol = 1 self._ncol = ncol if self.numpoints <= 0: raise ValueError("numpoints must be > 0; it was %d" % numpoints) # introduce y-offset for handles of the scatter plot if scatteryoffsets is None: self._scatteryoffsets = np.array([3. / 8., 4. / 8., 2.5 / 8.]) else: self._scatteryoffsets = np.asarray(scatteryoffsets) reps = self.scatterpoints // len(self._scatteryoffsets) + 1 self._scatteryoffsets = np.tile(self._scatteryoffsets, reps)[:self.scatterpoints] # _legend_box is an OffsetBox instance that contains all # legend items and will be initialized from _init_legend_box() # method. self._legend_box = None if isinstance(parent, Axes): self.isaxes = True self.axes = parent self.set_figure(parent.figure) elif isinstance(parent, Figure): self.isaxes = False self.set_figure(parent) else: raise TypeError("Legend needs either Axes or Figure as parent") self.parent = parent self._loc_used_default = loc is None if loc is None: loc = rcParams["legend.loc"] if not self.isaxes and loc in [0, 'best']: loc = 'upper right' if isinstance(loc, str): if loc not in self.codes: if self.isaxes: cbook.warn_deprecated( "3.1", message="Unrecognized location {!r}. Falling " "back on 'best'; valid locations are\n\t{}\n" "This will raise an exception %(removal)s." .format(loc, '\n\t'.join(self.codes))) loc = 0 else: cbook.warn_deprecated( "3.1", message="Unrecognized location {!r}. Falling " "back on 'upper right'; valid locations are\n\t{}\n'" "This will raise an exception %(removal)s." .format(loc, '\n\t'.join(self.codes))) loc = 1 else: loc = self.codes[loc] if not self.isaxes and loc == 0: cbook.warn_deprecated( "3.1", message="Automatic legend placement (loc='best') not " "implemented for figure legend. Falling back on 'upper " "right'. This will raise an exception %(removal)s.") loc = 1 self._mode = mode self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform) # We use FancyBboxPatch to draw a legend frame. The location # and size of the box will be updated during the drawing time. if facecolor is None: facecolor = rcParams["legend.facecolor"] if facecolor == 'inherit': facecolor = rcParams["axes.facecolor"] if edgecolor is None: edgecolor = rcParams["legend.edgecolor"] if edgecolor == 'inherit': edgecolor = rcParams["axes.edgecolor"] self.legendPatch = FancyBboxPatch( xy=(0.0, 0.0), width=1., height=1., facecolor=facecolor, edgecolor=edgecolor, mutation_scale=self._fontsize, snap=True ) # The width and height of the legendPatch will be set (in the # draw()) to the length that includes the padding. Thus we set # pad=0 here. if fancybox is None: fancybox = rcParams["legend.fancybox"] if fancybox: self.legendPatch.set_boxstyle("round", pad=0, rounding_size=0.2) else: self.legendPatch.set_boxstyle("square", pad=0) self._set_artist_props(self.legendPatch) self._drawFrame = frameon if frameon is None: self._drawFrame = rcParams["legend.frameon"] # init with null renderer self._init_legend_box(handles, labels, markerfirst) # If shadow is activated use framealpha if not # explicitly passed. See Issue 8943 if framealpha is None: if shadow: self.get_frame().set_alpha(1) else: self.get_frame().set_alpha(rcParams["legend.framealpha"]) else: self.get_frame().set_alpha(framealpha) tmp = self._loc_used_default self._set_loc(loc) self._loc_used_default = tmp # ignore changes done by _set_loc # figure out title fontsize: if title_fontsize is None: title_fontsize = rcParams['legend.title_fontsize'] tprop = FontProperties(size=title_fontsize) self.set_title(title, prop=tprop) self._last_fontsize_points = self._fontsize self._draggable = None
import datetime import numpy as np from matplotlib import colors as mcolors, verbose, get_cachedir from matplotlib.dates import date2num from matplotlib.cbook import iterable, mkdirs, warn_deprecated from matplotlib.collections import LineCollection, PolyCollection from matplotlib.lines import Line2D, TICKLEFT, TICKRIGHT from matplotlib.patches import Rectangle from matplotlib.transforms import Affine2D warn_deprecated( since=2.0, message=("The finance module has been deprecated in mpl 2.0 and will " "be removed in mpl 2.2. Please use the matplotlib toolkit " "finance instead.")) if six.PY3: import hashlib def md5(x): return hashlib.md5(x.encode()) else: from hashlib import md5 cachedir = get_cachedir() # cachedir will be None if there is no writable directory. if cachedir is not None:
""" from __future__ import (absolute_import, division, print_function, unicode_literals) import six import copy import numpy as np import xlwt as excel import matplotlib.cbook as cbook import matplotlib.mlab as mlab cbook.warn_deprecated("2.0", name="mpl_toolkits.exceltools", alternative="openpyxl", obj_type="module") def xlformat_factory(format): """ copy the format, perform any overrides, and attach an xlstyle instance copied format is returned """ #if we have created an excel format already using this format, #don't recreate it; mlab.FormatObj override has to make objs with #the same props hash to the same value key = hash(format) fmt_ = xlformat_factory.created_formats.get(key) if fmt_ is not None:
from __future__ import (absolute_import, division, print_function, unicode_literals) from matplotlib.externals import six from matplotlib.externals.six.moves import zip import warnings import numpy as np from matplotlib._delaunay import delaunay from .interpolate import LinearInterpolator, NNInterpolator from matplotlib.cbook import warn_deprecated warn_deprecated('1.4', name='matplotlib.delaunay', alternative='matplotlib.tri.Triangulation', obj_type='module') __all__ = ['Triangulation', 'DuplicatePointWarning'] class DuplicatePointWarning(RuntimeWarning): """Duplicate points were passed in to the triangulation routine. """ class Triangulation(object): """A Delaunay triangulation of points in a plane. Triangulation(x, y) x, y -- the coordinates of the points as 1-D arrays of floats
import datetime import numpy as np from matplotlib import colors as mcolors, verbose, get_cachedir from matplotlib.dates import date2num from matplotlib.cbook import iterable, mkdirs, warn_deprecated from matplotlib.collections import LineCollection, PolyCollection from matplotlib.lines import Line2D, TICKLEFT, TICKRIGHT from matplotlib.patches import Rectangle from matplotlib.transforms import Affine2D warn_deprecated( since=2.0, message=("The finance module has been deprecated in mpl 2.0 and will " "be removed in mpl 2.2. Please use the module mpl_finance " "instead.")) if six.PY3: import hashlib def md5(x): return hashlib.md5(x.encode()) else: from hashlib import md5 cachedir = get_cachedir() # cachedir will be None if there is no writable directory. if cachedir is not None: cachedir = os.path.join(cachedir, 'finance.cache')
def __init__(self, xy, s, size=None, prop=None, _interpolation_steps=1, usetex=False, *args, **kwargs): r""" Create a path from the text. Note that it simply is a path, not an artist. You need to use the `~.PathPatch` (or other artists) to draw this path onto the canvas. Parameters ---------- xy : tuple or array of two float values Position of the text. For no offset, use ``xy=(0, 0)``. s : str The text to convert to a path. size : float, optional Font size in points. Defaults to the size specified via the font properties *prop*. prop : `matplotlib.font_manager.FontProperties`, optional Font property. If not provided, will use a default ``FontProperties`` with parameters from the :ref:`rcParams <matplotlib-rcparams>`. _interpolation_steps : integer, optional (Currently ignored) usetex : bool, optional Whether to use tex rendering. Defaults to ``False``. Examples -------- The following creates a path from the string "ABC" with Helvetica font face; and another path from the latex fraction 1/2:: from matplotlib.textpath import TextPath from matplotlib.font_manager import FontProperties fp = FontProperties(family="Helvetica", style="italic") path1 = TextPath((12,12), "ABC", size=12, prop=fp) path2 = TextPath((0,0), r"$\frac{1}{2}$", size=12, usetex=True) Also see :doc:`/gallery/text_labels_and_annotations/demo_text_path`. """ # Circular import. from matplotlib.text import Text if args or kwargs: cbook.warn_deprecated( "3.1", message="Additional arguments to TextPath used to be " "ignored, but will trigger a TypeError %(removal)s.") if prop is None: prop = FontProperties() if size is None: size = prop.get_size_in_points() self._xy = xy self.set_size(size) self._cached_vertices = None s, ismath = Text(usetex=usetex)._preprocess_math(s) self._vertices, self._codes = text_to_path.get_text_path( prop, s, ismath=ismath) self._should_simplify = False self._simplify_threshold = rcParams['path.simplify_threshold'] self._interpolation_steps = _interpolation_steps
import tkinter as Tk import numpy as np from matplotlib import cbook from matplotlib.backends import _tkagg cbook.warn_deprecated("3.0", name=__name__, obj_type="module") def blit(photoimage, aggimage, bbox=None, colormode=1): tk = photoimage.tk if bbox is not None: bbox_array = bbox.__array__() # x1, x2, y1, y2 bboxptr = (bbox_array[0, 0], bbox_array[1, 0], bbox_array[0, 1], bbox_array[1, 1]) else: bboxptr = 0 data = np.asarray(aggimage) dataptr = (data.shape[0], data.shape[1], data.ctypes.data) try: tk.call( "PyAggImagePhoto", photoimage, dataptr, colormode, bboxptr) except Tk.TclError: if hasattr(tk, 'interpaddr'): _tkagg.tkinit(tk.interpaddr(), 1) else:
# Originally from astropy project (http://astropy.org), under BSD # 3-clause license. import contextlib import socket from matplotlib import cbook cbook.warn_deprecated("3.2", name=__name__, obj_type="module", alternative="pytest-remotedata") # save original socket method for restoration # These are global so that re-calling the turn_off_internet function doesn't # overwrite them again socket_original = socket.socket socket_create_connection = socket.create_connection socket_bind = socket.socket.bind socket_connect = socket.socket.connect INTERNET_OFF = False # urllib2 uses a global variable to cache its default "opener" for opening # connections for various protocols; we store it off here so we can restore to # the default after re-enabling internet use _orig_opener = None # ::1 is apparently another valid name for localhost? # it is returned by getaddrinfo when that function is given localhost
def _init_legend_box(self, handles, labels, markerfirst=True): """ Initialize the legend_box. The legend_box is an instance of the OffsetBox, which is packed with legend handles and texts. Once packed, their location is calculated during the drawing time. """ fontsize = self._fontsize # legend_box is a HPacker, horizontally packed with # columns. Each column is a VPacker, vertically packed with # legend items. Each legend item is HPacker packed with # legend handleBox and labelBox. handleBox is an instance of # offsetbox.DrawingArea which contains legend handle. labelBox # is an instance of offsetbox.TextArea which contains legend # text. text_list = [] # the list of text instances handle_list = [] # the list of text instances label_prop = dict(verticalalignment='baseline', horizontalalignment='left', fontproperties=self.prop, ) labelboxes = [] handleboxes = [] # The approximate height and descent of text. These values are # only used for plotting the legend handle. descent = 0.35 * self._approx_text_height() * (self.handleheight - 0.7) # 0.35 and 0.7 are just heuristic numbers and may need to be improved. height = self._approx_text_height() * self.handleheight - descent # each handle needs to be drawn inside a box of (x, y, w, h) = # (0, -descent, width, height). And their coordinates should # be given in the display coordinates. # The transformation of each handle will be automatically set # to self.get_trasnform(). If the artist does not use its # default transform (e.g., Collections), you need to # manually set their transform to the self.get_transform(). legend_handler_map = self.get_legend_handler_map() for orig_handle, lab in zip(handles, labels): handler = self.get_legend_handler(legend_handler_map, orig_handle) if handler is None: warnings.warn( "Legend does not support {!r} instances.\nA proxy artist " "may be used instead.\nSee: " "http://matplotlib.org/users/legend_guide.html" "#using-proxy-artist".format(orig_handle) ) # We don't have a handle for this artist, so we just defer # to None. handle_list.append(None) else: textbox = TextArea(lab, textprops=label_prop, multilinebaseline=True, minimumdescent=True) text_list.append(textbox._text) labelboxes.append(textbox) handlebox = DrawingArea(width=self.handlelength * fontsize, height=height, xdescent=0., ydescent=descent) handleboxes.append(handlebox) # Deprecate the old behaviour of accepting callable # legend handlers in favour of the "legend_artist" # interface. if (not hasattr(handler, 'legend_artist') and callable(handler)): handler.legend_artist = handler.__call__ warn_deprecated('1.4', ('Legend handers must now implement a ' '"legend_artist" method rather than ' 'being a callable.')) # Create the artist for the legend which represents the # original artist/handle. handle_list.append(handler.legend_artist(self, orig_handle, fontsize, handlebox)) if len(handleboxes) > 0: # We calculate number of rows in each column. The first # (num_largecol) columns will have (nrows+1) rows, and remaining # (num_smallcol) columns will have (nrows) rows. ncol = min(self._ncol, len(handleboxes)) nrows, num_largecol = divmod(len(handleboxes), ncol) num_smallcol = ncol - num_largecol # starting index of each column and number of rows in it. largecol = safezip(list(xrange(0, num_largecol * (nrows + 1), (nrows + 1))), [nrows + 1] * num_largecol) smallcol = safezip(list(xrange(num_largecol * (nrows + 1), len(handleboxes), nrows)), [nrows] * num_smallcol) else: largecol, smallcol = [], [] handle_label = safezip(handleboxes, labelboxes) columnbox = [] for i0, di in largecol + smallcol: # pack handleBox and labelBox into itemBox itemBoxes = [HPacker(pad=0, sep=self.handletextpad * fontsize, children=[h, t] if markerfirst else [t, h], align="baseline") for h, t in handle_label[i0:i0 + di]] # minimumdescent=False for the text of the last row of the column if markerfirst: itemBoxes[-1].get_children()[1].set_minimumdescent(False) else: itemBoxes[-1].get_children()[0].set_minimumdescent(False) # pack columnBox if markerfirst: alignment = "baseline" else: alignment = "right" columnbox.append(VPacker(pad=0, sep=self.labelspacing * fontsize, align=alignment, children=itemBoxes)) if self._mode == "expand": mode = "expand" else: mode = "fixed" sep = self.columnspacing * fontsize self._legend_handle_box = HPacker(pad=0, sep=sep, align="baseline", mode=mode, children=columnbox) self._legend_title_box = TextArea("") self._legend_box = VPacker(pad=self.borderpad * fontsize, sep=self.labelspacing * fontsize, align="center", children=[self._legend_title_box, self._legend_handle_box]) self._legend_box.set_figure(self.figure) self.texts = text_list self.legendHandles = handle_list
from six.moves import xrange import os, sys try: import objc except ImportError: raise ImportError('The CococaAgg backend required PyObjC to be installed!') from Foundation import * from AppKit import * from PyObjCTools import NibClassBuilder, AppHelper from matplotlib import cbook cbook.warn_deprecated( '1.3', message="The CocoaAgg backend is not a fully-functioning backend. " "It may be removed in matplotlib 1.4.") import matplotlib from matplotlib.figure import Figure from matplotlib.backend_bases import FigureManagerBase, FigureCanvasBase from matplotlib.backend_bases import ShowBase from .backend_agg import FigureCanvasAgg from matplotlib._pylab_helpers import Gcf mplBundle = NSBundle.bundleWithPath_(os.path.dirname(__file__)) def new_figure_manager(num, *args, **kwargs): FigureClass = kwargs.pop('FigureClass', Figure)
""" from __future__ import (absolute_import, division, print_function, unicode_literals) import six from six.moves import xrange, zip import copy import gtk, gobject import numpy as np import matplotlib.cbook as cbook from matplotlib.cbook import warn_deprecated import matplotlib.mlab as mlab warn_deprecated("2.0", name="mpl_toolkits.gtktools", obj_type="module") def error_message(msg, parent=None, title=None): """ create an error message dialog with string msg. Optionally set the parent widget and dialog title """ dialog = gtk.MessageDialog( parent = None, type = gtk.MESSAGE_ERROR, buttons = gtk.BUTTONS_OK, message_format = msg) if parent is not None: dialog.set_transient_for(parent)
def print_jpg(self, filename_or_obj, *args, dryrun=False, pil_kwargs=None, **kwargs): """ Write the figure to a JPEG file. Parameters ---------- filename_or_obj : str or path-like or file-like The file to write to. Other Parameters ---------------- quality : int, default: :rc:`savefig.jpeg_quality` The image quality, on a scale from 1 (worst) to 95 (best). Values above 95 should be avoided; 100 disables portions of the JPEG compression algorithm, and results in large files with hardly any gain in image quality. This parameter is deprecated. optimize : bool, default: False Whether the encoder should make an extra pass over the image in order to select optimal encoder settings. This parameter is deprecated. progressive : bool, default: False Whether the image should be stored as a progressive JPEG file. This parameter is deprecated. pil_kwargs : dict, optional Additional keyword arguments that are passed to `PIL.Image.Image.save` when saving the figure. These take precedence over *quality*, *optimize* and *progressive*. """ # Remove transparency by alpha-blending on an assumed white background. r, g, b, a = mcolors.to_rgba(self.figure.get_facecolor()) try: self.figure.set_facecolor(a * np.array([r, g, b]) + 1 - a) FigureCanvasAgg.draw(self) finally: self.figure.set_facecolor((r, g, b, a)) if dryrun: return if pil_kwargs is None: pil_kwargs = {} for k in ["quality", "optimize", "progressive"]: if k in kwargs: pil_kwargs.setdefault(k, kwargs.pop(k)) if "quality" not in pil_kwargs: quality = pil_kwargs["quality"] = \ dict.__getitem__(mpl.rcParams, "savefig.jpeg_quality") if quality not in [0, 75, 95]: # default qualities. cbook.warn_deprecated( "3.3", name="savefig.jpeg_quality", obj_type="rcParam", addendum="Set the quality using " "`pil_kwargs={'quality': ...}`; the future default " "quality will be 75, matching the default of Pillow and " "libjpeg.") pil_kwargs.setdefault("dpi", (self.figure.dpi, self.figure.dpi)) # Drop alpha channel now. return (Image.fromarray(np.asarray(self.buffer_rgba())[..., :3]) .save(filename_or_obj, format='jpeg', **pil_kwargs))
import numpy as np import matplotlib as mpl from matplotlib import cbook import matplotlib.colors as colors import matplotlib.cm as cm from matplotlib import docstring import matplotlib.ticker as ticker import matplotlib.collections as collections import matplotlib.contour as contour from matplotlib.path import Path from matplotlib.patches import PathPatch from matplotlib.transforms import Bbox cbook.warn_deprecated("3.2", name=__name__, obj_type="module", alternative="matplotlib.colorbar") make_axes_kw_doc = ''' ============= ==================================================== Property Description ============= ==================================================== *orientation* vertical or horizontal *fraction* 0.15; fraction of original axes to use for colorbar *pad* 0.05 if vertical, 0.15 if horizontal; fraction of original axes between colorbar and new image axes *shrink* 1.0; fraction by which to shrink the colorbar *aspect* 20; ratio of long to short dimensions ============= ====================================================
def __init__( self, parent, handles, labels, loc=None, numpoints=None, # the number of points in the legend line markerscale=None, # the relative size of legend markers # vs. original markerfirst=True, # controls ordering (left-to-right) of # legend marker and label scatterpoints=None, # number of scatter points scatteryoffsets=None, prop=None, # properties for the legend texts fontsize=None, # keyword to set font size directly # spacing & pad defined as a fraction of the font-size borderpad=None, # the whitespace inside the legend border labelspacing=None, # the vertical space between the legend # entries handlelength=None, # the length of the legend handles handleheight=None, # the height of the legend handles handletextpad=None, # the pad between the legend handle # and text borderaxespad=None, # the pad between the axes and legend # border columnspacing=None, # spacing between columns ncol=1, # number of columns mode=None, # mode for horizontal distribution of columns. # None, "expand" fancybox=None, # True use a fancy box, false use a rounded # box, none use rc shadow=None, title=None, # set a title for the legend title_fontsize=None, # set to ax.fontsize if None framealpha=None, # set frame alpha edgecolor=None, # frame patch edgecolor facecolor=None, # frame patch facecolor bbox_to_anchor=None, # bbox that the legend will be anchored. bbox_transform=None, # transform for the bbox frameon=None, # draw frame handler_map=None, ): """ Parameters ---------- parent : `~matplotlib.axes.Axes` or `.Figure` The artist that contains the legend. handles : list of `.Artist` A list of Artists (lines, patches) to be added to the legend. labels : list of str A list of labels to show next to the artists. The length of handles and labels should be the same. If they are not, they are truncated to the smaller of both lengths. Other Parameters ---------------- %(_legend_kw_doc)s Notes ----- Users can specify any arbitrary location for the legend using the *bbox_to_anchor* keyword argument. *bbox_to_anchor* can be a `.BboxBase` (or derived therefrom) or a tuple of 2 or 4 floats. See :meth:`set_bbox_to_anchor` for more detail. The legend location can be specified by setting *loc* with a tuple of 2 floats, which is interpreted as the lower-left corner of the legend in the normalized axes coordinate. """ # local import only to avoid circularity from matplotlib.axes import Axes from matplotlib.figure import Figure Artist.__init__(self) if prop is None: if fontsize is not None: self.prop = FontProperties(size=fontsize) else: self.prop = FontProperties(size=rcParams["legend.fontsize"]) elif isinstance(prop, dict): self.prop = FontProperties(**prop) if "size" not in prop: self.prop.set_size(rcParams["legend.fontsize"]) else: self.prop = prop self._fontsize = self.prop.get_size_in_points() self.texts = [] self.legendHandles = [] self._legend_title_box = None #: A dictionary with the extra handler mappings for this Legend #: instance. self._custom_handler_map = handler_map locals_view = locals() for name in [ "numpoints", "markerscale", "shadow", "columnspacing", "scatterpoints", "handleheight", 'borderpad', 'labelspacing', 'handlelength', 'handletextpad', 'borderaxespad' ]: if locals_view[name] is None: value = rcParams["legend." + name] else: value = locals_view[name] setattr(self, name, value) del locals_view # trim handles and labels if illegal label... _lab, _hand = [], [] for label, handle in zip(labels, handles): if isinstance(label, str) and label.startswith('_'): cbook._warn_external('The handle {!r} has a label of {!r} ' 'which cannot be automatically added to' ' the legend.'.format(handle, label)) else: _lab.append(label) _hand.append(handle) labels, handles = _lab, _hand handles = list(handles) if len(handles) < 2: ncol = 1 self._ncol = ncol if self.numpoints <= 0: raise ValueError("numpoints must be > 0; it was %d" % numpoints) # introduce y-offset for handles of the scatter plot if scatteryoffsets is None: self._scatteryoffsets = np.array([3. / 8., 4. / 8., 2.5 / 8.]) else: self._scatteryoffsets = np.asarray(scatteryoffsets) reps = self.scatterpoints // len(self._scatteryoffsets) + 1 self._scatteryoffsets = np.tile(self._scatteryoffsets, reps)[:self.scatterpoints] # _legend_box is a VPacker instance that contains all # legend items and will be initialized from _init_legend_box() # method. self._legend_box = None if isinstance(parent, Axes): self.isaxes = True self.axes = parent self.set_figure(parent.figure) elif isinstance(parent, Figure): self.isaxes = False self.set_figure(parent) else: raise TypeError("Legend needs either Axes or Figure as parent") self.parent = parent self._loc_used_default = loc is None if loc is None: loc = rcParams["legend.loc"] if not self.isaxes and loc in [0, 'best']: loc = 'upper right' if isinstance(loc, str): if loc not in self.codes: if self.isaxes: cbook.warn_deprecated( "3.1", message="Unrecognized location {!r}. Falling " "back on 'best'; valid locations are\n\t{}\n" "This will raise an exception %(removal)s.".format( loc, '\n\t'.join(self.codes))) loc = 0 else: cbook.warn_deprecated( "3.1", message="Unrecognized location {!r}. Falling " "back on 'upper right'; valid locations are\n\t{}\n'" "This will raise an exception %(removal)s.".format( loc, '\n\t'.join(self.codes))) loc = 1 else: loc = self.codes[loc] if not self.isaxes and loc == 0: cbook.warn_deprecated( "3.1", message="Automatic legend placement (loc='best') not " "implemented for figure legend. Falling back on 'upper " "right'. This will raise an exception %(removal)s.") loc = 1 self._mode = mode self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform) # We use FancyBboxPatch to draw a legend frame. The location # and size of the box will be updated during the drawing time. if facecolor is None: facecolor = rcParams["legend.facecolor"] if facecolor == 'inherit': facecolor = rcParams["axes.facecolor"] if edgecolor is None: edgecolor = rcParams["legend.edgecolor"] if edgecolor == 'inherit': edgecolor = rcParams["axes.edgecolor"] self.legendPatch = FancyBboxPatch(xy=(0.0, 0.0), width=1., height=1., facecolor=facecolor, edgecolor=edgecolor, mutation_scale=self._fontsize, snap=True) # The width and height of the legendPatch will be set (in the # draw()) to the length that includes the padding. Thus we set # pad=0 here. if fancybox is None: fancybox = rcParams["legend.fancybox"] if fancybox: self.legendPatch.set_boxstyle("round", pad=0, rounding_size=0.2) else: self.legendPatch.set_boxstyle("square", pad=0) self._set_artist_props(self.legendPatch) self._drawFrame = frameon if frameon is None: self._drawFrame = rcParams["legend.frameon"] # init with null renderer self._init_legend_box(handles, labels, markerfirst) # If shadow is activated use framealpha if not # explicitly passed. See Issue 8943 if framealpha is None: if shadow: self.get_frame().set_alpha(1) else: self.get_frame().set_alpha(rcParams["legend.framealpha"]) else: self.get_frame().set_alpha(framealpha) tmp = self._loc_used_default self._set_loc(loc) self._loc_used_default = tmp # ignore changes done by _set_loc # figure out title fontsize: if title_fontsize is None: title_fontsize = rcParams['legend.title_fontsize'] tprop = FontProperties(size=title_fontsize) self.set_title(title, prop=tprop) self._draggable = None
""" MS Windows-specific helper for the TkAgg backend. With rcParams['tk.window_focus'] default of False, it is effectively disabled. It uses a tiny C++ extension module to access MS Win functions. This module is deprecated and will be removed in version 3.2 """ from matplotlib import rcParams, cbook cbook.warn_deprecated('3.0', obj_type='module', name='backends.windowing') try: if not rcParams['tk.window_focus']: raise ImportError from matplotlib._windowing import GetForegroundWindow, SetForegroundWindow except ImportError: def GetForegroundWindow(): return 0 def SetForegroundWindow(hwnd): pass class FocusManager(object): def __init__(self):
def _wants_nose(): wants_nose = (not getattr(mpl, '_called_from_pytest', False) and 'nose' in sys.modules) if wants_nose: cbook.warn_deprecated("3.2", name="support for nose-based tests") return wants_nose
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. from __future__ import (absolute_import, division, print_function, unicode_literals) import six from six.moves import xrange import numpy as np from matplotlib.cbook import deprecated, warn_deprecated warn_deprecated('1.4.0', name='matplotlib.testing.image_util', obj_type='module') @deprecated('1.4.0') def autocontrast(image, cutoff=0): """ Maximize image contrast, based on histogram. This completely ignores the alpha channel. """ assert image.dtype == np.uint8 output_image = np.empty((image.shape[0], image.shape[1], 3), np.uint8) for i in xrange(0, 3): plane = image[:,:,i] output_plane = output_image[:,:,i]
import tkinter as Tk import numpy as np from matplotlib import cbook from matplotlib.backends import _tkagg cbook.warn_deprecated("3.0", "The matplotlib.backends.tkagg module is deprecated.") def blit(photoimage, aggimage, bbox=None, colormode=1): tk = photoimage.tk if bbox is not None: bbox_array = bbox.__array__() # x1, x2, y1, y2 bboxptr = (bbox_array[0, 0], bbox_array[1, 0], bbox_array[0, 1], bbox_array[1, 1]) else: bboxptr = 0 data = np.asarray(aggimage) dataptr = (data.shape[0], data.shape[1], data.ctypes.data) try: tk.call("PyAggImagePhoto", photoimage, dataptr, colormode, bboxptr) except Tk.TclError: if hasattr(tk, 'interpaddr'): _tkagg.tkinit(tk.interpaddr(), 1) else: # very old python? _tkagg.tkinit(tk, 0)
""" A replacement wrapper around the subprocess module, which provides a stub implementation of subprocess members on Google App Engine (which are missing in subprocess). Instead of importing subprocess, other modules should use this as follows: from matplotlib.compat import subprocess This module is safe to import from anywhere within matplotlib. """ import subprocess from matplotlib.cbook import warn_deprecated warn_deprecated(since='3.0', name='matplotlib.compat.subprocess', alternative='the python 3 standard library ' '"subprocess" module', obj_type='module') __all__ = ['Popen', 'PIPE', 'STDOUT', 'check_output', 'CalledProcessError'] if hasattr(subprocess, 'Popen'): Popen = subprocess.Popen # Assume that it also has the other constants. PIPE = subprocess.PIPE STDOUT = subprocess.STDOUT CalledProcessError = subprocess.CalledProcessError check_output = subprocess.check_output else: # In restricted environments (such as Google App Engine), these are
def _init_legend_box(self, handles, labels): """ Initialize the legend_box. The legend_box is an instance of the OffsetBox, which is packed with legend handles and texts. Once packed, their location is calculated during the drawing time. """ fontsize = self._fontsize # legend_box is a HPacker, horizontally packed with # columns. Each column is a VPacker, vertically packed with # legend items. Each legend item is HPacker packed with # legend handleBox and labelBox. handleBox is an instance of # offsetbox.DrawingArea which contains legend handle. labelBox # is an instance of offsetbox.TextArea which contains legend # text. text_list = [] # the list of text instances handle_list = [] # the list of text instances label_prop = dict(verticalalignment='baseline', horizontalalignment='left', fontproperties=self.prop, ) labelboxes = [] handleboxes = [] # The approximate height and descent of text. These values are # only used for plotting the legend handle. descent = 0.35 * self._approx_text_height() * (self.handleheight - 0.7) # 0.35 and 0.7 are just heuristic numbers and may need to be improved. height = self._approx_text_height() * self.handleheight - descent # each handle needs to be drawn inside a box of (x, y, w, h) = # (0, -descent, width, height). And their coordinates should # be given in the display coordinates. # The transformation of each handle will be automatically set # to self.get_trasnform(). If the artist does not use its # default transform (e.g., Collections), you need to # manually set their transform to the self.get_transform(). legend_handler_map = self.get_legend_handler_map() for orig_handle, lab in zip(handles, labels): handler = self.get_legend_handler(legend_handler_map, orig_handle) if handler is None: warnings.warn( "Legend does not support {!r} instances.\nA proxy artist " "may be used instead.\nSee: " "http://matplotlib.org/users/legend_guide.html" "#using-proxy-artist".format(orig_handle)) # We don't have a handle for this artist, so we just defer # to None. handle_list.append(None) else: textbox = TextArea(lab, textprops=label_prop, multilinebaseline=True, minimumdescent=True) text_list.append(textbox._text) labelboxes.append(textbox) handlebox = DrawingArea(width=self.handlelength * fontsize, height=height, xdescent=0., ydescent=descent) handleboxes.append(handlebox) # Deprecate the old behaviour of accepting callable # legend handlers in favour of the "legend_artist" # interface. if (not hasattr(handler, 'legend_artist') and callable(handler)): handler.legend_artist = handler.__call__ warn_deprecated('1.4', ('Legend handers must now implement a ' '"legend_artist" method rather than ' 'being a callable.')) # Create the artist for the legend which represents the # original artist/handle. handle_list.append(handler.legend_artist(self, orig_handle, fontsize, handlebox)) if len(handleboxes) > 0: # We calculate number of rows in each column. The first # (num_largecol) columns will have (nrows+1) rows, and remaining # (num_smallcol) columns will have (nrows) rows. ncol = min(self._ncol, len(handleboxes)) nrows, num_largecol = divmod(len(handleboxes), ncol) num_smallcol = ncol - num_largecol # starting index of each column and number of rows in it. largecol = safezip(list(xrange(0, num_largecol * (nrows + 1), (nrows + 1))), [nrows + 1] * num_largecol) smallcol = safezip(list(xrange(num_largecol * (nrows + 1), len(handleboxes), nrows)), [nrows] * num_smallcol) else: largecol, smallcol = [], [] handle_label = safezip(handleboxes, labelboxes) columnbox = [] for i0, di in largecol + smallcol: # pack handleBox and labelBox into itemBox itemBoxes = [HPacker(pad=0, sep=self.handletextpad * fontsize, children=[h, t], align="baseline") for h, t in handle_label[i0:i0 + di]] # minimumdescent=False for the text of the last row of the column itemBoxes[-1].get_children()[1].set_minimumdescent(False) # pack columnBox columnbox.append(VPacker(pad=0, sep=self.labelspacing * fontsize, align="baseline", children=itemBoxes)) if self._mode == "expand": mode = "expand" else: mode = "fixed" sep = self.columnspacing * fontsize self._legend_handle_box = HPacker(pad=0, sep=sep, align="baseline", mode=mode, children=columnbox) self._legend_title_box = TextArea("") self._legend_box = VPacker(pad=self.borderpad * fontsize, sep=self.labelspacing * fontsize, align="center", children=[self._legend_title_box, self._legend_handle_box]) self._legend_box.set_figure(self.figure) self.texts = text_list self.legendHandles = handle_list
""" MS Windows-specific helper for the TkAgg backend. With rcParams['tk.window_focus'] default of False, it is effectively disabled. It uses a tiny C++ extension module to access MS Win functions. This module is deprecated and will be removed in version 3.2 """ from matplotlib import rcParams, cbook cbook.warn_deprecated('3.0', obj_type='module', name='backends.windowing') try: if not rcParams['tk.window_focus']: raise ImportError from matplotlib._windowing import GetForegroundWindow, SetForegroundWindow except ImportError: def GetForegroundWindow(): return 0 def SetForegroundWindow(hwnd): pass class FocusManager(object): def __init__(self): self._shellWindow = GetForegroundWindow()
import tkinter as Tk import numpy as np from matplotlib import cbook from matplotlib.backends import _tkagg cbook.warn_deprecated( "3.0", "The matplotlib.backends.tkagg module is deprecated.") def blit(photoimage, aggimage, bbox=None, colormode=1): tk = photoimage.tk if bbox is not None: bbox_array = bbox.__array__() # x1, x2, y1, y2 bboxptr = (bbox_array[0, 0], bbox_array[1, 0], bbox_array[0, 1], bbox_array[1, 1]) else: bboxptr = 0 data = np.asarray(aggimage) dataptr = (data.shape[0], data.shape[1], data.ctypes.data) try: tk.call( "PyAggImagePhoto", photoimage, dataptr, colormode, bboxptr) except Tk.TclError: if hasattr(tk, 'interpaddr'): _tkagg.tkinit(tk.interpaddr(), 1)
def remove_coding(text): r"""Remove the coding comment, which six.exec\_ doesn't like.""" cbook.warn_deprecated('3.0', name='remove_coding', removal='3.1') sub_re = re.compile(r"^#\s*-\*-\s*coding:\s*.*-\*-$", flags=re.MULTILINE) return sub_re.sub("", text)
""" .. note:: Deprecated in 1.3 """ import warnings from matplotlib import cbook cbook.warn_deprecated( '1.3', name='matplotlib.mpl', alternative='`import matplotlib as mpl`', obj_type='module') from matplotlib import artist from matplotlib import axis from matplotlib import axes from matplotlib import collections from matplotlib import colors from matplotlib import colorbar from matplotlib import contour from matplotlib import dates from matplotlib import figure from matplotlib import finance from matplotlib import font_manager from matplotlib import image from matplotlib import legend from matplotlib import lines from matplotlib import mlab from matplotlib import cm from matplotlib import patches from matplotlib import quiver from matplotlib import rcParams from matplotlib import table from matplotlib import text from matplotlib import ticker from matplotlib import transforms
from __future__ import (absolute_import, division, print_function, unicode_literals) from matplotlib.externals import six from matplotlib.externals.six.moves import zip import warnings import numpy as np from _delaunay import delaunay from .interpolate import LinearInterpolator, NNInterpolator from matplotlib.cbook import warn_deprecated warn_deprecated('1.4', name='matplotlib.delaunay', alternative='matplotlib.tri.Triangulation', obj_type='module') __all__ = ['Triangulation', 'DuplicatePointWarning'] class DuplicatePointWarning(RuntimeWarning): """Duplicate points were passed in to the triangulation routine. """ class Triangulation(object): """A Delaunay triangulation of points in a plane. Triangulation(x, y) x, y -- the coordinates of the points as 1-D arrays of floats
""" import os, sys try: import objc except ImportError: raise ImportError('The CococaAgg backend required PyObjC to be installed!') from Foundation import * from AppKit import * from PyObjCTools import NibClassBuilder, AppHelper from matplotlib import cbook cbook.warn_deprecated( '1.3', message="The CocoaAgg backend is not a fully-functioning backend. " "It may be removed in matplotlib 1.4.") import matplotlib from matplotlib.figure import Figure from matplotlib.backend_bases import FigureManagerBase, FigureCanvasBase from matplotlib.backend_bases import ShowBase from backend_agg import FigureCanvasAgg from matplotlib._pylab_helpers import Gcf mplBundle = NSBundle.bundleWithPath_(os.path.dirname(__file__)) def new_figure_manager(num, *args, **kwargs): FigureClass = kwargs.pop('FigureClass', Figure)