desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Add the lines from a non-filled :class:`~matplotlib.contour.ContourSet` to the colorbar.'
def add_lines(self, CS):
if ((not isinstance(CS, contour.ContourSet)) or CS.filled): raise ValueError('add_lines is only for a ContourSet of lines') tcolors = [c[0] for c in CS.tcolors] tlinewidths = [t[0] for t in CS.tlinewidths] ColorbarBase.add_lines(self, CS.levels, tcolors, tlinewidths)
'Manually change any contour line colors. This is called when the image or contour plot to which this colorbar belongs is changed.'
def update_bruteforce(self, mappable):
self.ax.cla() self.draw_all() if isinstance(self.mappable, contour.ContourSet): CS = self.mappable if (not CS.filled): self.add_lines(CS)
'set the verbosity to one of the Verbose.levels strings'
def set_level(self, level):
if (self._commandLineVerbose is not None): level = self._commandLineVerbose if (level not in self.levels): raise ValueError(('Illegal verbose string "%s". Legal values are %s' % (level, self.levels))) self.level = level
'print message s to self.fileo if self.level>=level. Return value indicates whether a message was issued'
def report(self, s, level='helpful'):
if self.ge(level): print >>self.fileo, s return True return False
'return a callable function that wraps func and reports it output through the verbose handler if current verbosity level is higher than level if always is True, the report will occur on every function call; otherwise only on the first time the function is called'
def wrap(self, fmt, func, level='helpful', always=True):
assert callable(func) def wrapper(*args, **kwargs): ret = func(*args, **kwargs) if (always or (not wrapper._spoke)): spoke = self.report((fmt % ret), level) if (not wrapper._spoke): wrapper._spoke = spoke return ret wrapper._spoke = False w...
'return true if self.level is >= level'
def ge(self, level):
return (self.vald[self.level] >= self.vald[level])
'*control_points* : location of contol points. It needs have a shpae of n * 2, where n is the order of the bezier line. 1<= n <= 3 is supported.'
def __init__(self, control_points):
_o = len(control_points) self._orders = np.arange(_o) _coeff = BezierSegment._binom_coeff[(_o - 1)] _control_points = np.asarray(control_points) xx = _control_points[:, 0] yy = _control_points[:, 1] self._px = (xx * _coeff) self._py = (yy * _coeff)
'evaluate a point at t'
def point_at_t(self, t):
one_minus_t_powers = np.power((1.0 - t), self._orders)[::(-1)] t_powers = np.power(t, self._orders) tt = (one_minus_t_powers * t_powers) _x = sum((tt * self._px)) _y = sum((tt * self._py)) return (_x, _y)
'Event handler that will be passed to the current figure to retrieve events.'
def on_event(self, event):
self.add_event(event) verbose.report(('Event %i' % len(self.events))) self.post_event() if ((len(self.events) >= self.n) and (self.n > 0)): self.fig.canvas.stop_event_loop()
'For baseclass, do nothing but collect events'
def post_event(self):
pass
'Disconnect all callbacks'
def cleanup(self):
for cb in self.callbacks: self.fig.canvas.mpl_disconnect(cb) self.callbacks = []
'For base class, this just appends an event to events.'
def add_event(self, event):
self.events.append(event)
'This removes an event from the event list. Defaults to removing last event, but an index can be supplied. Note that this does not check that there are events, much like the normal pop method. If not events exist, this will throw an exception.'
def pop_event(self, index=(-1)):
self.events.pop(index)
'Blocking call to retrieve n events'
def __call__(self, n=1, timeout=30):
assert isinstance(n, int), 'Requires an integer argument' self.n = n self.events = [] self.callbacks = [] self.fig.show() for n in self.eventslist: self.callbacks.append(self.fig.canvas.mpl_connect(n, self.on_event)) try: self.fig.canvas.start_event_loop(timeout=time...
'This will be called to process events'
def post_event(self):
assert (len(self.events) > 0), 'No events yet' if (self.events[(-1)].name == 'key_press_event'): self.key_event() else: self.mouse_event()
'Process a mouse click event'
def mouse_event(self):
event = self.events[(-1)] button = event.button if (button == 3): self.button3(event) elif (button == 2): self.button2(event) else: self.button1(event)
'Process a key click event. This maps certain keys to appropriate mouse click events.'
def key_event(self):
event = self.events[(-1)] key = event.key if ((key == 'backspace') or (key == 'delete')): self.button3(event) elif (key == 'enter'): self.button2(event) else: self.button1(event)
'Will be called for any event involving a button other than button 2 or 3. This will add a click if it is inside axes.'
def button1(self, event):
if event.inaxes: self.add_click(event) else: BlockingInput.pop(self)
'Will be called for any event involving button 2. Button 2 ends blocking input.'
def button2(self, event):
BlockingInput.pop(self) self.fig.canvas.stop_event_loop()
'Will be called for any event involving button 3. Button 3 removes the last click.'
def button3(self, event):
BlockingInput.pop(self) if (len(self.events) > 0): self.pop()
'This add the coordinates of an event to the list of clicks'
def add_click(self, event):
self.clicks.append((event.xdata, event.ydata)) verbose.report(('input %i: %f,%f' % (len(self.clicks), event.xdata, event.ydata))) if self.show_clicks: self.marks.extend(event.inaxes.plot([event.xdata], [event.ydata], 'r+')) self.fig.canvas.draw()
'This removes a click from the list of clicks. Defaults to removing the last click.'
def pop_click(self, index=(-1)):
self.clicks.pop(index) if self.show_clicks: mark = self.marks.pop(index) mark.remove() self.fig.canvas.draw()
'This removes a click and the associated event from the object. Defaults to removing the last click, but any index can be supplied.'
def pop(self, index=(-1)):
self.pop_click(index) BlockingInput.pop(self, index)
'Blocking call to retrieve n coordinate pairs through mouse clicks.'
def __call__(self, n=1, timeout=30, show_clicks=True):
self.show_clicks = show_clicks self.clicks = [] self.marks = [] BlockingInput.__call__(self, n=n, timeout=timeout) return self.clicks
'This will be called if an event involving a button other than 2 or 3 occcurs. This will add a label to a contour.'
def button1(self, event):
cs = self.cs if (event.inaxes == cs.ax): (conmin, segmin, imin, xmin, ymin) = cs.find_nearest_contour(event.x, event.y, cs.labelIndiceList)[:5] lmin = cs.labelIndiceList.index(conmin) paths = cs.collections[conmin].get_paths() lc = paths[segmin].vertices slc = cs.ax.trans...
'This will be called if button 3 is clicked. This will remove a label if not in inline mode. Unfortunately, if one is doing inline labels, then there is currently no way to fix the broken contour - once humpty-dumpty is broken, he can\'t be put back together. In inline mode, this does nothing.'
def button3(self, event):
BlockingInput.pop(self) if self.inline: pass else: self.cs.pop_label() self.cs.ax.figure.canvas.draw()
'Determines if it is a key event'
def post_event(self):
assert (len(self.events) > 0), 'No events yet' self.keyormouse = (self.events[(-1)].name == 'key_press_event')
'Blocking call to retrieve a single mouse or key click Returns True if key click, False if mouse, or None if timeout'
def __call__(self, timeout=30):
self.keyormouse = None BlockingInput.__call__(self, n=1, timeout=timeout) return self.keyormouse
'Create a new path with the given vertices and codes. *vertices* is an Nx2 numpy float array, masked array or Python sequence. *codes* is an N-length numpy array or Python sequence of type :attr:`matplotlib.path.Path.code_type`. These two arrays must have the same length in the first dimension. If *codes* is None, *ver...
def __init__(self, vertices, codes=None):
if ma.isMaskedArray(vertices): vertices = vertices.astype(np.float_).filled(np.nan) else: vertices = np.asarray(vertices, np.float_) if (codes is not None): codes = np.asarray(codes, self.code_type) assert (codes.ndim == 1) assert (len(codes) == len(vertices)) ass...
'(staticmethod) Make a compound path from a list of Path objects. Only polygons (not curves) are supported.'
def make_compound_path(*args):
for p in args: assert (p.codes is None) lengths = [len(x) for x in args] total_length = sum(lengths) vertices = np.vstack([x.vertices for x in args]) vertices.reshape((total_length, 2)) codes = (Path.LINETO * np.ones(total_length)) i = 0 for length in lengths: codes[i] = ...
'Iterates over all of the curve segments in the path. Each iteration returns a 2-tuple (*vertices*, *code*), where *vertices* is a sequence of 1 - 3 coordinate pairs, and *code* is one of the :class:`Path` codes. If *simplify* is provided, it must be a tuple (*width*, *height*) defining the size of the figure, in nati...
def iter_segments(self, simplify=None):
vertices = self.vertices if (not len(vertices)): return codes = self.codes len_vertices = len(vertices) isfinite = np.isfinite NUM_VERTICES = self.NUM_VERTICES MOVETO = self.MOVETO LINETO = self.LINETO CLOSEPOLY = self.CLOSEPOLY STOP = self.STOP if ((simplify is not N...
'Return a transformed copy of the path. .. seealso:: :class:`matplotlib.transforms.TransformedPath`: A specialized path class that will cache the transformed result and automatically update when the transform changes.'
def transformed(self, transform):
return Path(transform.transform(self.vertices), self.codes)
'Returns *True* if the path contains the given point. If *transform* is not *None*, the path will be transformed before performing the test.'
def contains_point(self, point, transform=None):
if (transform is not None): transform = transform.frozen() return point_in_path(point[0], point[1], self, transform)
'Returns *True* if this path completely contains the given path. If *transform* is not *None*, the path will be transformed before performing the test.'
def contains_path(self, path, transform=None):
if (transform is not None): transform = transform.frozen() return path_in_path(self, None, path, transform)
'Returns the extents (*xmin*, *ymin*, *xmax*, *ymax*) of the path. Unlike computing the extents on the *vertices* alone, this algorithm will take into account the curves and deal with control points appropriately.'
def get_extents(self, transform=None):
from transforms import Bbox if (transform is not None): transform = transform.frozen() return Bbox(get_path_extents(self, transform))
'Returns *True* if this path intersects another given path. *filled*, when True, treats the paths as if they were filled. That is, if one path completely encloses the other, :meth:`intersects_path` will return True.'
def intersects_path(self, other, filled=True):
return path_intersects_path(self, other, filled)
'Returns *True* if this path intersects a given :class:`~matplotlib.transforms.Bbox`. *filled*, when True, treats the path as if it was filled. That is, if one path completely encloses the other, :meth:`intersects_path` will return True.'
def intersects_bbox(self, bbox, filled=True):
from transforms import BboxTransformTo rectangle = self.unit_rectangle().transformed(BboxTransformTo(bbox)) result = self.intersects_path(rectangle, filled) return result
'Returns a new path resampled to length N x steps. Does not currently handle interpolating curves.'
def interpolated(self, steps):
vertices = simple_linear_interpolation(self.vertices, steps) codes = self.codes if (codes is not None): new_codes = (Path.LINETO * np.ones(((((len(codes) - 1) * steps) + 1),))) new_codes[0::steps] = codes else: new_codes = None return Path(vertices, new_codes)
'Convert this path to a list of polygons. Each polygon is an Nx2 array of vertices. In other words, each polygon has no ``MOVETO`` instructions or curves. This is useful for displaying in backends that do not support compound paths or Bezier curves, such as GDK. If *width* and *height* are both non-zero then the lin...
def to_polygons(self, transform=None, width=0, height=0):
if (len(self.vertices) == 0): return [] if (transform is not None): transform = transform.frozen() if ((self.codes is None) and ((width == 0) or (height == 0))): if (transform is None): return [self.vertices] else: return [transform.transform(self.vert...
'(staticmethod) Returns a :class:`Path` of the unit rectangle from (0, 0) to (1, 1).'
def unit_rectangle(cls):
if (cls._unit_rectangle is None): cls._unit_rectangle = Path([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0]]) return cls._unit_rectangle
'(staticmethod) Returns a :class:`Path` for a unit regular polygon with the given *numVertices* and radius of 1.0, centered at (0, 0).'
def unit_regular_polygon(cls, numVertices):
if (numVertices <= 16): path = cls._unit_regular_polygons.get(numVertices) else: path = None if (path is None): theta = (((2 * np.pi) / numVertices) * np.arange((numVertices + 1)).reshape(((numVertices + 1), 1))) theta += (np.pi / 2.0) verts = np.concatenate((np.cos(t...
'(staticmethod) Returns a :class:`Path` for a unit regular star with the given numVertices and radius of 1.0, centered at (0, 0).'
def unit_regular_star(cls, numVertices, innerCircle=0.5):
if (numVertices <= 16): path = cls._unit_regular_stars.get((numVertices, innerCircle)) else: path = None if (path is None): ns2 = (numVertices * 2) theta = (((2 * np.pi) / ns2) * np.arange((ns2 + 1))) theta += (np.pi / 2.0) r = np.ones((ns2 + 1)) r[1::...
'(staticmethod) Returns a :class:`Path` for a unit regular asterisk with the given numVertices and radius of 1.0, centered at (0, 0).'
def unit_regular_asterisk(cls, numVertices):
return cls.unit_regular_star(numVertices, 0.0)
'(staticmethod) Returns a :class:`Path` of the unit circle. The circle is approximated using cubic Bezier curves. This uses 8 splines around the circle using the approach presented here: Lancaster, Don. `Approximating a Circle or an Ellipse Using Four Bezier Cubic Splines <http://www.tinaja.com/glib/ellipse4.pdf>`_.'...
def unit_circle(cls):
if (cls._unit_circle is None): MAGIC = 0.2652031 SQRTHALF = np.sqrt(0.5) MAGIC45 = np.sqrt(((MAGIC * MAGIC) / 2.0)) vertices = np.array([[0.0, (-1.0)], [MAGIC, (-1.0)], [(SQRTHALF - MAGIC45), ((- SQRTHALF) - MAGIC45)], [SQRTHALF, (- SQRTHALF)], [(SQRTHALF + MAGIC45), ((- SQRTHALF) + ...
'(staticmethod) Returns an arc on the unit circle from angle *theta1* to angle *theta2* (in degrees). If *n* is provided, it is the number of spline segments to make. If *n* is not provided, the number of spline segments is determined based on the delta between *theta1* and *theta2*. Masionobe, L. 2003. `Drawing an e...
def arc(cls, theta1, theta2, n=None, is_wedge=False):
theta1 *= (np.pi / 180.0) theta2 *= (np.pi / 180.0) twopi = (np.pi * 2.0) halfpi = (np.pi * 0.5) eta1 = np.arctan2(np.sin(theta1), np.cos(theta1)) eta2 = np.arctan2(np.sin(theta2), np.cos(theta2)) eta2 -= (twopi * np.floor(((eta2 - eta1) / twopi))) if (((theta2 - theta1) > np.pi) and ((e...
'(staticmethod) Returns a wedge of the unit circle from angle *theta1* to angle *theta2* (in degrees). If *n* is provided, it is the number of spline segments to make. If *n* is not provided, the number of spline segments is determined based on the delta between *theta1* and *theta2*.'
def wedge(cls, theta1, theta2, n=None):
return cls.arc(theta1, theta2, n, True)
'Dimension the drawing canvas'
def set_canvas_size(self, w, h, d):
self.width = w self.height = h self.depth = d
'Draw a glyph described by *info* to the reference point (*ox*, *oy*).'
def render_glyph(self, ox, oy, info):
raise NotImplementedError()
'Draw a filled black rectangle from (*x1*, *y1*) to (*x2*, *y2*).'
def render_filled_rect(self, x1, y1, x2, y2):
raise NotImplementedError()
'Return a backend-specific tuple to return to the backend after all processing is done.'
def get_results(self, box):
raise NotImplementedError()
'Get the Freetype hinting type to use with this particular backend.'
def get_hinting_type(self):
return LOAD_NO_HINTING
'*default_font_prop*: A :class:`~matplotlib.font_manager.FontProperties` object to use for the default non-math font, or the base font for Unicode (generic) font rendering. *mathtext_backend*: A subclass of :class:`MathTextBackend` used to delegate the actual rendering.'
def __init__(self, default_font_prop, mathtext_backend):
self.default_font_prop = default_font_prop self.mathtext_backend = mathtext_backend self.mathtext_backend.fonts_object = self self.used_characters = {}
'Fix any cyclical references before the object is about to be destroyed.'
def destroy(self):
self.used_characters = None
'Get the kerning distance for font between *sym1* and *sym2*. *fontX*: one of the TeX font names:: tt, it, rm, cal, sf, bf or default (non-math) *fontclassX*: TODO *symX*: a symbol in raw TeX form. e.g. \'1\', \'x\' or \'\sigma\' *fontsizeX*: the fontsize in points *dpi*: the current dots-per-inch'
def get_kern(self, font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi):
return 0.0
'*font*: one of the TeX font names:: tt, it, rm, cal, sf, bf or default (non-math) *font_class*: TODO *sym*: a symbol in raw TeX form. e.g. \'1\', \'x\' or \'\sigma\' *fontsize*: font size in points *dpi*: current dots-per-inch Returns an object with the following attributes: - *advance*: The advance distance (in poin...
def get_metrics(self, font, font_class, sym, fontsize, dpi):
info = self._get_info(font, font_class, sym, fontsize, dpi) return info.metrics
'Set the size of the buffer used to render the math expression. Only really necessary for the bitmap backends.'
def set_canvas_size(self, w, h, d):
(self.width, self.height, self.depth) = (ceil(w), ceil(h), ceil(d)) self.mathtext_backend.set_canvas_size(self.width, self.height, self.depth)
'Draw a glyph at - *ox*, *oy*: position - *facename*: One of the TeX face names - *font_class*: - *sym*: TeX symbol name or single character - *fontsize*: fontsize in points - *dpi*: The dpi to draw at.'
def render_glyph(self, ox, oy, facename, font_class, sym, fontsize, dpi):
info = self._get_info(facename, font_class, sym, fontsize, dpi) (realpath, stat_key) = get_realpath_and_stat(info.font.fname) used_characters = self.used_characters.setdefault(stat_key, (realpath, set())) used_characters[1].add(info.num) self.mathtext_backend.render_glyph(ox, oy, info)
'Draw a filled rectangle from (*x1*, *y1*) to (*x2*, *y2*).'
def render_rect_filled(self, x1, y1, x2, y2):
self.mathtext_backend.render_rect_filled(x1, y1, x2, y2)
'Get the xheight for the given *font* and *fontsize*.'
def get_xheight(self, font, fontsize, dpi):
raise NotImplementedError()
'Get the line thickness that matches the given font. Used as a base unit for drawing lines such as in a fraction or radical.'
def get_underline_thickness(self, font, fontsize, dpi):
raise NotImplementedError()
'Get the set of characters that were used in the math expression. Used by backends that need to subset fonts so they know which glyphs to include.'
def get_used_characters(self):
return self.used_characters
'Get the data needed by the backend to render the math expression. The return value is backend-specific.'
def get_results(self, box):
return self.mathtext_backend.get_results(box)
'Override if your font provides multiple sizes of the same symbol. Should return a list of symbols matching *sym* in various sizes. The expression renderer will select the most appropriate size for a given situation from this list.'
def get_sized_alternatives_for_symbol(self, fontname, sym):
return [(fontname, sym)]
'load the cmfont, metrics and glyph with caching'
def _get_info(self, fontname, font_class, sym, fontsize, dpi):
key = (fontname, sym, fontsize, dpi) tup = self.glyphd.get(key) if (tup is not None): return tup if ((fontname == 'it') and ((len(sym) > 1) or (not unicodedata.category(unicode(sym)).startswith('L')))): fontname = 'rm' found_symbol = False if (sym in latex_to_standard): (...
'Shrinks one level smaller. There are only three levels of sizes, after which things will no longer get smaller.'
def shrink(self):
self.size += 1
'Grows one level larger. There is no limit to how big something can get.'
def grow(self):
self.size -= 1
'Return the amount of kerning between this and the given character. Called when characters are strung together into :class:`Hlist` to create :class:`Kern` nodes.'
def get_kerning(self, next):
advance = (self._metrics.advance - self.width) kern = 0.0 if isinstance(next, Char): kern = self.font_output.get_kern(self.font, self.font_class, self.c, self.fontsize, next.font, next.font_class, next.c, next.fontsize, self.dpi) return (advance + kern)
'Render the character to the canvas'
def render(self, x, y):
self.font_output.render_glyph(x, y, self.font, self.font_class, self.c, self.fontsize, self.dpi)
'Render the character to the canvas.'
def render(self, x, y):
self.font_output.render_glyph((x - self._metrics.xmin), (y + self._metrics.ymin), self.font, self.font_class, self.c, self.fontsize, self.dpi)
'A helper function to determine the highest order of glue used by the members of this list. Used by vpack and hpack.'
def _determine_order(self, totals):
o = 0 for i in range((len(totals) - 1), 0, (-1)): if (totals[i] != 0.0): o = i break return o
'Insert :class:`Kern` nodes between :class:`Char` nodes to set kerning. The :class:`Char` nodes themselves determine the amount of kerning they need (in :meth:`~Char.get_kerning`), and this function just creates the linked list in the correct way.'
def kern(self):
new_children = [] num_children = len(self.children) if num_children: for i in range(num_children): elem = self.children[i] if (i < (num_children - 1)): next = self.children[(i + 1)] else: next = None new_children.append(...
'The main duty of :meth:`hpack` is to compute the dimensions of the resulting boxes, and to adjust the glue if one of those dimensions is pre-specified. The computed sizes normally enclose all of the material inside the new box; but some items may stick out if negative glue is used, if the box is overfull, or if a ``\...
def hpack(self, w=0.0, m='additional'):
h = 0.0 d = 0.0 x = 0.0 total_stretch = ([0.0] * 4) total_shrink = ([0.0] * 4) for p in self.children: if isinstance(p, Char): x += p.width h = max(h, p.height) d = max(d, p.depth) elif isinstance(p, Box): x += p.width i...
'The main duty of :meth:`vpack` is to compute the dimensions of the resulting boxes, and to adjust the glue if one of those dimensions is pre-specified. - *h*: specifies a height - *m*: is either \'exactly\' or \'additional\'. - *l*: a maximum height Thus, ``vpack(h, \'exactly\')`` produces a box whose height is exactl...
def vpack(self, h=0.0, m='additional', l=float(inf)):
w = 0.0 d = 0.0 x = 0.0 total_stretch = ([0.0] * 4) total_shrink = ([0.0] * 4) for p in self.children: if isinstance(p, Box): x += (d + p.height) d = p.depth if (not isinf(p.width)): s = getattr(p, 'shift_amount', 0.0) w...
'Clear any state before parsing.'
def clear(self):
self._expr = None self._state_stack = None self._em_width_cache = {}
'Parse expression *s* using the given *fonts_object* for output, at the given *fontsize* and *dpi*. Returns the parse tree of :class:`Node` instances.'
def parse(self, s, fonts_object, fontsize, dpi):
self._state_stack = [self.State(fonts_object, 'default', 'rm', fontsize, dpi)] try: self._expression.parseString(s) except ParseException as err: raise ValueError('\n'.join(['', err.line, ((' ' * (err.column - 1)) + '^'), str(err)])) return self._expr
'Get the current :class:`State` of the parser.'
def get_state(self):
return self._state_stack[(-1)]
'Pop a :class:`State` off of the stack.'
def pop_state(self):
self._state_stack.pop()
'Push a new :class:`State` onto the stack which is just a copy of the current state.'
def push_state(self):
self._state_stack.append(self.get_state().copy())
'Create a MathTextParser for the given backend *output*.'
def __init__(self, output):
self._output = output.lower() self._cache = maxdict(50)
'Parse the given math expression *s* at the given *dpi*. If *prop* is provided, it is a :class:`~matplotlib.font_manager.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 :meth:`parse` with the same expression sh...
def parse(self, s, dpi=72, prop=None):
if (prop is None): prop = FontProperties() cacheKey = (s, dpi, hash(prop)) result = self._cache.get(cacheKey) if (result is not None): return result if ((self._output == 'ps') and rcParams['ps.useafm']): font_output = StandardPsFonts(prop) else: backend = self._ba...
'*texstr* A valid mathtext string, eg r\'IQ: $\sigma_i=15$\' *dpi* The dots-per-inch to render the text *fontsize* The font size in points Returns a tuple (*array*, *depth*) - *array* is an NxM uint8 alpha ubyte mask array of rasterized tex. - depth is the offset of the baseline from the bottom of the image in pixels.'...
def to_mask(self, texstr, dpi=120, fontsize=14):
assert (self._output == 'bitmap') prop = FontProperties(size=fontsize) (ftimage, depth) = self.parse(texstr, dpi=dpi, prop=prop) x = ftimage.as_array() return (x, depth)
'*texstr* A valid mathtext string, eg r\'IQ: $\sigma_i=15$\' *color* Any matplotlib color argument *dpi* The dots-per-inch to render the text *fontsize* The font size in points Returns a tuple (*array*, *depth*) - *array* is an NxM uint8 alpha ubyte mask array of rasterized tex. - depth is the offset of the baseline fr...
def to_rgba(self, texstr, color='black', dpi=120, fontsize=14):
(x, depth) = self.to_mask(texstr, dpi=dpi, fontsize=fontsize) (r, g, b) = mcolors.colorConverter.to_rgb(color) RGBA = np.zeros((x.shape[0], x.shape[1], 4), dtype=np.uint8) RGBA[:, :, 0] = int((255 * r)) RGBA[:, :, 1] = int((255 * g)) RGBA[:, :, 2] = int((255 * b)) RGBA[:, :, 3] = x retur...
'Writes a tex expression to a PNG file. Returns the offset of the baseline from the bottom of the image in pixels. *filename* A writable filename or fileobject *texstr* A valid mathtext string, eg r\'IQ: $\sigma_i=15$\' *color* A valid matplotlib color argument *dpi* The dots-per-inch to render the text *fontsize* The ...
def to_png(self, filename, texstr, color='black', dpi=120, fontsize=14):
(rgba, depth) = self.to_rgba(texstr, color=color, dpi=dpi, fontsize=fontsize) (numrows, numcols, tmp) = rgba.shape _png.write_png(rgba.tostring(), numcols, numrows, filename) return depth
'Returns the offset of the baseline from the bottom of the image in pixels. *texstr* A valid mathtext string, eg r\'IQ: $\sigma_i=15$\' *dpi* The dots-per-inch to render the text *fontsize* The font size in points'
def get_depth(self, texstr, dpi=120, fontsize=14):
assert (self._output == 'bitmap') prop = FontProperties(size=fontsize) (ftimage, depth) = self.parse(texstr, dpi=dpi, prop=prop) return depth
'Returns an *RGB* tuple of three floats from 0-1. *arg* can be an *RGB* or *RGBA* sequence or a string in any of several forms: 1) a letter from the set \'rgbcmykw\' 2) a hex color string, like \'#00FFFF\' 3) a standard name, like \'aqua\' 4) a float, like \'0.4\', indicating gray on a 0-1 scale if *arg* is *RGBA*, the...
def to_rgb(self, arg):
try: return self.cache[arg] except KeyError: pass except TypeError: arg = tuple(arg) try: return self.cache[arg] except KeyError: pass except TypeError: raise ValueError(('to_rgb: arg "%s" is unhashable even ...
'Returns an *RGBA* tuple of four floats from 0-1. For acceptable values of *arg*, see :meth:`to_rgb`. If *arg* is an *RGBA* sequence and *alpha* is not *None*, *alpha* will replace the original *A*.'
def to_rgba(self, arg, alpha=None):
try: if ((not cbook.is_string_like(arg)) and cbook.iterable(arg)): if (len(arg) == 4): if [x for x in arg if ((float(x) < 0) or (x > 1))]: raise ValueError('number in rbga sequence outside 0-1 range') if (alpha is None): ...
'Returns a numpy array of *RGBA* tuples. Accepts a single mpl color spec or a sequence of specs. Special case to handle "no color": if *c* is "none" (case-insensitive), then an empty array will be returned. Same for an empty list.'
def to_rgba_array(self, c, alpha=None):
try: if (c.lower() == 'none'): return np.zeros((0, 4), dtype=np.float_) except AttributeError: pass if (len(c) == 0): return np.zeros((0, 4), dtype=np.float_) try: result = np.array([self.to_rgba(c, alpha)], dtype=np.float_) except ValueError: if i...
'Public class attributes: :attr:`N` : number of rgb quantization levels :attr:`name` : name of colormap'
def __init__(self, name, N=256):
self.name = name self.N = N self._rgba_bad = (0.0, 0.0, 0.0, 0.0) self._rgba_under = None self._rgba_over = None self._i_under = N self._i_over = (N + 1) self._i_bad = (N + 2) self._isinit = False
'*X* is either a scalar or an array (of any dimension). If scalar, a tuple of rgba values is returned, otherwise an array with the new shape = oldshape+(4,). If the X-values are integers, then they are used as indices into the array. If they are floating point, then they must be in the interval (0.0, 1.0). Alpha must b...
def __call__(self, X, alpha=1.0, bytes=False):
if (not self._isinit): self._init() alpha = min(alpha, 1.0) alpha = max(alpha, 0.0) self._lut[:(-3), (-1)] = alpha mask_bad = None if (not cbook.iterable(X)): vtype = 'scalar' xa = np.array([X]) else: vtype = 'array' xma = ma.asarray(X) xa = xm...
'Set color to be used for masked values.'
def set_bad(self, color='k', alpha=1.0):
self._rgba_bad = colorConverter.to_rgba(color, alpha) if self._isinit: self._set_extremes()
'Set color to be used for low out-of-range values. Requires norm.clip = False'
def set_under(self, color='k', alpha=1.0):
self._rgba_under = colorConverter.to_rgba(color, alpha) if self._isinit: self._set_extremes()
'Set color to be used for high out-of-range values. Requires norm.clip = False'
def set_over(self, color='k', alpha=1.0):
self._rgba_over = colorConverter.to_rgba(color, alpha) if self._isinit: self._set_extremes()
'Generate the lookup table, self._lut'
def _init():
raise NotImplementedError('Abstract class only')
'Create color map from linear mapping segments segmentdata argument is a dictionary with a red, green and blue entries. Each entry should be a list of *x*, *y0*, *y1* tuples, forming rows in a table. Example: suppose you want red to increase from 0 to 1 over the bottom half, green to do the same over the middle half, a...
def __init__(self, name, segmentdata, N=256):
self.monochrome = False Colormap.__init__(self, name, N) self._segmentdata = segmentdata
'Make a colormap from a list of colors. *colors* a list of matplotlib color specifications, or an equivalent Nx3 floating point array (*N* rgb values) *name* a string to identify the colormap *N* the number of entries in the map. The default is *None*, in which case there is one colormap entry for each element in the ...
def __init__(self, colors, name='from_list', N=None):
self.colors = colors self.monochrome = False if (N is None): N = len(self.colors) elif cbook.is_string_like(self.colors): self.colors = ([self.colors] * N) self.monochrome = True elif cbook.iterable(self.colors): self.colors = list(self.colors) if (len(self.co...
'If *vmin* or *vmax* is not given, they are taken from the input\'s minimum and maximum value respectively. If *clip* is *True* and the given value falls outside the range, the returned value will be 0 or 1, whichever is closer. Returns 0 if:: vmin==vmax Works with scalars or arrays, including masked arrays. If *clip...
def __init__(self, vmin=None, vmax=None, clip=False):
self.vmin = vmin self.vmax = vmax self.clip = clip
'Set *vmin*, *vmax* to min, max of *A*.'
def autoscale(self, A):
self.vmin = ma.minimum(A) self.vmax = ma.maximum(A)
'autoscale only None-valued vmin or vmax'
def autoscale_None(self, A):
if (self.vmin is None): self.vmin = ma.minimum(A) if (self.vmax is None): self.vmax = ma.maximum(A)
'return true if vmin and vmax set'
def scaled(self):
return ((self.vmin is not None) and (self.vmax is not None))
'*boundaries* a monotonically increasing sequence *ncolors* number of colors in the colormap to be used If:: b[i] <= v < b[i+1] then v is mapped to color j; as i varies from 0 to len(boundaries)-2, j goes from 0 to ncolors-1. Out-of-range values are mapped to -1 if low and ncolors if high; these are converted to valid ...
def __init__(self, boundaries, ncolors, clip=False):
self.clip = clip self.vmin = boundaries[0] self.vmax = boundaries[(-1)] self.boundaries = np.asarray(boundaries) self.N = len(self.boundaries) self.Ncmap = ncolors if ((self.N - 1) == self.Ncmap): self._interp = False else: self._interp = True