desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'*norm* is an instance of :class:`colors.Normalize` or one of its subclasses, used to map luminance to 0-1. *cmap* is a :mod:`cm` colormap instance, for example :data:`cm.jet`'
def __init__(self, norm=None, cmap=None):
self.callbacksSM = cbook.CallbackRegistry(('changed',)) if (cmap is None): cmap = get_cmap() if (norm is None): norm = colors.Normalize() self._A = None self.norm = norm self.cmap = cmap self.colorbar = None self.update_dict = {'array': False}
'set the colorbar image and axes associated with mappable'
def set_colorbar(self, im, ax):
self.colorbar = (im, ax)
'Return a normalized rgba array corresponding to *x*. If *x* is already an rgb array, insert *alpha*; if it is already rgba, return it unchanged. If *bytes* is True, return rgba as 4 uint8s instead of 4 floats.'
def to_rgba(self, x, alpha=1.0, bytes=False):
try: if (x.ndim == 3): if (x.shape[2] == 3): if (x.dtype == np.uint8): alpha = np.array((alpha * 255), np.uint8) (m, n) = x.shape[:2] xx = np.empty(shape=(m, n, 4), dtype=x.dtype) xx[:, :, :3] = x xx[:, :, 3] = alpha elif (x.shape[2] == 4): xx = x else: raise ValueError('third dimension must be 3 or 4') if (bytes and (xx.dtype != np.uint8)): xx = (xx * 255).astype(np.uint8) return xx except AttributeError: pass x = ma.asarray(x) x = self.norm(x) x = self.cmap(x, alpha=alpha, bytes=bytes) return x
'Set the image array from numpy array *A*'
def set_array(self, A):
self._A = A self.update_dict['array'] = True
'Return the array'
def get_array(self):
return self._A
'return the colormap'
def get_cmap(self):
return self.cmap
'return the min, max of the color limits for image scaling'
def get_clim(self):
return (self.norm.vmin, self.norm.vmax)
'set the norm limits for image scaling; if *vmin* is a length2 sequence, interpret it as ``(vmin, vmax)`` which is used to support setp ACCEPTS: a length 2 sequence of floats'
def set_clim(self, vmin=None, vmax=None):
if ((vmin is not None) and (vmax is None) and cbook.iterable(vmin) and (len(vmin) == 2)): (vmin, vmax) = vmin if (vmin is not None): self.norm.vmin = vmin if (vmax is not None): self.norm.vmax = vmax self.changed()
'set the colormap for luminance data ACCEPTS: a colormap'
def set_cmap(self, cmap):
if (cmap is None): cmap = get_cmap() self.cmap = cmap self.changed()
'set the normalization instance'
def set_norm(self, norm):
if (norm is None): norm = colors.Normalize() self.norm = norm self.changed()
'Autoscale the scalar limits on the norm instance using the current array'
def autoscale(self):
if (self._A is None): raise TypeError('You must first set_array for mappable') self.norm.autoscale(self._A) self.changed()
'Autoscale the scalar limits on the norm instance using the current array, changing only limits that are None'
def autoscale_None(self):
if (self._A is None): raise TypeError('You must first set_array for mappable') self.norm.autoscale_None(self._A) self.changed()
'Add an entry to a dictionary of boolean flags that are set to True when the mappable is changed.'
def add_checker(self, checker):
self.update_dict[checker] = False
'If mappable has changed since the last check, return True; else return False'
def check_update(self, checker):
if self.update_dict[checker]: self.update_dict[checker] = False return True return False
'Call this whenever the mappable is changed to notify all the callbackSM listeners to the \'changed\' signal'
def changed(self):
self.callbacksSM.process('changed', self) for key in self.update_dict: self.update_dict[key] = True
'initialization delayed until first draw; allow time for axes setup.'
def _init(self):
if True: trans = self._set_transform() ax = self.ax (sx, sy) = trans.inverted().transform_point((ax.bbox.width, ax.bbox.height)) self.span = sx sn = max(8, min(25, math.sqrt(self.N))) if (self.width is None): self.width = ((0.06 * self.span) / sn)
'length is in arrow width units'
def _h_arrows(self, length):
minsh = (self.minshaft * self.headlength) N = len(length) length = length.reshape(N, 1) x = np.array([0, (- self.headaxislength), (- self.headlength), 0], np.float64) x = (x + (np.array([0, 1, 1, 1]) * length)) y = (0.5 * np.array([1, 1, self.headwidth, 0], np.float64)) y = np.repeat(y[np.newaxis, :], N, axis=0) x0 = np.array([0, (minsh - self.headaxislength), (minsh - self.headlength), minsh], np.float64) y0 = (0.5 * np.array([1, 1, self.headwidth, 0], np.float64)) ii = [0, 1, 2, 3, 2, 1, 0] X = x.take(ii, 1) Y = y.take(ii, 1) Y[:, 3:] *= (-1) X0 = x0.take(ii) Y0 = y0.take(ii) Y0[3:] *= (-1) shrink = (length / minsh) X0 = (shrink * X0[np.newaxis, :]) Y0 = (shrink * Y0[np.newaxis, :]) short = np.repeat((length < minsh), 7, axis=1) X = ma.where(short, X0, X) Y = ma.where(short, Y0, Y) if (self.pivot[:3] == 'mid'): X -= (0.5 * X[:, 3, np.newaxis]) elif (self.pivot[:3] == 'tip'): X = (X - X[:, 3, np.newaxis]) tooshort = (length < self.minlength) if tooshort.any(): th = (np.arange(0, 7, 1, np.float64) * (np.pi / 3.0)) x1 = ((np.cos(th) * self.minlength) * 0.5) y1 = ((np.sin(th) * self.minlength) * 0.5) X1 = np.repeat(x1[np.newaxis, :], N, axis=0) Y1 = np.repeat(y1[np.newaxis, :], N, axis=0) tooshort = ma.repeat(tooshort, 7, 1) X = ma.where(tooshort, X1, X) Y = ma.where(tooshort, Y1, Y) return (X, Y)
'Find how many of each of the tail pieces is necessary. Flag specifies the increment for a flag, barb for a full barb, and half for half a barb. Mag should be the magnitude of a vector (ie. >= 0). This returns a tuple of: (*number of flags*, *number of barbs*, *half_flag*, *empty_flag*) *half_flag* is a boolean whether half of a barb is needed, since there should only ever be one half on a given barb. *empty_flag* flag is an array of flags to easily tell if a barb is empty (too low to plot any barbs/flags.'
def _find_tails(self, mag, rounding=True, half=5, full=10, flag=50):
if rounding: mag = (half * ((mag / half) + 0.5).astype(np.int)) num_flags = np.floor((mag / flag)).astype(np.int) mag = np.mod(mag, flag) num_barb = np.floor((mag / full)).astype(np.int) mag = np.mod(mag, full) half_flag = (mag >= half) empty_flag = (~ ((half_flag | (num_flags > 0)) | (num_barb > 0))) return (num_flags, num_barb, half_flag, empty_flag)
'This function actually creates the wind barbs. *u* and *v* are components of the vector in the *x* and *y* directions, respectively. *nflags*, *nbarbs*, and *half_barb*, empty_flag* are, *respectively, the number of flags, number of barbs, flag for *half a barb, and flag for empty barb, ostensibly obtained *from :meth:`_find_tails`. *length* is the length of the barb staff in points. *pivot* specifies the point on the barb around which the entire barb should be rotated. Right now, valid options are \'head\' and \'middle\'. *sizes* is a dictionary of coefficients specifying the ratio of a given feature to the length of the barb. These features include: - *spacing*: space between features (flags, full/half barbs) - *height*: distance from shaft of top of a flag or full barb - *width* - width of a flag, twice the width of a full barb - *emptybarb* - radius of the circle used for low magnitudes *fill_empty* specifies whether the circle representing an empty barb should be filled or not (this changes the drawing of the polygon). *flip* is a flag indicating whether the features should be flipped to the other side of the barb (useful for winds in the southern hemisphere. This function returns list of arrays of vertices, defining a polygon for each of the wind barbs. These polygons have been rotated to properly align with the vector direction.'
def _make_barbs(self, u, v, nflags, nbarbs, half_barb, empty_flag, length, pivot, sizes, fill_empty, flip):
spacing = (length * sizes.get('spacing', 0.125)) full_height = (length * sizes.get('height', 0.4)) full_width = (length * sizes.get('width', 0.25)) empty_rad = (length * sizes.get('emptybarb', 0.15)) pivot_points = dict(tip=0.0, middle=((- length) / 2.0)) if flip: full_height = (- full_height) endx = 0.0 endy = pivot_points[pivot.lower()] angles = (- (ma.arctan2(v, u) + (np.pi / 2))) circ = CirclePolygon((0, 0), radius=empty_rad).get_verts() if fill_empty: empty_barb = circ else: empty_barb = np.concatenate((circ, circ[::(-1)])) barb_list = [] for (index, angle) in np.ndenumerate(angles): if empty_flag[index]: barb_list.append(empty_barb) continue poly_verts = [(endx, endy)] offset = length for i in range(nflags[index]): if (offset != length): offset += (spacing / 2.0) poly_verts.extend([[endx, (endy + offset)], [(endx + full_height), ((endy - (full_width / 2)) + offset)], [endx, ((endy - full_width) + offset)]]) offset -= (full_width + spacing) for i in range(nbarbs[index]): poly_verts.extend([(endx, (endy + offset)), ((endx + full_height), ((endy + offset) + (full_width / 2))), (endx, (endy + offset))]) offset -= spacing if half_barb[index]: if (offset == length): poly_verts.append((endx, (endy + offset))) offset -= (1.5 * spacing) poly_verts.extend([(endx, (endy + offset)), ((endx + (full_height / 2)), ((endy + offset) + (full_width / 4))), (endx, (endy + offset))]) poly_verts = transforms.Affine2D().rotate((- angle)).transform(poly_verts) barb_list.append(poly_verts) return barb_list
'Set the offsets for the barb polygons. This saves the offets passed in and actually sets version masked as appropriate for the existing U/V data. *offsets* should be a sequence. ACCEPTS: sequence of pairs of floats'
def set_offsets(self, xy):
self.x = xy[:, 0] self.y = xy[:, 1] (x, y, u, v) = delete_masked_points(self.x.ravel(), self.y.ravel(), self.u, self.v) xy = np.hstack((x[:, np.newaxis], y[:, np.newaxis])) collections.PolyCollection.set_offsets(self, xy)
'valid is a list of legal strings'
def __init__(self, key, valid, ignorecase=False):
self.key = key self.ignorecase = ignorecase def func(s): if ignorecase: return s.lower() else: return s self.valid = dict([(func(k), k) for k in valid])
'return a seq of n floats or raise'
def __call__(self, s):
if (type(s) is str): ss = s.split(',') if (len(ss) != self.n): raise ValueError(('You must supply exactly %d comma separated values' % self.n)) try: return [float(val) for val in ss] except ValueError: raise ValueError('Could not convert all entries to floats') else: assert (type(s) in (list, tuple)) if (len(s) != self.n): raise ValueError(('You must supply exactly %d values' % self.n)) return [float(val) for val in s]
'return a seq of n ints or raise'
def __call__(self, s):
if (type(s) is str): ss = s.split(',') if (len(ss) != self.n): raise ValueError(('You must supply exactly %d comma separated values' % self.n)) try: return [int(val) for val in ss] except ValueError: raise ValueError('Could not convert all entries to ints') else: assert (type(s) in (list, tuple)) if (len(s) != self.n): raise ValueError(('You must supply exactly %d values' % self.n)) return [int(val) for val in s]
'Register a new set of projection(s).'
def register(self, *projections):
for projection in projections: name = projection.name self._all_projection_types[name] = projection
'Get a projection class from its *name*.'
def get_projection_class(self, name):
return self._all_projection_types[name]
'Get a list of the names of all projections currently registered.'
def get_projection_names(self):
names = self._all_projection_types.keys() names.sort() return names
'Create a new polar transform. Resolution is the number of steps to interpolate between each input line segment to approximate its path in curved polar space.'
def __init__(self, resolution):
Transform.__init__(self) self._resolution = resolution
'return a format string formatting the coordinate'
def format_coord(self, long, lat):
long = (long * (180.0 / np.pi)) lat = (lat * (180.0 / np.pi)) if (lat >= 0.0): ns = 'N' else: ns = 'S' if (long >= 0.0): ew = 'E' else: ew = 'W' return (u'%f\xb0%s, %f\xb0%s' % (abs(lat), ns, abs(long), ew))
'Set the number of degrees between each longitude grid.'
def set_longitude_grid(self, degrees):
number = ((360.0 / degrees) + 1) self.xaxis.set_major_locator(FixedLocator(np.linspace((- np.pi), np.pi, number, True)[1:(-1)])) self._logitude_degrees = degrees self.xaxis.set_major_formatter(self.ThetaFormatter(degrees))
'Set the number of degrees between each longitude grid.'
def set_latitude_grid(self, degrees):
number = ((180.0 / degrees) + 1) self.yaxis.set_major_locator(FixedLocator(np.linspace(((- np.pi) / 2.0), (np.pi / 2.0), number, True)[1:(-1)])) self._latitude_degrees = degrees self.yaxis.set_major_formatter(self.ThetaFormatter(degrees))
'Set the latitude(s) at which to stop drawing the longitude grids.'
def set_longitude_grid_ends(self, degrees):
self._longitude_cap = (degrees * (np.pi / 180.0)) self._xaxis_pretransform.clear().scale(1.0, (self._longitude_cap * 2.0)).translate(0.0, (- self._longitude_cap))
'Return the aspect ratio of the data itself.'
def get_data_ratio(self):
return 1.0
'Return True if this axes support the zoom box'
def can_zoom(self):
return False
'Create a new Aitoff transform. Resolution is the number of steps to interpolate between each input line segment to approximate its path in curved Aitoff space.'
def __init__(self, resolution):
Transform.__init__(self) self._resolution = resolution
'Create a new Hammer transform. Resolution is the number of steps to interpolate between each input line segment to approximate its path in curved Hammer space.'
def __init__(self, resolution):
Transform.__init__(self) self._resolution = resolution
'Create a new Mollweide transform. Resolution is the number of steps to interpolate between each input line segment to approximate its path in curved Mollweide space.'
def __init__(self, resolution):
Transform.__init__(self) self._resolution = resolution
'Create a new Lambert transform. Resolution is the number of steps to interpolate between each input line segment to approximate its path in curved Lambert space.'
def __init__(self, center_longitude, center_latitude, resolution):
Transform.__init__(self) self._resolution = resolution self._center_longitude = center_longitude self._center_latitude = center_latitude
'All dimensions are fraction of the figure width or height. All values default to their rc params The following attributes are available *left* = 0.125 the left side of the subplots of the figure *right* = 0.9 the right side of the subplots of the figure *bottom* = 0.1 the bottom of the subplots of the figure *top* = 0.9 the top of the subplots of the figure *wspace* = 0.2 the amount of width reserved for blank space between subplots *hspace* = 0.2 the amount of height reserved for white space between subplots *validate* make sure the params are in a legal state (*left*<*right*, etc)'
def __init__(self, left=None, bottom=None, right=None, top=None, wspace=None, hspace=None):
self.validate = True self.update(left, bottom, right, top, wspace, hspace)
'Update the current values. If any kwarg is None, default to the current value, if set, otherwise to rc'
def update(self, left=None, bottom=None, right=None, top=None, wspace=None, hspace=None):
thisleft = getattr(self, 'left', None) thisright = getattr(self, 'right', None) thistop = getattr(self, 'top', None) thisbottom = getattr(self, 'bottom', None) thiswspace = getattr(self, 'wspace', None) thishspace = getattr(self, 'hspace', None) self._update_this('left', left) self._update_this('right', right) self._update_this('bottom', bottom) self._update_this('top', top) self._update_this('wspace', wspace) self._update_this('hspace', hspace) def reset(): self.left = thisleft self.right = thisright self.top = thistop self.bottom = thisbottom self.wspace = thiswspace self.hspace = thishspace if self.validate: if (self.left >= self.right): reset() raise ValueError('left cannot be >= right') if (self.bottom >= self.top): reset() raise ValueError('bottom cannot be >= top')
'*figsize* w,h tuple in inches *dpi* dots per inch *facecolor* the figure patch facecolor; defaults to rc ``figure.facecolor`` *edgecolor* the figure patch edge color; defaults to rc ``figure.edgecolor`` *linewidth* the figure patch edge linewidth; the default linewidth of the frame *frameon* if False, suppress drawing the figure frame *subplotpars* a :class:`SubplotParams` instance, defaults to rc'
def __init__(self, figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=1.0, frameon=True, subplotpars=None):
Artist.__init__(self) self.callbacks = cbook.CallbackRegistry(('dpi_changed',)) if (figsize is None): figsize = rcParams['figure.figsize'] if (dpi is None): dpi = rcParams['figure.dpi'] if (facecolor is None): facecolor = rcParams['figure.facecolor'] if (edgecolor is None): edgecolor = rcParams['figure.edgecolor'] self.dpi_scale_trans = Affine2D() self.dpi = dpi self.bbox_inches = Bbox.from_bounds(0, 0, *figsize) self.bbox = TransformedBbox(self.bbox_inches, self.dpi_scale_trans) self.frameon = frameon self.transFigure = BboxTransformTo(self.bbox) self.patch = self.figurePatch = Rectangle(xy=(0, 0), width=1, height=1, facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth) self._set_artist_props(self.patch) self._hold = rcParams['axes.hold'] self.canvas = None if (subplotpars is None): subplotpars = SubplotParams() self.subplotpars = subplotpars self._axstack = Stack() self.axes = [] self.clf() self._cachedRenderer = None
'Date ticklabels often overlap, so it is useful to rotate them and right align them. Also, a common use case is a number of subplots with shared xaxes where the x-axis is date data. The ticklabels are often long, and it helps to rotate them on the bottom subplot and turn them off on other subplots, as well as turn off xlabels. *bottom* the bottom of the subplots for :meth:`subplots_adjust` *rotation* the rotation of the xtick labels *ha* the horizontal alignment of the xticklabels'
def autofmt_xdate(self, bottom=0.2, rotation=30, ha='right'):
allsubplots = np.alltrue([hasattr(ax, 'is_last_row') for ax in self.axes]) if (len(self.axes) == 1): for label in ax.get_xticklabels(): label.set_ha(ha) label.set_rotation(rotation) elif allsubplots: for ax in self.get_axes(): if ax.is_last_row(): for label in ax.get_xticklabels(): label.set_ha(ha) label.set_rotation(rotation) else: for label in ax.get_xticklabels(): label.set_visible(False) ax.set_xlabel('') if allsubplots: self.subplots_adjust(bottom=bottom)
'get a list of artists contained in the figure'
def get_children(self):
children = [self.patch] children.extend(self.artists) children.extend(self.axes) children.extend(self.lines) children.extend(self.patches) children.extend(self.texts) children.extend(self.images) children.extend(self.legends) return children
'Test whether the mouse event occurred on the figure. Returns True,{}'
def contains(self, mouseevent):
if callable(self._contains): return self._contains(self, mouseevent) inside = self.bbox.contains(mouseevent.x, mouseevent.y) return (inside, {})
'get the figure bounding box in display space; kwargs are void'
def get_window_extent(self, *args, **kwargs):
return self.bbox
'Add a centered title to the figure. kwargs are :class:`matplotlib.text.Text` properties. Using figure coordinates, the defaults are: - *x* = 0.5 the x location of text in figure coords - *y* = 0.98 the y location of the text in figure coords - *horizontalalignment* = \'center\' the horizontal alignment of the text - *verticalalignment* = \'top\' the vertical alignment of the text A :class:`matplotlib.text.Text` instance is returned. Example:: fig.subtitle(\'this is the figure title\', fontsize=12)'
def suptitle(self, t, **kwargs):
x = kwargs.pop('x', 0.5) y = kwargs.pop('y', 0.98) if (('horizontalalignment' not in kwargs) and ('ha' not in kwargs)): kwargs['horizontalalignment'] = 'center' if (('verticalalignment' not in kwargs) and ('va' not in kwargs)): kwargs['verticalalignment'] = 'top' t = self.text(x, y, t, **kwargs) return t
'Set the canvas the contains the figure ACCEPTS: a FigureCanvas instance'
def set_canvas(self, canvas):
self.canvas = canvas
'Set the hold state. If hold is None (default), toggle the hold state. Else set the hold state to boolean value b. Eg:: hold() # toggle hold hold(True) # hold is on hold(False) # hold is off'
def hold(self, b=None):
if (b is None): self._hold = (not self._hold) else: self._hold = b
'call signatures:: figimage(X, **kwargs) adds a non-resampled array *X* to the figure. figimage(X, xo, yo) with pixel offsets *xo*, *yo*, *X* must be a float array: * If *X* is MxN, assume luminance (grayscale) * If *X* is MxNx3, assume RGB * If *X* is MxNx4, assume RGBA Optional keyword arguments: Keyword Description xo or yo An integer, the *x* and *y* image offset in pixels cmap a :class:`matplotlib.cm.ColorMap` instance, eg cm.jet. If None, default to the rc ``image.cmap`` value norm a :class:`matplotlib.colors.Normalize` instance. The default is normalization(). This scales luminance -> 0-1 vmin|vmax are used to scale a luminance image to 0-1. If either is None, the min and max of the luminance values will be used. Note if you pass a norm instance, the settings for *vmin* and *vmax* will be ignored. alpha the alpha blending value, default is 1.0 origin [ \'upper\' | \'lower\' ] Indicates where the [0,0] index of the array is in the upper left or lower left corner of the axes. Defaults to the rc image.origin value figimage complements the axes image (:meth:`~matplotlib.axes.Axes.imshow`) which will be resampled to fit the current axes. If you want a resampled image to fill the entire figure, you can define an :class:`~matplotlib.axes.Axes` with size [0,1,0,1]. An :class:`matplotlib.image.FigureImage` instance is returned. .. plot:: mpl_examples/pylab_examples/figimage_demo.py'
def figimage(self, X, xo=0, yo=0, alpha=1.0, norm=None, cmap=None, vmin=None, vmax=None, origin=None):
if (not self._hold): self.clf() im = FigureImage(self, cmap, norm, xo, yo, origin) im.set_array(X) im.set_alpha(alpha) if (norm is None): im.set_clim(vmin, vmax) self.images.append(im) return im
'set_size_inches(w,h, forward=False) Set the figure size in inches Usage:: fig.set_size_inches(w,h) # OR fig.set_size_inches((w,h) ) optional kwarg *forward=True* will cause the canvas size to be automatically updated; eg you can resize the figure window from the shell WARNING: forward=True is broken on all backends except GTK* and WX* ACCEPTS: a w,h tuple with w,h in inches'
def set_size_inches(self, *args, **kwargs):
forward = kwargs.get('forward', False) if (len(args) == 1): (w, h) = args[0] else: (w, h) = args dpival = self.dpi self.bbox_inches.p1 = (w, h) if forward: dpival = self.dpi canvasw = (w * dpival) canvash = (h * dpival) manager = getattr(self.canvas, 'manager', None) if (manager is not None): manager.resize(int(canvasw), int(canvash))
'Get the edge color of the Figure rectangle'
def get_edgecolor(self):
return self.patch.get_edgecolor()
'Get the face color of the Figure rectangle'
def get_facecolor(self):
return self.patch.get_facecolor()
'Return the figwidth as a float'
def get_figwidth(self):
return self.bbox_inches.width
'Return the figheight as a float'
def get_figheight(self):
return self.bbox_inches.height
'Return the dpi as a float'
def get_dpi(self):
return self.dpi
'get the boolean indicating frameon'
def get_frameon(self):
return self.frameon
'Set the edge color of the Figure rectangle ACCEPTS: any matplotlib color - see help(colors)'
def set_edgecolor(self, color):
self.patch.set_edgecolor(color)
'Set the face color of the Figure rectangle ACCEPTS: any matplotlib color - see help(colors)'
def set_facecolor(self, color):
self.patch.set_facecolor(color)
'Set the dots-per-inch of the figure ACCEPTS: float'
def set_dpi(self, val):
self.dpi = val
'Set the width of the figure in inches ACCEPTS: float'
def set_figwidth(self, val):
self.bbox_inches.x1 = val
'Set the height of the figure in inches ACCEPTS: float'
def set_figheight(self, val):
self.bbox_inches.y1 = val
'Set whether the figure frame (background) is displayed or invisible ACCEPTS: boolean'
def set_frameon(self, b):
self.frameon = b
'remove a from the figure and update the current axes'
def delaxes(self, a):
self.axes.remove(a) self._axstack.remove(a) keys = [] for (key, thisax) in self._seen.items(): if (a == thisax): del self._seen[key] for func in self._axobservers: func(self)
'make a hashable key out of args and kwargs'
def _make_key(self, *args, **kwargs):
def fixitems(items): ret = [] for (k, v) in items: if iterable(v): v = tuple(v) ret.append((k, v)) return tuple(ret) def fixlist(args): ret = [] for a in args: if iterable(a): a = tuple(a) ret.append(a) return tuple(ret) key = (fixlist(args), fixitems(kwargs.items())) return key
'Add an a axes with axes rect [*left*, *bottom*, *width*, *height*] where all quantities are in fractions of figure width and height. kwargs are legal :class:`~matplotlib.axes.Axes` kwargs plus *projection* which sets the projection type of the axes. (For backward compatibility, ``polar=True`` may also be provided, which is equivalent to ``projection=\'polar\'``). Valid values for *projection* are: %(list)s. Some of these projections support additional kwargs, which may be provided to :meth:`add_axes`:: rect = l,b,w,h fig.add_axes(rect) fig.add_axes(rect, frameon=False, axisbg=\'g\') fig.add_axes(rect, polar=True) fig.add_axes(rect, projection=\'polar\') fig.add_axes(ax) # add an Axes instance If the figure already has an axes with the same parameters, then it will simply make that axes current and return it. If you do not want this behavior, eg. you want to force the creation of a new axes, you must use a unique set of args and kwargs. The axes :attr:`~matplotlib.axes.Axes.label` attribute has been exposed for this purpose. Eg., if you want two axes that are otherwise identical to be added to the figure, make sure you give them unique labels:: fig.add_axes(rect, label=\'axes1\') fig.add_axes(rect, label=\'axes2\') The :class:`~matplotlib.axes.Axes` instance will be returned. The following kwargs are supported: %(Axes)s'
def add_axes(self, *args, **kwargs):
key = self._make_key(*args, **kwargs) if (key in self._seen): ax = self._seen[key] self.sca(ax) return ax if (not len(args)): return if isinstance(args[0], Axes): a = args[0] assert (a.get_figure() is self) else: rect = args[0] ispolar = kwargs.pop('polar', False) projection = kwargs.pop('projection', None) if ispolar: if ((projection is not None) and (projection != 'polar')): raise ValueError(("polar=True, yet projection='%s'. " + ('Only one of these arguments should be supplied.' % projection))) projection = 'polar' a = projection_factory(projection, self, rect, **kwargs) self.axes.append(a) self._axstack.push(a) self.sca(a) self._seen[key] = a return a
'Add a subplot. Examples: fig.add_subplot(111) fig.add_subplot(1,1,1) # equivalent but more general fig.add_subplot(212, axisbg=\'r\') # add subplot with red background fig.add_subplot(111, polar=True) # add a polar subplot fig.add_subplot(sub) # add Subplot instance sub *kwargs* are legal :class:`!matplotlib.axes.Axes` kwargs plus *projection*, which chooses a projection type for the axes. (For backward compatibility, *polar=True* may also be provided, which is equivalent to *projection=\'polar\'*). Valid values for *projection* are: %(list)s. Some of these projections support additional *kwargs*, which may be provided to :meth:`add_axes`. The :class:`~matplotlib.axes.Axes` instance will be returned. If the figure already has a subplot with key (*args*, *kwargs*) then it will simply make that subplot current and return it. The following kwargs are supported: %(Axes)s'
def add_subplot(self, *args, **kwargs):
kwargs = kwargs.copy() if (not len(args)): return if isinstance(args[0], SubplotBase): a = args[0] assert (a.get_figure() is self) else: ispolar = kwargs.pop('polar', False) projection = kwargs.pop('projection', None) if ispolar: if ((projection is not None) and (projection != 'polar')): raise ValueError(("polar=True, yet projection='%s'. " + ('Only one of these arguments should be supplied.' % projection))) projection = 'polar' projection_class = get_projection_class(projection) key = self._make_key(*args, **kwargs) if (key in self._seen): ax = self._seen[key] if isinstance(ax, projection_class): self.sca(ax) return ax else: self.axes.remove(ax) self._axstack.remove(ax) a = subplot_class_factory(projection_class)(self, *args, **kwargs) self._seen[key] = a self.axes.append(a) self._axstack.push(a) self.sca(a) return a
'Clear the figure'
def clf(self):
self.suppressComposite = None self.callbacks = cbook.CallbackRegistry(('dpi_changed',)) for ax in tuple(self.axes): ax.cla() self.delaxes(ax) toolbar = getattr(self.canvas, 'toolbar', None) if (toolbar is not None): toolbar.update() self._axstack.clear() self._seen = {} self.artists = [] self.lines = [] self.patches = [] self.texts = [] self.images = [] self.legends = [] self._axobservers = []
'Clear the figure -- synonym for fig.clf'
def clear(self):
self.clf()
'Render the figure using :class:`matplotlib.backend_bases.RendererBase` instance renderer'
def draw(self, renderer):
if (not self.get_visible()): return renderer.open_group('figure') if self.frameon: self.patch.draw(renderer) for p in self.patches: p.draw(renderer) for l in self.lines: l.draw(renderer) for a in self.artists: a.draw(renderer) composite = renderer.option_image_nocomposite() if (self.suppressComposite is not None): composite = self.suppressComposite if ((len(self.images) <= 1) or composite or (not allequal([im.origin for im in self.images]))): for im in self.images: im.draw(renderer) else: mag = renderer.get_image_magnification() ims = [(im.make_image(mag), im.ox, im.oy) for im in self.images] im = _image.from_images((self.bbox.height * mag), (self.bbox.width * mag), ims) im.is_grayscale = False (l, b, w, h) = self.bbox.bounds (clippath, affine) = self.get_transformed_clip_path_and_affine() renderer.draw_image(l, b, im, self.bbox, clippath, affine) for a in self.axes: a.draw(renderer) for t in self.texts: t.draw(renderer) for legend in self.legends: legend.draw(renderer) renderer.close_group('figure') self._cachedRenderer = renderer self.canvas.draw_event(renderer)
'draw :class:`matplotlib.artist.Artist` instance *a* only -- this is available only after the figure is drawn'
def draw_artist(self, a):
assert (self._cachedRenderer is not None) a.draw(self._cachedRenderer)
'Place a legend in the figure. Labels are a sequence of strings, handles is a sequence of :class:`~matplotlib.lines.Line2D` or :class:`~matplotlib.patches.Patch` instances, and loc can be a string or an integer specifying the legend location USAGE:: legend( (line1, line2, line3), (\'label1\', \'label2\', \'label3\'), \'upper right\') The *loc* location codes are:: \'best\' : 0, (currently not supported for figure legends) \'upper right\' : 1, \'upper left\' : 2, \'lower left\' : 3, \'lower right\' : 4, \'right\' : 5, \'center left\' : 6, \'center right\' : 7, \'lower center\' : 8, \'upper center\' : 9, \'center\' : 10, *loc* can also be an (x,y) tuple in figure coords, which specifies the lower left of the legend box. figure coords are (0,0) is the left, bottom of the figure and 1,1 is the right, top. The legend instance is returned. The following kwargs are supported *loc* the location of the legend *numpoints* the number of points in the legend line *prop* a :class:`matplotlib.font_manager.FontProperties` instance *pad* the fractional whitespace inside the legend border *markerscale* the relative size of legend markers vs. original *shadow* if True, draw a shadow behind legend *labelsep* the vertical space between the legend entries *handlelen* the length of the legend lines *handletextsep* the space between the legend line and legend text *axespad* the border between the axes and legend edge .. plot:: mpl_examples/pylab_examples/figlegend_demo.py'
def legend(self, handles, labels, *args, **kwargs):
handles = flatten(handles) l = Legend(self, handles, labels, *args, **kwargs) self.legends.append(l) return l
'Call signature:: figtext(x, y, s, fontdict=None, **kwargs) Add text to figure at location *x*, *y* (relative 0-1 coords). See :func:`~matplotlib.pyplot.text` for the meaning of the other arguments. kwargs control the :class:`~matplotlib.text.Text` properties: %(Text)s'
def text(self, x, y, s, *args, **kwargs):
override = _process_text_args({}, *args, **kwargs) t = Text(x=x, y=y, text=s) t.update(override) self._set_artist_props(t) self.texts.append(t) return t
'Return the current axes, creating one if necessary The following kwargs are supported %(Axes)s'
def gca(self, **kwargs):
ax = self._axstack() if (ax is not None): ispolar = kwargs.get('polar', False) projection = kwargs.get('projection', None) if ispolar: if ((projection is not None) and (projection != 'polar')): raise ValueError(("polar=True, yet projection='%s'. " + ('Only one of these arguments should be supplied.' % projection))) projection = 'polar' projection_class = get_projection_class(projection) if isinstance(ax, projection_class): return ax return self.add_subplot(111, **kwargs)
'Set the current axes to be a and return a'
def sca(self, a):
self._axstack.bubble(a) for func in self._axobservers: func(self) return a
'whenever the axes state change, func(self) will be called'
def add_axobserver(self, func):
self._axobservers.append(func)
'call signature:: savefig(fname, dpi=None, facecolor=\'w\', edgecolor=\'w\', orientation=\'portrait\', papertype=None, format=None, transparent=False): Save the current figure. The output formats available depend on the backend being used. Arguments: *fname*: A string containing a path to a filename, or a Python file-like object. If *format* is *None* and *fname* is a string, the output format is deduced from the extension of the filename. Keyword arguments: *dpi*: [ None | scalar > 0 ] The resolution in dots per inch. If *None* it will default to the value ``savefig.dpi`` in the matplotlibrc file. *facecolor*, *edgecolor*: the colors of the figure rectangle *orientation*: [ \'landscape\' | \'portrait\' ] not supported on all backends; currently only on postscript output *papertype*: One of \'letter\', \'legal\', \'executive\', \'ledger\', \'a0\' through \'a10\', \'b0\' through \'b10\'. Only supported for postscript output. *format*: One of the file extensions supported by the active backend. Most backends support png, pdf, ps, eps and svg. *transparent*: If *True*, the figure patch and axes patches will all be transparent. This is useful, for example, for displaying a plot on top of a colored background on a web page. The transparency of these patches will be restored to their original values upon exit of this function.'
def savefig(self, *args, **kwargs):
for key in ('dpi', 'facecolor', 'edgecolor'): if (key not in kwargs): kwargs[key] = rcParams[('savefig.%s' % key)] transparent = kwargs.pop('transparent', False) if transparent: original_figure_alpha = self.patch.get_alpha() self.patch.set_alpha(0.0) original_axes_alpha = [] for ax in self.axes: patch = ax.patch original_axes_alpha.append(patch.get_alpha()) patch.set_alpha(0.0) self.canvas.print_figure(*args, **kwargs) if transparent: self.patch.set_alpha(original_figure_alpha) for (ax, alpha) in zip(self.axes, original_axes_alpha): ax.patch.set_alpha(alpha)
'fig.subplots_adjust(left=None, bottom=None, right=None, wspace=None, hspace=None) Update the :class:`SubplotParams` with *kwargs* (defaulting to rc where None) and update the subplot locations'
def subplots_adjust(self, *args, **kwargs):
self.subplotpars.update(*args, **kwargs) import matplotlib.axes for ax in self.axes: if (not isinstance(ax, matplotlib.axes.SubplotBase)): if ((ax._sharex is not None) and isinstance(ax._sharex, matplotlib.axes.SubplotBase)): ax._sharex.update_params() ax.set_position(ax._sharex.figbox) elif ((ax._sharey is not None) and isinstance(ax._sharey, matplotlib.axes.SubplotBase)): ax._sharey.update_params() ax.set_position(ax._sharey.figbox) else: ax.update_params() ax.set_position(ax.figbox)
'call signature:: ginput(self, n=1, timeout=30, show_clicks=True) Blocking call to interact with the figure. This will wait for *n* clicks from the user and return a list of the coordinates of each click. If *timeout* is zero or negative, does not timeout. If *n* is zero or negative, accumulate clicks until a middle click (or potentially both mouse buttons at once) terminates the input. Right clicking cancels last input. The keyboard can also be used to select points in case your mouse does not have one or more of the buttons. The delete and backspace keys act like right clicking (i.e., remove last point), the enter key terminates input and any other key (not already used by the window manager) selects a point.'
def ginput(self, n=1, timeout=30, show_clicks=True):
blocking_mouse_input = BlockingMouseInput(self) return blocking_mouse_input(n=n, timeout=timeout, show_clicks=show_clicks)
'call signature:: waitforbuttonpress(self, timeout=-1) Blocking call to interact with the figure. This will return True is a key was pressed, False if a mouse button was pressed and None if *timeout* was reached without either being pressed. If *timeout* is negative, does not timeout.'
def waitforbuttonpress(self, timeout=(-1)):
blocking_input = BlockingKeyMouseInput(self) return blocking_input(timeout=timeout)
'Create a :class:`~matplotlib.text.Text` instance at *x*, *y* with string *text*. Valid kwargs are %(Text)s'
def __init__(self, x=0, y=0, text='', color=None, verticalalignment='bottom', horizontalalignment='left', multialignment=None, fontproperties=None, rotation=None, linespacing=None, **kwargs):
Artist.__init__(self) self.cached = maxdict(5) (self._x, self._y) = (x, y) if (color is None): color = rcParams['text.color'] if (fontproperties is None): fontproperties = FontProperties() elif is_string_like(fontproperties): fontproperties = FontProperties(fontproperties) self.set_text(text) self.set_color(color) self._verticalalignment = verticalalignment self._horizontalalignment = horizontalalignment self._multialignment = multialignment self._rotation = rotation self._fontproperties = fontproperties self._bbox = None self._bbox_patch = None self._renderer = None if (linespacing is None): linespacing = 1.2 self._linespacing = linespacing self.update(kwargs)
'Test whether the mouse event occurred in the patch. In the case of text, a hit is true anywhere in the axis-aligned bounding-box containing the text. Returns True or False.'
def contains(self, mouseevent):
if callable(self._contains): return self._contains(self, mouseevent) if ((not self.get_visible()) or (self._renderer is None)): return (False, {}) (l, b, w, h) = self.get_window_extent().bounds r = (l + w) t = (b + h) xyverts = ((l, b), (l, t), (r, t), (r, b)) (x, y) = (mouseevent.x, mouseevent.y) inside = nxutils.pnpoly(x, y, xyverts) return (inside, {})
'get the (possibly unit converted) transformed x, y in display coords'
def _get_xy_display(self):
(x, y) = self.get_position() return self.get_transform().transform_point((x, y))
'return the text angle as float in degrees'
def get_rotation(self):
return get_rotation(self._rotation)
'Copy properties from other to self'
def update_from(self, other):
Artist.update_from(self, other) self._color = other._color self._multialignment = other._multialignment self._verticalalignment = other._verticalalignment self._horizontalalignment = other._horizontalalignment self._fontproperties = other._fontproperties.copy() self._rotation = other._rotation self._picker = other._picker self._linespacing = other._linespacing
'Draw a bounding box around self. rectprops are any settable properties for a rectangle, eg facecolor=\'red\', alpha=0.5. t.set_bbox(dict(facecolor=\'red\', alpha=0.5)) If rectprops has "boxstyle" key. A FancyBboxPatch is initialized with rectprops and will be drawn. The mutation scale of the FancyBboxPath is set to the fontsize. ACCEPTS: rectangle prop dict'
def set_bbox(self, rectprops):
if ((rectprops is not None) and ('boxstyle' in rectprops)): props = rectprops.copy() boxstyle = props.pop('boxstyle') bbox_transmuter = props.pop('bbox_transmuter', None) self._bbox_patch = FancyBboxPatch((0.0, 0.0), 1.0, 1.0, boxstyle=boxstyle, bbox_transmuter=bbox_transmuter, transform=mtransforms.IdentityTransform(), **props) self._bbox = None else: self._bbox_patch = None self._bbox = rectprops
'Return the bbox Patch object. Returns None if the the FancyBboxPatch is not made.'
def get_bbox_patch(self):
return self._bbox_patch
'Update the location and the size of the bbox. This method should be used when the position and size of the bbox needs to be updated before actually drawing the bbox.'
def update_bbox_position_size(self, renderer):
if (not isinstance(self.arrow_patch, FancyArrowPatch)): return if self._bbox_patch: trans = self.get_transform() posx = float(self.convert_xunits(self._x)) posy = float(self.convert_yunits(self._y)) (posx, posy) = trans.transform_point((posx, posy)) (x_box, y_box, w_box, h_box) = _get_textbox(self, renderer) self._bbox_patch.set_bounds(0.0, 0.0, w_box, h_box) theta = ((self.get_rotation() / 180.0) * math.pi) tr = mtransforms.Affine2D().rotate(theta) tr = tr.translate((posx + x_box), (posy + y_box)) self._bbox_patch.set_transform(tr) fontsize_in_pixel = renderer.points_to_pixels(self.get_size()) self._bbox_patch.set_mutation_scale(fontsize_in_pixel) else: props = self._bbox if (props is None): props = {} props = props.copy() pad = props.pop('pad', 4) pad = renderer.points_to_pixels(pad) bbox = self.get_window_extent(renderer) (l, b, w, h) = bbox.bounds l -= (pad / 2.0) b -= (pad / 2.0) w += pad h += pad r = Rectangle(xy=(l, b), width=w, height=h) r.set_transform(mtransforms.IdentityTransform()) r.set_clip_on(False) r.update(props) self.arrow_patch.set_patchA(r)
'Update the location and the size of the bbox (FancyBoxPatch), and draw'
def _draw_bbox(self, renderer, posx, posy):
(x_box, y_box, w_box, h_box) = _get_textbox(self, renderer) self._bbox_patch.set_bounds(0.0, 0.0, w_box, h_box) theta = ((self.get_rotation() / 180.0) * math.pi) tr = mtransforms.Affine2D().rotate(theta) tr = tr.translate((posx + x_box), (posy + y_box)) self._bbox_patch.set_transform(tr) fontsize_in_pixel = renderer.points_to_pixels(self.get_size()) self._bbox_patch.set_mutation_scale(fontsize_in_pixel) self._bbox_patch.draw(renderer)
'Draws the :class:`Text` object to the given *renderer*.'
def draw(self, renderer):
if (renderer is not None): self._renderer = renderer if (not self.get_visible()): return if (self._text == ''): return (bbox, info) = self._get_layout(renderer) trans = self.get_transform() posx = float(self.convert_xunits(self._x)) posy = float(self.convert_yunits(self._y)) (posx, posy) = trans.transform_point((posx, posy)) (canvasw, canvash) = renderer.get_canvas_width_height() if self._bbox_patch: self._draw_bbox(renderer, posx, posy) gc = renderer.new_gc() gc.set_foreground(self._color) gc.set_alpha(self._alpha) gc.set_url(self._url) if self.get_clip_on(): gc.set_clip_rectangle(self.clipbox) if self._bbox: bbox_artist(self, renderer, self._bbox) angle = self.get_rotation() if rcParams['text.usetex']: for (line, wh, x, y) in info: x = (x + posx) y = (y + posy) if renderer.flipy(): y = (canvash - y) (clean_line, ismath) = self.is_math_text(line) renderer.draw_tex(gc, x, y, clean_line, self._fontproperties, angle) return for (line, wh, x, y) in info: x = (x + posx) y = (y + posy) if renderer.flipy(): y = (canvash - y) (clean_line, ismath) = self.is_math_text(line) renderer.draw_text(gc, x, y, clean_line, self._fontproperties, angle, ismath=ismath)
'Return the color of the text'
def get_color(self):
return self._color
'Return the :class:`~font_manager.FontProperties` object'
def get_fontproperties(self):
return self._fontproperties
'alias for get_fontproperties'
def get_font_properties(self):
return self.get_fontproperties
'Return the list of font families used for font lookup'
def get_family(self):
return self._fontproperties.get_family()
'alias for get_family'
def get_fontfamily(self):
return self.get_family()
'Return the font name as string'
def get_name(self):
return self._fontproperties.get_name()
'Return the font style as string'
def get_style(self):
return self._fontproperties.get_style()
'Return the font size as integer'
def get_size(self):
return self._fontproperties.get_size_in_points()
'Return the font variant as a string'
def get_variant(self):
return self._fontproperties.get_variant()
'alias for get_variant'
def get_fontvariant(self):
return self.get_variant()
'Get the font weight as string or number'
def get_weight(self):
return self._fontproperties.get_weight()
'alias for get_name'
def get_fontname(self):
return self.get_name()