desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'select a scale for the range from vmin to vmax Normally This will be overridden.'
def view_limits(self, vmin, vmax):
return mtransforms.nonsingular(vmin, vmax)
'autoscale the view limits'
def autoscale(self):
return self.view_limits(*self.axis.get_view_interval())
'Pan numticks (can be positive or negative)'
def pan(self, numsteps):
ticks = self() numticks = len(ticks) (vmin, vmax) = self.axis.get_view_interval() (vmin, vmax) = mtransforms.nonsingular(vmin, vmax, expander=0.05) if (numticks > 2): step = (numsteps * abs((ticks[0] - ticks[1]))) else: d = abs((vmax - vmin)) step = ((numsteps * d) / 6.0) vmin += step vmax += step self.axis.set_view_interval(vmin, vmax, ignore=True)
'Zoom in/out on axis; if direction is >0 zoom in, else zoom out'
def zoom(self, direction):
(vmin, vmax) = self.axis.get_view_interval() (vmin, vmax) = mtransforms.nonsingular(vmin, vmax, expander=0.05) interval = abs((vmax - vmin)) step = ((0.1 * interval) * direction) self.axis.set_view_interval((vmin + step), (vmax - step), ignore=True)
'refresh internal information based on current lim'
def refresh(self):
pass
'place ticks on the i-th data points where (i-offset)%base==0'
def __init__(self, base, offset):
self._base = base self.offset = offset
'Return the locations of the ticks'
def __call__(self):
(dmin, dmax) = self.axis.get_data_interval() return np.arange((dmin + self.offset), (dmax + 1), self._base)
'Return the locations of the ticks'
def __call__(self):
if (self.nbins is None): return self.locs step = max(int((0.99 + (len(self.locs) / float(self.nbins)))), 1) return self.locs[::step]
'Return the locations of the ticks'
def __call__(self):
return []
'Use presets to set locs based on lom. A dict mapping vmin, vmax->locs'
def __init__(self, numticks=None, presets=None):
self.numticks = numticks if (presets is None): self.presets = {} else: self.presets = presets
'Return the locations of the ticks'
def __call__(self):
(vmin, vmax) = self.axis.get_view_interval() (vmin, vmax) = mtransforms.nonsingular(vmin, vmax, expander=0.05) if (vmax < vmin): (vmin, vmax) = (vmax, vmin) if ((vmin, vmax) in self.presets): return self.presets[(vmin, vmax)] if (self.numticks is None): self._set_numticks() if (self.numticks == 0): return [] ticklocs = np.linspace(vmin, vmax, self.numticks) return ticklocs
'Try to choose the view limits intelligently'
def view_limits(self, vmin, vmax):
if (vmax < vmin): (vmin, vmax) = (vmax, vmin) if (vmin == vmax): vmin -= 1 vmax += 1 (exponent, remainder) = divmod(math.log10((vmax - vmin)), 1) if (remainder < 0.5): exponent -= 1 scale = (10 ** (- exponent)) vmin = (math.floor((scale * vmin)) / scale) vmax = (math.ceil((scale * vmax)) / scale) return mtransforms.nonsingular(vmin, vmax)
'return the largest multiple of base < x'
def lt(self, x):
(d, m) = divmod(x, self._base) if (closeto(m, 0) and (not closeto((m / self._base), 1))): return ((d - 1) * self._base) return (d * self._base)
'return the largest multiple of base <= x'
def le(self, x):
(d, m) = divmod(x, self._base) if closeto((m / self._base), 1): return ((d + 1) * self._base) return (d * self._base)
'return the smallest multiple of base > x'
def gt(self, x):
(d, m) = divmod(x, self._base) if closeto((m / self._base), 1): return ((d + 2) * self._base) return ((d + 1) * self._base)
'return the smallest multiple of base >= x'
def ge(self, x):
(d, m) = divmod(x, self._base) if (closeto(m, 0) and (not closeto((m / self._base), 1))): return (d * self._base) return ((d + 1) * self._base)
'Return the locations of the ticks'
def __call__(self):
(vmin, vmax) = self.axis.get_view_interval() if (vmax < vmin): (vmin, vmax) = (vmax, vmin) vmin = self._base.ge(vmin) base = self._base.get_base() n = (((vmax - vmin) + (0.001 * base)) // base) locs = (vmin + (np.arange((n + 1)) * base)) return locs
'Set the view limits to the nearest multiples of base that contain the data'
def view_limits(self, dmin, dmax):
vmin = self._base.le(dmin) vmax = self._base.ge(dmax) if (vmin == vmax): vmin -= 1 vmax += 1 return mtransforms.nonsingular(vmin, vmax)
'place ticks on the location= base**i*subs[j]'
def __init__(self, base=10.0, subs=[1.0]):
self.base(base) self.subs(subs) self.numticks = 15
'set the base of the log scaling (major tick every base**i, i interger)'
def base(self, base):
self._base = (base + 0.0)
'set the minor ticks the log scaling every base**i*subs[j]'
def subs(self, subs):
if (subs is None): self._subs = None else: self._subs = (np.asarray(subs) + 0.0)
'Return the locations of the ticks'
def __call__(self):
b = self._base (vmin, vmax) = self.axis.get_view_interval() if (vmin <= 0.0): vmin = self.axis.get_minpos() if (vmin <= 0.0): raise ValueError('Data has no positive values, and therefore can not be log-scaled.') vmin = (math.log(vmin) / math.log(b)) vmax = (math.log(vmax) / math.log(b)) if (vmax < vmin): (vmin, vmax) = (vmax, vmin) numdec = (math.floor(vmax) - math.ceil(vmin)) if (self._subs is None): if (numdec > 10): subs = np.array([1.0]) elif (numdec > 6): subs = np.arange(2.0, b, 2.0) else: subs = np.arange(2.0, b) else: subs = self._subs stride = 1 while (((numdec / stride) + 1) > self.numticks): stride += 1 decades = np.arange(math.floor(vmin), (math.ceil(vmax) + stride), stride) if ((len(subs) > 1) or (len((subs == 1)) and (subs[0] != 1.0))): ticklocs = [] for decadeStart in (b ** decades): ticklocs.extend((subs * decadeStart)) else: ticklocs = (b ** decades) return np.array(ticklocs)
'Try to choose the view limits intelligently'
def view_limits(self, vmin, vmax):
if (vmax < vmin): (vmin, vmax) = (vmax, vmin) minpos = self.axis.get_minpos() if (minpos <= 0): raise ValueError('Data has no positive values, and therefore can not be log-scaled.') if (vmin <= minpos): vmin = minpos if (not is_decade(vmin, self._base)): vmin = decade_down(vmin, self._base) if (not is_decade(vmax, self._base)): vmax = decade_up(vmax, self._base) if (vmin == vmax): vmin = decade_down(vmin, self._base) vmax = decade_up(vmax, self._base) result = mtransforms.nonsingular(vmin, vmax) return result
'place ticks on the location= base**i*subs[j]'
def __init__(self, transform, subs=[1.0]):
self._transform = transform self._subs = subs self.numticks = 15
'Return the locations of the ticks'
def __call__(self):
b = self._transform.base (vmin, vmax) = self.axis.get_view_interval() (vmin, vmax) = self._transform.transform((vmin, vmax)) if (vmax < vmin): (vmin, vmax) = (vmax, vmin) numdec = (math.floor(vmax) - math.ceil(vmin)) if (self._subs is None): if (numdec > 10): subs = np.array([1.0]) elif (numdec > 6): subs = np.arange(2.0, b, 2.0) else: subs = np.arange(2.0, b) else: subs = np.asarray(self._subs) stride = 1 while (((numdec / stride) + 1) > self.numticks): stride += 1 decades = np.arange(math.floor(vmin), (math.ceil(vmax) + stride), stride) if ((len(subs) > 1) or (subs[0] != 1.0)): ticklocs = [] for decade in decades: ticklocs.extend((subs * (np.sign(decade) * (b ** np.abs(decade))))) else: ticklocs = (np.sign(decades) * (b ** np.abs(decades))) return np.array(ticklocs)
'Try to choose the view limits intelligently'
def view_limits(self, vmin, vmax):
b = self._transform.base if (vmax < vmin): (vmin, vmax) = (vmax, vmin) if (not is_decade(abs(vmin), b)): if (vmin < 0): vmin = (- decade_up((- vmin), b)) else: vmin = decade_down(vmin, b) if (not is_decade(abs(vmax), b)): if (vmax < 0): vmax = (- decade_down((- vmax), b)) else: vmax = decade_up(vmax, b) if (vmin == vmax): if (vmin < 0): vmin = (- decade_up((- vmin), b)) vmax = (- decade_down((- vmax), b)) else: vmin = decade_down(vmin, b) vmax = decade_up(vmax, b) result = mtransforms.nonsingular(vmin, vmax) return result
'Return the locations of the ticks'
def __call__(self):
self.refresh() return self._locator()
'refresh internal information based on current lim'
def refresh(self):
(vmin, vmax) = self.axis.get_view_interval() (vmin, vmax) = mtransforms.nonsingular(vmin, vmax, expander=0.05) d = abs((vmax - vmin)) self._locator = self.get_locator(d)
'Try to choose the view limits intelligently'
def view_limits(self, vmin, vmax):
d = abs((vmax - vmin)) self._locator = self.get_locator(d) return self._locator.view_limits(vmin, vmax)
'pick the best locator based on a distance'
def get_locator(self, d):
d = abs(d) if (d <= 0): locator = MultipleLocator(0.2) else: try: ld = math.log10(d) except OverflowError: raise RuntimeError('AutoLocator illegal data interval range') fld = math.floor(ld) base = (10 ** fld) if (d >= (5 * base)): ticksize = base elif (d >= (2 * base)): ticksize = (base / 2.0) else: ticksize = (base / 5.0) locator = MultipleLocator(ticksize) return locator
'Parse the given fontconfig *pattern* and return a dictionary of key/value pairs useful for initializing a :class:`font_manager.FontProperties` object.'
def parse(self, pattern):
props = self._properties = {} try: self._parser.parseString(pattern) except self.ParseException as e: raise ValueError(("Could not parse font string: '%s'\n%s" % (pattern, e))) self._properties = None return props
'Buffer up to *nmax* points.'
def __init__(self, nmax):
self._xa = np.zeros((nmax,), np.float_) self._ya = np.zeros((nmax,), np.float_) self._xs = np.zeros((nmax,), np.float_) self._ys = np.zeros((nmax,), np.float_) self._ind = 0 self._nmax = nmax self.dataLim = None self.callbackd = {}
'Call *func* every time *N* events are passed; *func* signature is ``func(fifo)``.'
def register(self, func, N):
self.callbackd.setdefault(N, []).append(func)
'Add scalar *x* and *y* to the queue.'
def add(self, x, y):
if (self.dataLim is not None): xys = ((x, y),) self.dataLim.update(xys, (-1)) ind = (self._ind % self._nmax) self._xs[ind] = x self._ys[ind] = y for (N, funcs) in self.callbackd.items(): if ((self._ind % N) == 0): for func in funcs: func(self) self._ind += 1
'Get the last *x*, *y* or *None*. *None* if no data set.'
def last(self):
if (self._ind == 0): return (None, None) ind = ((self._ind - 1) % self._nmax) return (self._xs[ind], self._ys[ind])
'Return *x* and *y* as arrays; their length will be the len of data added or *nmax*.'
def asarrays(self):
if (self._ind < self._nmax): return (self._xs[:self._ind], self._ys[:self._ind]) ind = (self._ind % self._nmax) self._xa[:(self._nmax - ind)] = self._xs[ind:] self._xa[(self._nmax - ind):] = self._xs[:ind] self._ya[:(self._nmax - ind)] = self._ys[ind:] self._ya[(self._nmax - ind):] = self._ys[:ind] return (self._xa, self._ya)
'Update the *datalim* in the current data in the fifo.'
def update_datalim_to_current(self):
if (self.dataLim is None): raise ValueError('You must first set the dataLim attr') (x, y) = self.asarrays() self.dataLim.update_numerix(x, y, True)
'Return a list of font names that comprise the font family.'
def get_family(self):
if (self._family is None): family = rcParams['font.family'] if is_string_like(family): return [family] return family return self._family
'Return the name of the font that best matches the font properties.'
def get_name(self):
return ft2font.FT2Font(str(findfont(self))).family_name
'Return the font style. Values are: \'normal\', \'italic\' or \'oblique\'.'
def get_style(self):
if (self._slant is None): return rcParams['font.style'] return self._slant
'Return the font variant. Values are: \'normal\' or \'small-caps\'.'
def get_variant(self):
if (self._variant is None): return rcParams['font.variant'] return self._variant
'Set the font weight. Options are: A numeric value in the range 0-1000 or one of \'light\', \'normal\', \'regular\', \'book\', \'medium\', \'roman\', \'semibold\', \'demibold\', \'demi\', \'bold\', \'heavy\', \'extra bold\', \'black\''
def get_weight(self):
if (self._weight is None): return rcParams['font.weight'] return self._weight
'Return the font stretch or width. Options are: \'ultra-condensed\', \'extra-condensed\', \'condensed\', \'semi-condensed\', \'normal\', \'semi-expanded\', \'expanded\', \'extra-expanded\', \'ultra-expanded\'.'
def get_stretch(self):
if (self._stretch is None): return rcParams['font.stretch'] return self._stretch
'Return the font size.'
def get_size(self):
if (self._size is None): return rcParams['font.size'] return self._size
'Return the filename of the associated font.'
def get_file(self):
return self._file
'Get a fontconfig pattern suitable for looking up the font as specified with fontconfig\'s ``fc-match`` utility. See the documentation on `fontconfig patterns <http://www.fontconfig.org/fontconfig-user.html>`_. This support does not require fontconfig to be installed or support for it to be enabled. We are merely borrowing its pattern syntax for use here.'
def get_fontconfig_pattern(self):
return generate_fontconfig_pattern(self)
'Change the font family. May be either an alias (generic name is CSS parlance), such as: \'serif\', \'sans-serif\', \'cursive\', \'fantasy\', or \'monospace\', or a real font name.'
def set_family(self, family):
if (family is None): self._family = None else: if is_string_like(family): family = [family] self._family = family
'Set the font style. Values are: \'normal\', \'italic\' or \'oblique\'.'
def set_style(self, style):
if (style not in ('normal', 'italic', 'oblique', None)): raise ValueError('style must be normal, italic or oblique') self._slant = style
'Set the font variant. Values are: \'normal\' or \'small-caps\'.'
def set_variant(self, variant):
if (variant not in ('normal', 'small-caps', None)): raise ValueError('variant must be normal or small-caps') self._variant = variant
'Set the font weight. May be either a numeric value in the range 0-1000 or one of \'ultralight\', \'light\', \'normal\', \'regular\', \'book\', \'medium\', \'roman\', \'semibold\', \'demibold\', \'demi\', \'bold\', \'heavy\', \'extra bold\', \'black\''
def set_weight(self, weight):
if (weight is not None): try: weight = int(weight) if ((weight < 0) or (weight > 1000)): raise ValueError() except ValueError: if (weight not in weight_dict): raise ValueError('weight is invalid') self._weight = weight
'Set the font stretch or width. Options are: \'ultra-condensed\', \'extra-condensed\', \'condensed\', \'semi-condensed\', \'normal\', \'semi-expanded\', \'expanded\', \'extra-expanded\' or \'ultra-expanded\', or a numeric value in the range 0-1000.'
def set_stretch(self, stretch):
if (stretch is not None): try: stretch = int(stretch) if ((stretch < 0) or (stretch > 1000)): raise ValueError() except ValueError: if (stretch not in stretch_dict): raise ValueError('stretch is invalid') self._stretch = stretch
'Set the font size. Either an relative value of \'xx-small\', \'x-small\', \'small\', \'medium\', \'large\', \'x-large\', \'xx-large\' or an absolute font size, e.g. 12.'
def set_size(self, size):
if (size is not None): try: size = float(size) except ValueError: if ((size is not None) and (size not in font_scalings)): raise ValueError('size is invalid') self._size = size
'Set the filename of the fontfile to use. In this case, all other properties will be ignored.'
def set_file(self, file):
self._file = file
'Set the properties by parsing a fontconfig *pattern*. See the documentation on `fontconfig patterns <http://www.fontconfig.org/fontconfig-user.html>`_. This support does not require fontconfig to be installed or support for it to be enabled. We are merely borrowing its pattern syntax for use here.'
def set_fontconfig_pattern(self, pattern):
for (key, val) in self._parse_fontconfig_pattern(pattern).items(): if (type(val) == list): getattr(self, ('set_' + key))(val[0]) else: getattr(self, ('set_' + key))(val)
'Return a deep copy of self'
def copy(self):
return FontProperties(_init=self)
'Return the default font weight.'
def get_default_weight(self):
return self.__default_weight
'Return the default font size.'
def get_default_size(self):
if (self.default_size is None): return rcParams['font.size'] return self.default_size
'Set the default font weight. The initial value is \'normal\'.'
def set_default_weight(self, weight):
self.__default_weight = weight
'Set the default font size in points. The initial value is set by ``font.size`` in rc.'
def set_default_size(self, size):
self.default_size = size
'Update the font dictionary with new font files. Currently not implemented.'
def update_fonts(self, filenames):
raise NotImplementedError
'Returns a match score between the list of font families in *families* and the font family name *family2*. An exact match anywhere in the list returns 0.0. A match by generic font name will return 0.1. No match will return 1.0.'
def score_family(self, families, family2):
for (i, family1) in enumerate(families): if (family1.lower() in font_family_aliases): if (family1 == 'sans'): (family1 == 'sans-serif') options = rcParams[('font.' + family1)] if (family2 in options): idx = options.index(family2) return (0.1 * (float(idx) / len(options))) elif (family1.lower() == family2.lower()): return 0.0 return 1.0
'Returns a match score between *style1* and *style2*. An exact match returns 0.0. A match between \'italic\' and \'oblique\' returns 0.1. No match returns 1.0.'
def score_style(self, style1, style2):
if (style1 == style2): return 0.0 elif ((style1 in ('italic', 'oblique')) and (style2 in ('italic', 'oblique'))): return 0.1 return 1.0
'Returns a match score between *variant1* and *variant2*. An exact match returns 0.0, otherwise 1.0.'
def score_variant(self, variant1, variant2):
if (variant1 == variant2): return 0.0 else: return 1.0
'Returns a match score between *stretch1* and *stretch2*. The result is the absolute value of the difference between the CSS numeric values of *stretch1* and *stretch2*, normalized between 0.0 and 1.0.'
def score_stretch(self, stretch1, stretch2):
try: stretchval1 = int(stretch1) except ValueError: stretchval1 = stretch_dict.get(stretch1, 500) try: stretchval2 = int(stretch2) except ValueError: stretchval2 = stretch_dict.get(stretch2, 500) return (abs((stretchval1 - stretchval2)) / 1000.0)
'Returns a match score between *weight1* and *weight2*. The result is the absolute value of the difference between the CSS numeric values of *weight1* and *weight2*, normalized between 0.0 and 1.0.'
def score_weight(self, weight1, weight2):
try: weightval1 = int(weight1) except ValueError: weightval1 = weight_dict.get(weight1, 500) try: weightval2 = int(weight2) except ValueError: weightval2 = weight_dict.get(weight2, 500) return (abs((weightval1 - weightval2)) / 1000.0)
'Returns a match score between *size1* and *size2*. If *size2* (the size specified in the font file) is \'scalable\', this function always returns 0.0, since any font size can be generated. Otherwise, the result is the absolute distance between *size1* and *size2*, normalized so that the usual range of font sizes (6pt - 72pt) will lie between 0.0 and 1.0.'
def score_size(self, size1, size2):
if (size2 == 'scalable'): return 0.0 try: sizeval1 = float(size1) except ValueError: sizeval1 = (self.default_size * font_scalings(size1)) try: sizeval2 = float(size2) except ValueError: return 1.0 return (abs((sizeval1 - sizeval2)) / 72.0)
'Search the font list for the font that most closely matches the :class:`FontProperties` *prop*. :meth:`findfont` performs a nearest neighbor search. Each font is given a similarity score to the target font properties. The first font with the highest score is returned. If no matches below a certain threshold are found, the default font (usually Vera Sans) is returned. The result is cached, so subsequent lookups don\'t have to perform the O(n) nearest neighbor search. See the `W3C Cascading Style Sheet, Level 1 <http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_ documentation for a description of the font finding algorithm.'
def findfont(self, prop, fontext='ttf'):
debug = False if (prop is None): return self.defaultFont if is_string_like(prop): prop = FontProperties(prop) fname = prop.get_file() if (fname is not None): verbose.report(('findfont returning %s' % fname), 'debug') return fname if (fontext == 'afm'): font_cache = self.afm_lookup_cache fontlist = self.afmlist else: font_cache = self.ttf_lookup_cache fontlist = self.ttflist cached = font_cache.get(hash(prop)) if cached: return cached best_score = 1e+64 best_font = None for font in fontlist: score = ((((((self.score_family(prop.get_family(), font.name) * 10.0) + self.score_style(prop.get_style(), font.style)) + self.score_variant(prop.get_variant(), font.variant)) + self.score_weight(prop.get_weight(), font.weight)) + self.score_stretch(prop.get_stretch(), font.stretch)) + self.score_size(prop.get_size(), font.size)) if (score < best_score): best_score = score best_font = font if (score == 0): break if ((best_font is None) or (best_score >= 10.0)): verbose.report(('findfont: Could not match %s. Returning %s' % (prop, self.defaultFont))) result = self.defaultFont else: verbose.report(('findfont: Matching %s to %s (%s) with score of %f' % (prop, best_font.name, best_font.fname, best_score))) result = best_font.fname font_cache[hash(prop)] = result return result
'- *parent* : the artist that contains the legend - *handles* : a list of artists (lines, patches) to add to the legend - *labels* : a list of strings to label the legend Optional keyword arguments: Keyword Description loc a location code or a tuple of coordinates numpoints the number of points in the legend line prop the font property markerscale the relative size of legend markers vs. original fancybox if True, draw a frame with a round fancybox. If None, use rc shadow if True, draw a shadow behind legend scatteryoffsets a list of yoffsets for scatter symbols in legend borderpad the fractional whitespace inside the legend border labelspacing the vertical space between the legend entries handlelength the length of the legend handles handletextpad the pad between the legend handle and text borderaxespad the pad between the axes and legend border columnspacing the spacing between columns The dimensions of pad and spacing are given as a fraction of the fontsize. Values from rcParams will be used if None.'
def __init__(self, parent, handles, labels, loc=None, numpoints=None, markerscale=None, scatterpoints=3, scatteryoffsets=None, prop=None, pad=None, labelsep=None, handlelen=None, handletextsep=None, axespad=None, borderpad=None, labelspacing=None, handlelength=None, handletextpad=None, borderaxespad=None, columnspacing=None, ncol=1, mode=None, fancybox=None, shadow=None):
from matplotlib.axes import Axes from matplotlib.figure import Figure Artist.__init__(self) if (prop is None): self.prop = FontProperties(size=rcParams['legend.fontsize']) else: self.prop = prop self.fontsize = self.prop.get_size_in_points() propnames = ['numpoints', 'markerscale', 'shadow', 'columnspacing', 'scatterpoints'] localdict = locals() for name in propnames: if (localdict[name] is None): value = rcParams[('legend.' + name)] else: value = localdict[name] setattr(self, name, value) deprecated_kwds = {'pad': 'borderpad', 'labelsep': 'labelspacing', 'handlelen': 'handlelength', 'handletextsep': 'handletextpad', 'axespad': 'borderaxespad'} bbox = parent.bbox axessize_fontsize = (min(bbox.width, bbox.height) / self.fontsize) for (k, v) in deprecated_kwds.items(): if ((localdict[k] is not None) and (localdict[v] is None)): warnings.warn(("Use '%s' instead of '%s'." % (v, k)), DeprecationWarning) setattr(self, v, (localdict[k] * axessize_fontsize)) continue if (localdict[v] is None): setattr(self, v, rcParams[('legend.' + v)]) else: setattr(self, v, localdict[v]) del localdict self._ncol = ncol if (self.numpoints <= 0): raise ValueError(('numpoints must be >= 0; it was %d' % numpoints)) if (scatteryoffsets is None): self._scatteryoffsets = np.array([(3.0 / 8.0), (4.0 / 8.0), (2.5 / 8.0)]) else: self._scatteryoffsets = np.asarray(scatteryoffsets) reps = (int((self.numpoints / len(self._scatteryoffsets))) + 1) self._scatteryoffsets = np.tile(self._scatteryoffsets, reps)[:self.scatterpoints] self._legend_box = None if isinstance(parent, Axes): self.isaxes = True 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 if (loc is None): loc = rcParams['legend.loc'] if ((not self.isaxes) and (loc in [0, 'best'])): loc = 'upper right' if is_string_like(loc): if (loc not in self.codes): if self.isaxes: warnings.warn(('Unrecognized location "%s". Falling back on "best"; valid locations are\n DCTB %s\n' % (loc, '\n DCTB '.join(self.codes.keys())))) loc = 0 else: warnings.warn(('Unrecognized location "%s". Falling back on "upper right"; valid locations are\n DCTB %s\n' % (loc, '\n DCTB '.join(self.codes.keys())))) loc = 1 else: loc = self.codes[loc] if ((not self.isaxes) and (loc == 0)): warnings.warn('Automatic legend placement (loc="best") not implemented for figure legend. Falling back on "upper right".') loc = 1 self._loc = loc self._mode = mode self.legendPatch = FancyBboxPatch(xy=(0.0, 0.0), width=1.0, height=1.0, facecolor='w', edgecolor='k', mutation_scale=self.fontsize, snap=True) if (fancybox is None): fancybox = rcParams['legend.fancybox'] if (fancybox == True): 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 = True self._init_legend_box(handles, labels) self._last_fontsize_points = self.fontsize
'set the boilerplate props for artists added to axes'
def _set_artist_props(self, a):
a.set_figure(self.figure) for c in self.get_children(): c.set_figure(self.figure) a.set_transform(self.get_transform())
'Heper function to locate the legend at its best position'
def _findoffset_best(self, width, height, xdescent, ydescent, renderer):
(ox, oy) = self._find_best_position(width, height, renderer) return ((ox + xdescent), (oy + ydescent))
'Heper function to locate the legend using the location code'
def _findoffset_loc(self, width, height, xdescent, ydescent, renderer):
if (iterable(self._loc) and (len(self._loc) == 2)): (fx, fy) = self._loc bbox = self.parent.bbox (x, y) = ((bbox.x0 + (bbox.width * fx)), (bbox.y0 + (bbox.height * fy))) else: bbox = Bbox.from_bounds(0, 0, width, height) (x, y) = self._get_anchored_bbox(self._loc, bbox, self.parent.bbox, renderer) return ((x + xdescent), (y + ydescent))
'Draw everything that belongs to the legend'
def draw(self, renderer):
if (not self.get_visible()): return self._update_legend_box(renderer) renderer.open_group('legend') if (self._loc == 0): _findoffset = self._findoffset_best else: _findoffset = self._findoffset_loc def findoffset(width, height, xdescent, ydescent): return _findoffset(width, height, xdescent, ydescent, renderer) self._legend_box.set_offset(findoffset) fontsize = renderer.points_to_pixels(self.fontsize) if (self._mode in ['expand']): pad = ((2 * (self.borderaxespad + self.borderpad)) * fontsize) self._legend_box.set_width((self.parent.bbox.width - pad)) if self._drawFrame: bbox = self._legend_box.get_window_extent(renderer) self.legendPatch.set_bounds(bbox.x0, bbox.y0, bbox.width, bbox.height) self.legendPatch.set_mutation_scale(fontsize) if self.shadow: shadow = Shadow(self.legendPatch, 2, (-2)) shadow.draw(renderer) self.legendPatch.draw(renderer) self._legend_box.draw(renderer) renderer.close_group('legend')
'Return the approximate height of the text. This is used to place the legend handle.'
def _approx_text_height(self, renderer=None):
if (renderer is None): return self.fontsize else: return renderer.points_to_pixels(self.fontsize)
'Initiallize 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.'
def _init_legend_box(self, handles, labels):
fontsize = self.fontsize text_list = [] handle_list = [] label_prop = dict(verticalalignment='baseline', horizontalalignment='left', fontproperties=self.prop) labelboxes = [] for l in labels: textbox = TextArea(l, textprops=label_prop, multilinebaseline=True, minimumdescent=True) text_list.append(textbox._text) labelboxes.append(textbox) handleboxes = [] height = (self._approx_text_height() * 0.7) descent = 0.0 for handle in handles: if isinstance(handle, RegularPolyCollection): npoints = self.scatterpoints else: npoints = self.numpoints if (npoints > 1): xdata = np.linspace((0.3 * fontsize), ((self.handlelength - 0.3) * fontsize), npoints) xdata_marker = xdata elif (npoints == 1): xdata = np.linspace(0, (self.handlelength * fontsize), 2) xdata_marker = [((0.5 * self.handlelength) * fontsize)] if isinstance(handle, Line2D): ydata = (((height - descent) / 2.0) * np.ones(xdata.shape, float)) legline = Line2D(xdata, ydata) legline.update_from(handle) self._set_artist_props(legline) legline.set_clip_box(None) legline.set_clip_path(None) legline.set_drawstyle('default') legline.set_marker('None') handle_list.append(legline) legline_marker = Line2D(xdata_marker, ydata[:len(xdata_marker)]) legline_marker.update_from(handle) self._set_artist_props(legline_marker) legline_marker.set_clip_box(None) legline_marker.set_clip_path(None) legline_marker.set_linestyle('None') legline._legmarker = legline_marker elif isinstance(handle, Patch): p = Rectangle(xy=(0.0, 0.0), width=(self.handlelength * fontsize), height=(height - descent)) p.update_from(handle) self._set_artist_props(p) p.set_clip_box(None) p.set_clip_path(None) handle_list.append(p) elif isinstance(handle, LineCollection): ydata = (((height - descent) / 2.0) * np.ones(xdata.shape, float)) legline = Line2D(xdata, ydata) self._set_artist_props(legline) legline.set_clip_box(None) legline.set_clip_path(None) lw = handle.get_linewidth()[0] dashes = handle.get_dashes()[0] color = handle.get_colors()[0] legline.set_color(color) legline.set_linewidth(lw) legline.set_dashes(dashes) handle_list.append(legline) elif isinstance(handle, RegularPolyCollection): ydata = (height * self._scatteryoffsets) (size_max, size_min) = (max(handle.get_sizes()), min(handle.get_sizes())) if (self.scatterpoints < 4): sizes = [(0.5 * (size_max + size_min)), size_max, size_min] else: sizes = (((size_max - size_min) * np.linspace(0, 1, self.scatterpoints)) + size_min) p = type(handle)(handle.get_numsides(), rotation=handle.get_rotation(), sizes=sizes, offsets=zip(xdata_marker, ydata), transOffset=self.get_transform()) p.update_from(handle) p.set_figure(self.figure) p.set_clip_box(None) p.set_clip_path(None) handle_list.append(p) else: handle_list.append(None) handlebox = DrawingArea(width=(self.handlelength * fontsize), height=height, xdescent=0.0, ydescent=descent) handle = handle_list[(-1)] handlebox.add_artist(handle) if hasattr(handle, '_legmarker'): handlebox.add_artist(handle._legmarker) handleboxes.append(handlebox) (nrows, num_largecol) = divmod(len(handleboxes), self._ncol) num_smallcol = (self._ncol - num_largecol) largecol = safezip(range(0, (num_largecol * (nrows + 1)), (nrows + 1)), ([(nrows + 1)] * num_largecol)) smallcol = safezip(range((num_largecol * (nrows + 1)), len(handleboxes), nrows), ([nrows] * num_smallcol)) handle_label = safezip(handleboxes, labelboxes) columnbox = [] for (i0, di) in (largecol + smallcol): itemBoxes = [HPacker(pad=0, sep=(self.handletextpad * fontsize), children=[h, t], align='baseline') for (h, t) in handle_label[i0:(i0 + di)]] itemBoxes[(-1)].get_children()[1].set_minimumdescent(False) 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_box = HPacker(pad=(self.borderpad * fontsize), sep=sep, align='baseline', mode=mode, children=columnbox) self._legend_box.set_figure(self.figure) self.texts = text_list self.legendHandles = handle_list
'Update the dimension of the legend_box. This is required becuase the paddings, the hadle size etc. depends on the dpi of the renderer.'
def _update_legend_box(self, renderer):
fontsize = renderer.points_to_pixels(self.fontsize) if (self._last_fontsize_points == fontsize): return height = (self._approx_text_height(renderer) * 0.7) descent = 0.0 for handle in self.legendHandles: if isinstance(handle, RegularPolyCollection): npoints = self.scatterpoints else: npoints = self.numpoints if (npoints > 1): xdata = np.linspace((0.3 * fontsize), ((self.handlelength - 0.3) * fontsize), npoints) xdata_marker = xdata elif (npoints == 1): xdata = np.linspace(0, (self.handlelength * fontsize), 2) xdata_marker = [((0.5 * self.handlelength) * fontsize)] if isinstance(handle, Line2D): legline = handle ydata = (((height - descent) / 2.0) * np.ones(xdata.shape, float)) legline.set_data(xdata, ydata) legline_marker = legline._legmarker legline_marker.set_data(xdata_marker, ydata[:len(xdata_marker)]) elif isinstance(handle, Patch): p = handle p.set_bounds(0.0, 0.0, (self.handlelength * fontsize), (height - descent)) elif isinstance(handle, RegularPolyCollection): p = handle ydata = (height * self._scatteryoffsets) p.set_offsets(zip(xdata_marker, ydata)) cor = (fontsize / self._last_fontsize_points) def all_children(parent): (yield parent) for c in parent.get_children(): for cc in all_children(c): (yield cc) for box in all_children(self._legend_box): if isinstance(box, PackerBase): box.pad = (box.pad * cor) box.sep = (box.sep * cor) elif isinstance(box, DrawingArea): box.width = (self.handlelength * fontsize) box.height = height box.xdescent = 0.0 box.ydescent = descent self._last_fontsize_points = fontsize
'Returns list of vertices and extents covered by the plot. Returns a two long list. First element is a list of (x, y) vertices (in display-coordinates) covered by all the lines and line collections, in the legend\'s handles. Second element is a list of bounding boxes for all the patches in the legend\'s handles.'
def _auto_legend_data(self):
assert self.isaxes ax = self.parent vertices = [] bboxes = [] lines = [] for handle in ax.lines: assert isinstance(handle, Line2D) path = handle.get_path() trans = handle.get_transform() tpath = trans.transform_path(path) lines.append(tpath) for handle in ax.patches: assert isinstance(handle, Patch) if isinstance(handle, Rectangle): transform = handle.get_data_transform() bboxes.append(handle.get_bbox().transformed(transform)) else: transform = handle.get_transform() bboxes.append(handle.get_path().get_extents(transform)) return [vertices, bboxes, lines]
'b is a boolean. Set draw frame to b'
def draw_frame(self, b):
self._drawFrame = b
'return a list of child artists'
def get_children(self):
children = [] if self._legend_box: children.append(self._legend_box) return children
'return the Rectangle instance used to frame the legend'
def get_frame(self):
return self.legendPatch
'return a list of lines.Line2D instances in the legend'
def get_lines(self):
return [h for h in self.legendHandles if isinstance(h, Line2D)]
'return a list of patch instances in the legend'
def get_patches(self):
return silent_list('Patch', [h for h in self.legendHandles if isinstance(h, Patch)])
'return a list of text.Text instance in the legend'
def get_texts(self):
return silent_list('Text', self.texts)
'return a extent of the the legend'
def get_window_extent(self):
return self.legendPatch.get_window_extent()
'Place the *bbox* inside the *parentbbox* according to a given location code. Return the (x,y) coordinate of the bbox. - loc: a location code in range(1, 11). This corresponds to the possible values for self._loc, excluding "best". - bbox: bbox to be placed, display coodinate units. - parentbbox: a parent box which will contain the bbox. In display coordinates.'
def _get_anchored_bbox(self, loc, bbox, parentbbox, renderer):
assert (loc in range(1, 11)) (BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C) = range(11) anchor_coefs = {UR: 'NE', UL: 'NW', LL: 'SW', LR: 'SE', R: 'E', CL: 'W', CR: 'E', LC: 'S', UC: 'N', C: 'C'} c = anchor_coefs[loc] fontsize = renderer.points_to_pixels(self.fontsize) container = parentbbox.padded(((- self.borderaxespad) * fontsize)) anchored_box = bbox.anchored(c, container=container) return (anchored_box.x0, anchored_box.y0)
'Determine the best location to place the legend. `consider` is a list of (x, y) pairs to consider as a potential lower-left corner of the legend. All are display coords.'
def _find_best_position(self, width, height, renderer, consider=None):
assert self.isaxes (verts, bboxes, lines) = self._auto_legend_data() bbox = Bbox.from_bounds(0, 0, width, height) consider = [self._get_anchored_bbox(x, bbox, self.parent.bbox, renderer) for x in range(1, len(self.codes))] candidates = [] for (l, b) in consider: legendBox = Bbox.from_bounds(l, b, width, height) badness = 0 badness = legendBox.count_contains(verts) badness += legendBox.count_overlaps(bboxes) for line in lines: if line.intersects_bbox(legendBox): badness += 1 (ox, oy) = (l, b) if (badness == 0): return (ox, oy) candidates.append((badness, (l, b))) minCandidate = candidates[0] for candidate in candidates: if (candidate[0] < minCandidate[0]): minCandidate = candidate (ox, oy) = minCandidate[1] return (ox, oy)
'Return a copy of the vertices used in this patch If the patch contains Bézier curves, the curves will be interpolated by line segments. To access the curves as curves, use :meth:`get_path`.'
def get_verts(self):
trans = self.get_transform() path = self.get_path() polygons = path.to_polygons(trans) if len(polygons): return polygons[0] return []
'Test whether the mouse event occurred in the patch. Returns T/F, {}'
def contains(self, mouseevent):
if callable(self._contains): return self._contains(self, mouseevent) inside = self.get_path().contains_point((mouseevent.x, mouseevent.y), self.get_transform()) return (inside, {})
'Updates this :class:`Patch` from the properties of *other*.'
def update_from(self, other):
artist.Artist.update_from(self, other) self.set_edgecolor(other.get_edgecolor()) self.set_facecolor(other.get_facecolor()) self.set_fill(other.get_fill()) self.set_hatch(other.get_hatch()) self.set_linewidth(other.get_linewidth()) self.set_linestyle(other.get_linestyle()) self.set_transform(other.get_data_transform()) self.set_figure(other.get_figure()) self.set_alpha(other.get_alpha())
'Return a :class:`~matplotlib.transforms.Bbox` object defining the axis-aligned extents of the :class:`Patch`.'
def get_extents(self):
return self.get_path().get_extents(self.get_transform())
'Return the :class:`~matplotlib.transforms.Transform` applied to the :class:`Patch`.'
def get_transform(self):
return (self.get_patch_transform() + artist.Artist.get_transform(self))
'Returns True if the :class:`Patch` is to be drawn with antialiasing.'
def get_antialiased(self):
return self._antialiased
'Return the edge color of the :class:`Patch`.'
def get_edgecolor(self):
return self._edgecolor
'Return the face color of the :class:`Patch`.'
def get_facecolor(self):
return self._facecolor
'Return the line width in points.'
def get_linewidth(self):
return self._linewidth
'Return the linestyle. Will be one of [\'solid\' | \'dashed\' | \'dashdot\' | \'dotted\']'
def get_linestyle(self):
return self._linestyle
'Set whether to use antialiased rendering ACCEPTS: [True | False] or None for default'
def set_antialiased(self, aa):
if (aa is None): aa = mpl.rcParams['patch.antialiased'] self._antialiased = aa
'alias for set_antialiased'
def set_aa(self, aa):
return self.set_antialiased(aa)
'Set the patch edge color ACCEPTS: mpl color spec, or None for default, or \'none\' for no color'
def set_edgecolor(self, color):
if (color is None): color = mpl.rcParams['patch.edgecolor'] self._edgecolor = color
'alias for set_edgecolor'
def set_ec(self, color):
return self.set_edgecolor(color)
'Set the patch face color ACCEPTS: mpl color spec, or None for default, or \'none\' for no color'
def set_facecolor(self, color):
if (color is None): color = mpl.rcParams['patch.facecolor'] self._facecolor = color