desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Draw a text string verbatim; no conversion is done.'
def draw_plain_text(self, gc, x, y, s, prop, angle):
if debugText: print ("draw_plain_text: (%f,%f) %d degrees: '%s'" % (x, y, angle, s)) if debugText: print (' properties:\n' + str(prop)) self.select_font(prop, angle) hackoffsetper300dpi = 10 xhack = (((math.sin(((angle * math.pi) / 180.0)) * hackoffsetper300dpi) * self.dpi) / 300.0) yhack = (((math.cos(((angle * math.pi) / 180.0)) * hackoffsetper300dpi) * self.dpi) / 300.0) self.emf.TextOut(long((x + xhack)), long((y + yhack)), s)
'Draw a subset of TeX, currently handles exponents only. Since pyemf doesn\'t have any raster functionality yet, the texmanager.get_rgba won\'t help.'
def draw_math_text(self, gc, x, y, s, prop, angle):
if debugText: print ("draw_math_text: (%f,%f) %d degrees: '%s'" % (x, y, angle, s)) s = s[1:(-1)] match = re.match('10\\^\\{(.+)\\}', s) if match: exp = match.group(1) if debugText: print (' exponent=%s' % exp) font = self._get_font_ttf(prop) font.set_text('10', 0.0) (w, h) = font.get_width_height() w /= 64.0 h /= 64.0 self.draw_plain_text(gc, x, y, '10', prop, angle) propexp = prop.copy() propexp.set_size((prop.get_size_in_points() * 0.8)) self.draw_plain_text(gc, ((x + w) + self.points_to_pixels(self.hackPointsForMathExponent)), (y - (h / 2)), exp, propexp, angle) else: self.draw_plain_text(gc, x, y, s, prop, angle)
'get the width and height in display coords of the string s with FontPropertry prop, ripped right out of backend_ps. This method must be kept in sync with draw_math_text.'
def get_math_text_width_height(self, s, prop):
if debugText: print 'get_math_text_width_height:' s = s[1:(-1)] match = re.match('10\\^\\{(.+)\\}', s) if match: exp = match.group(1) if debugText: print (' exponent=%s' % exp) font = self._get_font_ttf(prop) font.set_text('10', 0.0) (w1, h1) = font.get_width_height() propexp = prop.copy() propexp.set_size((prop.get_size_in_points() * 0.8)) fontexp = self._get_font_ttf(propexp) fontexp.set_text(exp, 0.0) (w2, h2) = fontexp.get_width_height() w = (w1 + w2) h = (h1 + (h2 / 2)) w /= 64.0 h /= 64.0 w += self.points_to_pixels(self.hackPointsForMathExponent) if debugText: print (' math string=%s w,h=(%f,%f)' % (s, w, h)) else: (w, h) = self.get_text_width_height(s, prop, False) return (w, h)
'return true if y small numbers are top for renderer Is used for drawing text (text.py) and images (image.py) only'
def flipy(self):
return True
'return the canvas width and height in display coords'
def get_canvas_width_height(self):
return (self.width, self.height)
'Update the EMF file with the current handle, but only if it isn\'t the same as the last one. Don\'t want to flood the file with duplicate info.'
def set_handle(self, type, handle):
if (self.lastHandle[type] != handle): self.emf.SelectObject(handle) self.lastHandle[type] = handle
'Look up the handle for the font based on the dict of properties *and* the rotation angle, since in EMF the font rotation is a part of the font definition.'
def get_font_handle(self, prop, angle):
prop = EMFFontProperties(prop, angle) size = int((prop.get_size_in_points() * self.pointstodpi)) face = prop.get_name() key = hash(prop) handle = self._fontHandle.get(key) if (handle is None): handle = self.emf.CreateFont((- size), 0, (int(angle) * 10), (int(angle) * 10), pyemf.FW_NORMAL, 0, 0, 0, pyemf.ANSI_CHARSET, pyemf.OUT_DEFAULT_PRECIS, pyemf.CLIP_DEFAULT_PRECIS, pyemf.DEFAULT_QUALITY, (pyemf.DEFAULT_PITCH | pyemf.FF_DONTCARE), face) if debugHandle: print ('get_font_handle: creating handle=%d for face=%s size=%d' % (handle, face, size)) self._fontHandle[key] = handle if debugHandle: print (' found font handle %d for face=%s size=%d' % (handle, face, size)) self.set_handle('font', handle) return handle
'Select a pen that includes the color, line width and line style. Return the pen if it will draw a line, or None if the pen won\'t produce any output (i.e. the style is PS_NULL)'
def select_pen(self, gc):
pen = EMFPen(self.emf, gc) key = hash(pen) handle = self._fontHandle.get(key) if (handle is None): handle = pen.get_handle() self._fontHandle[key] = handle if debugHandle: print (' found pen handle %d' % handle) self.set_handle('pen', handle) if (pen.style != pyemf.PS_NULL): return pen else: return None
'Select a fill color, and return the brush if the color is valid or None if this won\'t produce a fill operation.'
def select_brush(self, rgb):
if (rgb is not None): brush = EMFBrush(self.emf, rgb) key = hash(brush) handle = self._fontHandle.get(key) if (handle is None): handle = brush.get_handle() self._fontHandle[key] = handle if debugHandle: print (' found brush handle %d' % handle) self.set_handle('brush', handle) return brush else: return None
'get the true type font properties, used because EMFs on windows will use true type fonts.'
def _get_font_ttf(self, prop):
key = hash(prop) font = _fontd.get(key) if (font is None): fname = findfont(prop) if debugText: print ('_get_font_ttf: name=%s' % fname) font = FT2Font(str(fname)) _fontd[key] = font font.clear() size = prop.get_size_in_points() font.set_size(size, self.dpi) return font
'get the width and height in display coords of the string s with FontPropertry prop, ripped right out of backend_ps'
def get_text_width_height(self, s, prop, ismath):
if debugText: print ('get_text_width_height: ismath=%s properties: %s' % (str(ismath), str(prop))) if ismath: if debugText: print (' MATH TEXT! = %s' % str(ismath)) (w, h) = self.get_math_text_width_height(s, prop) return (w, h) font = self._get_font_ttf(prop) font.set_text(s, 0.0) (w, h) = font.get_width_height() w /= 64.0 h /= 64.0 if debugText: print (' text string=%s w,h=(%f,%f)' % (s, w, h)) return (w, h)
'Draw the figure using the renderer'
def draw(self):
pass
'Override to use cairo (rather than GDK) renderer'
def _renderer_init(self):
if _debug: print ('%s.%s()' % (self.__class__.__name__, _fn_name())) self._renderer = RendererGTKCairo(self.figure.dpi)
'w,h is the figure w,h not the pixmap w,h'
def set_width_height(self, width, height):
(self.width, self.height) = (width, height)
'Draw the text rotated 90 degrees, other angles are not supported'
def _draw_rotated_text(self, gc, x, y, s, prop, angle):
gdrawable = self.gdkDrawable ggc = gc.gdkGC (layout, inkRect, logicalRect) = self._get_pango_layout(s, prop) (l, b, w, h) = inkRect x = int((x - h)) y = int((y - w)) if ((x < 0) or (y < 0)): return key = (x, y, s, angle, hash(prop)) imageVert = self.rotated.get(key) if (imageVert != None): gdrawable.draw_image(ggc, imageVert, 0, 0, x, y, h, w) return imageBack = gdrawable.get_image(x, y, w, h) imageVert = gdrawable.get_image(x, y, h, w) imageFlip = gtk.gdk.Image(type=gdk.IMAGE_FASTEST, visual=gdrawable.get_visual(), width=w, height=h) if ((imageFlip == None) or (imageBack == None) or (imageVert == None)): warnings.warn('Could not renderer vertical text') return imageFlip.set_colormap(self._cmap) for i in range(w): for j in range(h): imageFlip.put_pixel(i, j, imageVert.get_pixel(j, ((w - i) - 1))) gdrawable.draw_image(ggc, imageFlip, 0, 0, x, y, w, h) gdrawable.draw_layout(ggc, x, (y - b), layout) imageIn = gdrawable.get_image(x, y, w, h) for i in range(w): for j in range(h): imageVert.put_pixel(j, i, imageIn.get_pixel(((w - i) - 1), j)) gdrawable.draw_image(ggc, imageBack, 0, 0, x, y, w, h) gdrawable.draw_image(ggc, imageVert, 0, 0, x, y, h, w) self.rotated[key] = imageVert
'Create a pango layout instance for Text \'s\' with properties \'prop\'. Return - pango layout (from cache if already exists) Note that pango assumes a logical DPI of 96 Ref: pango/fonts.c/pango_font_description_set_size() manual page'
def _get_pango_layout(self, s, prop):
key = (self.dpi, s, hash(prop)) value = self.layoutd.get(key) if (value != None): return value size = ((prop.get_size_in_points() * self.dpi) / 96.0) size = round(size) font_str = ('%s, %s %i' % (prop.get_name(), prop.get_style(), size)) font = pango.FontDescription(font_str) font.set_weight(self.fontweights[prop.get_weight()]) layout = self.gtkDA.create_pango_layout(s) layout.set_font_description(font) (inkRect, logicalRect) = layout.get_pixel_extents() self.layoutd[key] = (layout, inkRect, logicalRect) return (layout, inkRect, logicalRect)
'rgb - an RGB tuple (three 0.0-1.0 values) return an allocated gtk.gdk.Color'
def rgb_to_gdk_color(self, rgb):
try: return self._cached[tuple(rgb)] except KeyError: color = self._cached[tuple(rgb)] = self._cmap.alloc_color(int((rgb[0] * 65535)), int((rgb[1] * 65535)), int((rgb[2] * 65535))) return color
'Draw to the Agg backend and then copy the image to the qt.drawable. In Qt, all drawing should be done inside of here when a widget is shown onscreen.'
def paintEvent(self, e):
FigureCanvasQT.paintEvent(self, e) if DEBUG: print 'FigureCanvasQtAgg.paintEvent: ', self, self.get_width_height() p = qt.QPainter(self) if (type(self.replot) is bool): if self.replot: FigureCanvasAgg.draw(self) if (qt.QImage.systemByteOrder() == qt.QImage.LittleEndian): stringBuffer = self.renderer._renderer.tostring_bgra() else: stringBuffer = self.renderer._renderer.tostring_argb() qImage = qt.QImage(stringBuffer, self.renderer.width, self.renderer.height, 32, None, 0, qt.QImage.IgnoreEndian) self.pixmap.convertFromImage(qImage, qt.QPixmap.Color) p.drawPixmap(qt.QPoint(0, 0), self.pixmap) if self.drawRect: p.setPen(qt.QPen(qt.Qt.black, 1, qt.Qt.DotLine)) p.drawRect(self.rect[0], self.rect[1], self.rect[2], self.rect[3]) else: bbox = self.replot (l, b, r, t) = bbox.extents w = (int(r) - int(l)) h = (int(t) - int(b)) reg = self.copy_from_bbox(bbox) stringBuffer = reg.to_string_argb() qImage = qt.QImage(stringBuffer, w, h, 32, None, 0, qt.QImage.IgnoreEndian) self.pixmap.convertFromImage(qImage, qt.QPixmap.Color) p.drawPixmap(qt.QPoint(l, (self.renderer.height - t)), self.pixmap) p.end() self.replot = False self.drawRect = False
'Draw the figure when xwindows is ready for the update'
def draw(self):
if DEBUG: print 'FigureCanvasQtAgg.draw', self self.replot = True FigureCanvasAgg.draw(self) self.repaint(False)
'Blit the region in bbox'
def blit(self, bbox=None):
self.replot = bbox self.repaint(False)
'update drawing area only if idle'
def draw_idle(self):
d = self._idle self._idle = False def idle_draw(*args): self.draw() self._idle = True if d: self._tkcanvas.after_idle(idle_draw)
'returns the Tk widget used to implement FigureCanvasTkAgg. Although the initial implementation uses a Tk canvas, this routine is intended to hide that fact.'
def get_tk_widget(self):
return self._tkcanvas
'MouseWheel event processor'
def scroll_event_windows(self, event):
w = event.widget.winfo_containing(event.x_root, event.y_root) if (w == self._tkcanvas): x = (event.x_root - w.winfo_rootx()) y = (event.y_root - w.winfo_rooty()) y = (self.figure.bbox.height - y) step = (event.delta / 120.0) FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=event)
'this function doesn\'t segfault but causes the PyEval_RestoreThread: NULL state bug on win32'
def show(self):
def destroy(*args): self.window = None Gcf.destroy(self._num) if (not self._shown): self.canvas._tkcanvas.bind('<Destroy>', destroy) _focus = windowing.FocusManager() if (not self._shown): self.window.deiconify() if (sys.platform == 'win32'): self.window.update() else: self.canvas.draw() self._shown = True
'update drawing area only if idle'
def dynamic_update(self):
self.canvas.draw_idle()
'Draw the math text using matplotlib.mathtext'
def draw_mathtext(self, gc, x, y, s, prop, angle):
if __debug__: verbose.report('RendererAgg.draw_mathtext', 'debug-annoying') (ox, oy, width, height, descent, font_image, used_characters) = self.mathtext_parser.parse(s, self.dpi, prop) x = (int(x) + ox) y = (int(y) - oy) self._renderer.draw_text_image(font_image, x, (y + 1), angle, gc)
'Render the text'
def draw_text(self, gc, x, y, s, prop, angle, ismath):
if __debug__: verbose.report('RendererAgg.draw_text', 'debug-annoying') if ismath: return self.draw_mathtext(gc, x, y, s, prop, angle) font = self._get_agg_font(prop) if (font is None): return None if ((len(s) == 1) and (ord(s) > 127)): font.load_char(ord(s), flags=LOAD_FORCE_AUTOHINT) else: font.set_text(s, 0, flags=LOAD_FORCE_AUTOHINT) font.draw_glyphs_to_bitmap() self._renderer.draw_text_image(font.get_image(), int(x), (int(y) + 1), angle, gc)
'get the width and height in display coords of the string s with FontPropertry prop # passing rgb is a little hack to make cacheing in the # texmanager more efficient. It is not meant to be used # outside the backend'
def get_text_width_height_descent(self, s, prop, ismath):
if (ismath == 'TeX'): size = prop.get_size_in_points() texmanager = self.get_texmanager() Z = texmanager.get_grey(s, size, self.dpi) (m, n) = Z.shape return (n, m, 0) if ismath: (ox, oy, width, height, descent, fonts, used_characters) = self.mathtext_parser.parse(s, self.dpi, prop) return (width, height, descent) font = self._get_agg_font(prop) font.set_text(s, 0.0, flags=LOAD_FORCE_AUTOHINT) (w, h) = font.get_width_height() d = font.get_descent() w /= 64.0 h /= 64.0 d /= 64.0 return (w, h, d)
'return the canvas width and height in display coords'
def get_canvas_width_height(self):
return (self.width, self.height)
'Get the font for text instance t, cacheing for efficiency'
def _get_agg_font(self, prop):
if __debug__: verbose.report('RendererAgg._get_agg_font', 'debug-annoying') key = hash(prop) font = self._fontd.get(key) if (font is None): fname = findfont(prop) font = self._fontd.get(fname) if (font is None): font = FT2Font(str(fname)) self._fontd[fname] = font self._fontd[key] = font font.clear() size = prop.get_size_in_points() font.set_size(size, self.dpi) return font
'convert point measures to pixes using dpi and the pixels per inch of the display'
def points_to_pixels(self, points):
if __debug__: verbose.report('RendererAgg.points_to_pixels', 'debug-annoying') return ((points * self.dpi) / 72.0)
'Draw the figure using the renderer'
def draw(self):
if __debug__: verbose.report('FigureCanvasAgg.draw', 'debug-annoying') self.renderer = self.get_renderer() self.figure.draw(self.renderer)
'set the canvas size in pixels'
def resize(self, width, height):
self.window.resize(width, height)
'Render the figure using agg.'
def draw(self, drawDC=None):
DEBUG_MSG('draw()', 1, self) FigureCanvasAgg.draw(self) self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None) self._isDrawn = True self.gui_repaint(drawDC=drawDC)
'Transfer the region of the agg buffer defined by bbox to the display. If bbox is None, the entire buffer is transferred.'
def blit(self, bbox=None):
if (bbox is None): self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None) self.gui_repaint() return (l, b, w, h) = bbox.bounds r = (l + w) t = (b + h) x = int(l) y = int((self.bitmap.GetHeight() - t)) srcBmp = _convert_agg_to_wx_bitmap(self.get_renderer(), None) srcDC = wx.MemoryDC() srcDC.SelectObject(srcBmp) destDC = wx.MemoryDC() destDC.SelectObject(self.bitmap) destDC.BeginDrawing() destDC.Blit(x, y, int(w), int(h), srcDC, x, y) destDC.EndDrawing() destDC.SelectObject(wx.NullBitmap) srcDC.SelectObject(wx.NullBitmap) self.gui_repaint()
''
def __init__(self, dpi):
if _debug: print ('%s.%s()' % (self.__class__.__name__, _fn_name())) self.dpi = dpi self.text_ctx = cairo.Context(cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1)) self.mathtext_parser = MathTextParser('Cairo')
'Draw to the Agg backend and then copy the image to the qt.drawable. In Qt, all drawing should be done inside of here when a widget is shown onscreen.'
def paintEvent(self, e):
if DEBUG: print 'FigureCanvasQtAgg.paintEvent: ', self, self.get_width_height() if (type(self.replot) is bool): if self.replot: FigureCanvasAgg.draw(self) if (QtCore.QSysInfo.ByteOrder == QtCore.QSysInfo.LittleEndian): stringBuffer = self.renderer._renderer.tostring_bgra() else: stringBuffer = self.renderer._renderer.tostring_argb() qImage = QtGui.QImage(stringBuffer, self.renderer.width, self.renderer.height, QtGui.QImage.Format_ARGB32) p = QtGui.QPainter(self) p.drawPixmap(QtCore.QPoint(0, 0), QtGui.QPixmap.fromImage(qImage)) if self.drawRect: p.setPen(QtGui.QPen(QtCore.Qt.black, 1, QtCore.Qt.DotLine)) p.drawRect(self.rect[0], self.rect[1], self.rect[2], self.rect[3]) p.end() else: bbox = self.replot (l, b, r, t) = bbox.extents w = (int(r) - int(l)) h = (int(t) - int(b)) t = (int(b) + h) reg = self.copy_from_bbox(bbox) stringBuffer = reg.to_string_argb() qImage = QtGui.QImage(stringBuffer, w, h, QtGui.QImage.Format_ARGB32) pixmap = QtGui.QPixmap.fromImage(qImage) p = QtGui.QPainter(self) p.drawPixmap(QtCore.QPoint(l, (self.renderer.height - t)), pixmap) p.end() self.replot = False self.drawRect = False
'Draw the figure when xwindows is ready for the update'
def draw(self):
if DEBUG: print 'FigureCanvasQtAgg.draw', self self.replot = True FigureCanvasAgg.draw(self) self.update() QtGui.qApp.processEvents()
'Blit the region in bbox'
def blit(self, bbox=None):
self.replot = bbox (l, b, w, h) = bbox.bounds t = (b + h) self.update(l, (self.renderer.height - t), w, h)
'set the canvas size in pixels'
def resize(self, width, height):
self.window.resize(width, height)
'coordinates: should we show the coordinates on the right?'
def __init__(self, canvas, parent, coordinates=True):
self.canvas = canvas self.coordinates = coordinates QtGui.QToolBar.__init__(self, parent) NavigationToolbar2.__init__(self, canvas)
'use a :func:`time.strptime` format string for conversion'
def __init__(self, fmt='%Y-%m-%d', missing='Null', missingval=None):
converter.__init__(self, missing, missingval) self.fmt = fmt
'use a :func:`time.strptime` format string for conversion'
def __init__(self, fmt='%Y-%m-%d', missing='Null', missingval=None):
converter.__init__(self, missing, missingval) self.fmt = fmt
'*signals* is a sequence of valid signals'
def __init__(self, signals):
self.signals = set(signals) self.callbacks = dict([(s, dict()) for s in signals]) self._cid = 0
'make sure *s* is a valid signal or raise a ValueError'
def _check_signal(self, s):
if (s not in self.signals): signals = list(self.signals) signals.sort() raise ValueError(('Unknown signal "%s"; valid signals are %s' % (s, signals)))
'register *func* to be called when a signal *s* is generated func will be called'
def connect(self, s, func):
self._check_signal(s) self._cid += 1 self.callbacks[s][self._cid] = func return self._cid
'disconnect the callback registered with callback id *cid*'
def disconnect(self, cid):
for (eventname, callbackd) in self.callbacks.items(): try: del callbackd[cid] except KeyError: continue else: return
'process signal *s*. All of the functions registered to receive callbacks on *s* will be called with *\*args* and *\*\*kwargs*'
def process(self, s, *args, **kwargs):
self._check_signal(s) for func in self.callbacks[s].values(): func(*args, **kwargs)
'Build re object based on the keys of the current dictionary'
def _make_regex(self):
return re.compile('|'.join(map(re.escape, self.keys())))
'Handler invoked for each regex *match*'
def __call__(self, match):
return self[match.group(0)]
'Translate *text*, returns the modified text.'
def xlat(self, text):
return self._make_regex().sub(self, text)
'Append an element overwriting the oldest one.'
def append(self, x):
self.data[self.cur] = x self.cur = ((self.cur + 1) % self.max)
'return list of elements in correct order'
def get(self):
return (self.data[self.cur:] + self.data[:self.cur])
'append an element at the end of the buffer'
def append(self, x):
self.data.append(x) if (len(self.data) == self.max): self.cur = 0 self.__class__ = __Full
'Return a list of elements from the oldest to the newest.'
def get(self):
return self.data
'return the current element, or None'
def __call__(self):
if (not len(self._elements)): return self._default else: return self._elements[self._pos]
'move the position forward and return the current element'
def forward(self):
N = len(self._elements) if (self._pos < (N - 1)): self._pos += 1 return self()
'move the position back and return the current element'
def back(self):
if (self._pos > 0): self._pos -= 1 return self()
'push object onto stack at current position - all elements occurring later than the current position are discarded'
def push(self, o):
self._elements = self._elements[:(self._pos + 1)] self._elements.append(o) self._pos = (len(self._elements) - 1) return self()
'push the first element onto the top of the stack'
def home(self):
if (not len(self._elements)): return self.push(self._elements[0]) return self()
'empty the stack'
def clear(self):
self._pos = (-1) self._elements = []
'raise *o* to the top of the stack and return *o*. *o* must be in the stack'
def bubble(self, o):
if (o not in self._elements): raise ValueError('Unknown element o') old = self._elements[:] self.clear() bubbles = [] for thiso in old: if (thiso == o): bubbles.append(thiso) else: self.push(thiso) for thiso in bubbles: self.push(o) return o
'remove element *o* from the stack'
def remove(self, o):
if (o not in self._elements): raise ValueError('Unknown element o') old = self._elements[:] self.clear() for thiso in old: if (thiso == o): continue else: self.push(thiso)
'Clean dead weak references from the dictionary'
def clean(self):
mapping = self._mapping for (key, val) in mapping.items(): if (key() is None): del mapping[key] val.remove(key)
'Join given arguments into the same set. Accepts one or more arguments.'
def join(self, a, *args):
mapping = self._mapping set_a = mapping.setdefault(ref(a), [ref(a)]) for arg in args: set_b = mapping.get(ref(arg)) if (set_b is None): set_a.append(ref(arg)) mapping[ref(arg)] = set_a elif (set_b is not set_a): if (len(set_b) > len(set_a)): (set_a, set_b) = (set_b, set_a) set_a.extend(set_b) for elem in set_b: mapping[elem] = set_a self.clean()
'Returns True if *a* and *b* are members of the same set.'
def joined(self, a, b):
self.clean() mapping = self._mapping try: return (mapping[ref(a)] is mapping[ref(b)]) except KeyError: return False
'Iterate over each of the disjoint sets as a list. The iterator is invalid if interleaved with calls to join().'
def __iter__(self):
self.clean() class Token: pass token = Token() for group in self._mapping.itervalues(): if (not (group[(-1)] is token)): (yield [x() for x in group]) group.append(token) for group in self._mapping.itervalues(): if (group[(-1)] is token): del group[(-1)]
'Returns all of the items joined with *a*, including itself.'
def get_siblings(self, a):
self.clean() siblings = self._mapping.get(ref(a), [ref(a)]) return [x() for x in siblings]
'Return the :class:`~matplotlib.transforms.Transform` object associated with this scale.'
def get_transform(self):
raise NotImplementedError
'Set the :class:`~matplotlib.ticker.Locator` and :class:`~matplotlib.ticker.Formatter` objects on the given axis to match this scale.'
def set_default_locators_and_formatters(self, axis):
raise NotImplementedError
'Returns the range *vmin*, *vmax*, possibly limited to the domain supported by this scale. *minpos* should be the minimum positive value in the data. This is used by log scales to determine a minimum value.'
def limit_range_for_scale(self, vmin, vmax, minpos):
return (vmin, vmax)
'Set the locators and formatters to reasonable defaults for linear scaling.'
def set_default_locators_and_formatters(self, axis):
axis.set_major_locator(AutoLocator()) axis.set_major_formatter(ScalarFormatter()) axis.set_minor_locator(NullLocator()) axis.set_minor_formatter(NullFormatter())
'The transform for linear scaling is just the :class:`~matplotlib.transforms.IdentityTransform`.'
def get_transform(self):
return IdentityTransform()
'*basex*/*basey*: The base of the logarithm *subsx*/*subsy*: Where to place the subticks between each major tick. Should be a sequence of integers. For example, in a log10 scale: ``[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]`` will place 10 logarithmically spaced minor ticks between each major tick.'
def __init__(self, axis, **kwargs):
if (axis.axis_name == 'x'): base = kwargs.pop('basex', 10.0) subs = kwargs.pop('subsx', None) else: base = kwargs.pop('basey', 10.0) subs = kwargs.pop('subsy', None) if (base == 10.0): self._transform = self.Log10Transform() elif (base == 2.0): self._transform = self.Log2Transform() elif (base == np.e): self._transform = self.NaturalLogTransform() else: self._transform = self.LogTransform(base) self.base = base self.subs = subs
'Set the locators and formatters to specialized versions for log scaling.'
def set_default_locators_and_formatters(self, axis):
axis.set_major_locator(LogLocator(self.base)) axis.set_major_formatter(LogFormatterMathtext(self.base)) axis.set_minor_locator(LogLocator(self.base, self.subs)) axis.set_minor_formatter(NullFormatter())
'Return a :class:`~matplotlib.transforms.Transform` instance appropriate for the given logarithm base.'
def get_transform(self):
return self._transform
'Limit the domain to positive values.'
def limit_range_for_scale(self, vmin, vmax, minpos):
return ((((vmin <= 0.0) and minpos) or vmin), (((vmax <= 0.0) and minpos) or vmax))
'*basex*/*basey*: The base of the logarithm *linthreshx*/*linthreshy*: The range (-*x*, *x*) within which the plot is linear (to avoid having the plot go to infinity around zero). *subsx*/*subsy*: Where to place the subticks between each major tick. Should be a sequence of integers. For example, in a log10 scale: ``[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]`` will place 10 logarithmically spaced minor ticks between each major tick.'
def __init__(self, axis, **kwargs):
if (axis.axis_name == 'x'): base = kwargs.pop('basex', 10.0) linthresh = kwargs.pop('linthreshx', 2.0) subs = kwargs.pop('subsx', None) else: base = kwargs.pop('basey', 10.0) linthresh = kwargs.pop('linthreshy', 2.0) subs = kwargs.pop('subsy', None) self._transform = self.SymmetricalLogTransform(base, linthresh) self.base = base self.linthresh = linthresh self.subs = subs
'Set the locators and formatters to specialized versions for symmetrical log scaling.'
def set_default_locators_and_formatters(self, axis):
axis.set_major_locator(SymmetricalLogLocator(self.get_transform())) axis.set_major_formatter(LogFormatterMathtext(self.base)) axis.set_minor_locator(SymmetricalLogLocator(self.get_transform(), self.subs)) axis.set_minor_formatter(NullFormatter())
'Return a :class:`SymmetricalLogTransform` instance.'
def get_transform(self):
return self._transform
'Open a grouping element with label *s*. Is only currently used by :mod:`~matplotlib.backends.backend_svg`'
def open_group(self, s):
pass
'Close a grouping element with label *s* Is only currently used by :mod:`~matplotlib.backends.backend_svg`'
def close_group(self, s):
pass
'Draws a :class:`~matplotlib.path.Path` instance using the given affine transform.'
def draw_path(self, gc, path, transform, rgbFace=None):
raise NotImplementedError
'Draws a marker at each of the vertices in path. This includes all vertices, including control points on curves. To avoid that behavior, those vertices should be removed before calling this function. *gc* the :class:`GraphicsContextBase` instance *marker_trans* is an affine transform applied to the marker. *trans* is an affine transform applied to the path. This provides a fallback implementation of draw_markers that makes multiple calls to :meth:`draw_path`. Some backends may want to override this method in order to draw the marker only once and reuse it multiple times.'
def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None):
tpath = trans.transform_path(path) for (vertices, codes) in tpath.iter_segments(): if len(vertices): (x, y) = vertices[(-2):] self.draw_path(gc, marker_path, (marker_trans + transforms.Affine2D().translate(x, y)), rgbFace)
'Draws a collection of paths, selecting drawing properties from the lists *facecolors*, *edgecolors*, *linewidths*, *linestyles* and *antialiaseds*. *offsets* is a list of offsets to apply to each of the paths. The offsets in *offsets* are first transformed by *offsetTrans* before being applied. This provides a fallback implementation of :meth:`draw_path_collection` that makes multiple calls to draw_path. Some backends may want to override this in order to render each set of path data only once, and then reference that path multiple times with the different offsets, colors, styles etc. The generator methods :meth:`_iter_collection_raw_paths` and :meth:`_iter_collection` are provided to help with (and standardize) the implementation across backends. It is highly recommended to use those generators, so that changes to the behavior of :meth:`draw_path_collection` can be made globally.'
def draw_path_collection(self, master_transform, cliprect, clippath, clippath_trans, paths, all_transforms, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls):
path_ids = [] for (path, transform) in self._iter_collection_raw_paths(master_transform, paths, all_transforms): path_ids.append((path, transform)) for (xo, yo, path_id, gc, rgbFace) in self._iter_collection(path_ids, cliprect, clippath, clippath_trans, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls): (path, transform) = path_id transform = transforms.Affine2D(transform.get_matrix()).translate(xo, yo) self.draw_path(gc, path, transform, rgbFace)
'This provides a fallback implementation of :meth:`draw_quad_mesh` that generates paths and then calls :meth:`draw_path_collection`.'
def draw_quad_mesh(self, master_transform, cliprect, clippath, clippath_trans, meshWidth, meshHeight, coordinates, offsets, offsetTrans, facecolors, antialiased, showedges):
from matplotlib.collections import QuadMesh paths = QuadMesh.convert_mesh_to_paths(meshWidth, meshHeight, coordinates) if showedges: edgecolors = np.array([[0.0, 0.0, 0.0, 1.0]], np.float_) linewidths = np.array([1.0], np.float_) else: edgecolors = facecolors linewidths = np.array([0.0], np.float_) return self.draw_path_collection(master_transform, cliprect, clippath, clippath_trans, paths, [], offsets, offsetTrans, facecolors, edgecolors, linewidths, [], [antialiased], [None])
'This is a helper method (along with :meth:`_iter_collection`) to make it easier to write a space-efficent :meth:`draw_path_collection` implementation in a backend. This method yields all of the base path/transform combinations, given a master transform, a list of paths and list of transforms. The arguments should be exactly what is passed in to :meth:`draw_path_collection`. The backend should take each yielded path and transform and create an object that can be referenced (reused) later.'
def _iter_collection_raw_paths(self, master_transform, paths, all_transforms):
Npaths = len(paths) Ntransforms = len(all_transforms) N = max(Npaths, Ntransforms) if (Npaths == 0): return transform = transforms.IdentityTransform() for i in xrange(N): path = paths[(i % Npaths)] if Ntransforms: transform = all_transforms[(i % Ntransforms)] (yield (path, (transform + master_transform)))
'This is a helper method (along with :meth:`_iter_collection_raw_paths`) to make it easier to write a space-efficent :meth:`draw_path_collection` implementation in a backend. This method yields all of the path, offset and graphics context combinations to draw the path collection. The caller should already have looped over the results of :meth:`_iter_collection_raw_paths` to draw this collection. The arguments should be the same as that passed into :meth:`draw_path_collection`, with the exception of *path_ids*, which is a list of arbitrary objects that the backend will use to reference one of the paths created in the :meth:`_iter_collection_raw_paths` stage. Each yielded result is of the form:: xo, yo, path_id, gc, rgbFace where *xo*, *yo* is an offset; *path_id* is one of the elements of *path_ids*; *gc* is a graphics context and *rgbFace* is a color to use for filling the path.'
def _iter_collection(self, path_ids, cliprect, clippath, clippath_trans, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls):
Npaths = len(path_ids) Noffsets = len(offsets) N = max(Npaths, Noffsets) Nfacecolors = len(facecolors) Nedgecolors = len(edgecolors) Nlinewidths = len(linewidths) Nlinestyles = len(linestyles) Naa = len(antialiaseds) Nurls = len(urls) if (((Nfacecolors == 0) and (Nedgecolors == 0)) or (Npaths == 0)): return if Noffsets: toffsets = offsetTrans.transform(offsets) gc = self.new_gc() gc.set_clip_rectangle(cliprect) if (clippath is not None): clippath = transforms.TransformedPath(clippath, clippath_trans) gc.set_clip_path(clippath) if (Nfacecolors == 0): rgbFace = None if (Nedgecolors == 0): gc.set_linewidth(0.0) (xo, yo) = (0, 0) for i in xrange(N): path_id = path_ids[(i % Npaths)] if Noffsets: (xo, yo) = toffsets[(i % Noffsets)] if Nfacecolors: rgbFace = facecolors[(i % Nfacecolors)] if Nedgecolors: gc.set_foreground(edgecolors[(i % Nedgecolors)]) if Nlinewidths: gc.set_linewidth(linewidths[(i % Nlinewidths)]) if Nlinestyles: gc.set_dashes(*linestyles[(i % Nlinestyles)]) if ((rgbFace is not None) and (len(rgbFace) == 4)): gc.set_alpha(rgbFace[(-1)]) rgbFace = rgbFace[:3] gc.set_antialiased(antialiaseds[(i % Naa)]) if Nurls: gc.set_url(urls[(i % Nurls)]) (yield (xo, yo, path_id, gc, rgbFace))
'Get the factor by which to magnify images passed to :meth:`draw_image`. Allows a backend to have images at a different resolution to other artists.'
def get_image_magnification(self):
return 1.0
'Draw the image instance into the current axes; *x* is the distance in pixels from the left hand side of the canvas. *y* the distance from the origin. That is, if origin is upper, y is the distance from top. If origin is lower, y is the distance from bottom *im* the :class:`matplotlib._image.Image` instance *bbox* a :class:`matplotlib.transforms.Bbox` instance for clipping, or None'
def draw_image(self, x, y, im, bbox, clippath=None, clippath_trans=None):
raise NotImplementedError
'overwrite this method for renderers that do not necessarily want to rescale and composite raster images. (like SVG)'
def option_image_nocomposite(self):
return False
'Draw the text instance *gc* the :class:`GraphicsContextBase` instance *x* the x location of the text in display coords *y* the y location of the text in display coords *s* a :class:`matplotlib.text.Text` instance *prop* a :class:`matplotlib.font_manager.FontProperties` instance *angle* the rotation angle in degrees **backend implementers note** When you are trying to determine if you have gotten your bounding box right (which is what enables the text layout/alignment to work properly), it helps to change the line in text.py:: if 0: bbox_artist(self, renderer) to if 1, and then the actual bounding box will be blotted along with your text.'
def draw_text(self, gc, x, y, s, prop, angle, ismath=False):
raise NotImplementedError
'Return true if y small numbers are top for renderer Is used for drawing text (:mod:`matplotlib.text`) and images (:mod:`matplotlib.image`) only'
def flipy(self):
return True
'return the canvas width and height in display coords'
def get_canvas_width_height(self):
return (1, 1)
'return the :class:`matplotlib.texmanager.TexManager` instance'
def get_texmanager(self):
if (self._texmanager is None): from matplotlib.texmanager import TexManager self._texmanager = TexManager() return self._texmanager
'get the width and height, and the offset from the bottom to the baseline (descent), in display coords of the string s with :class:`~matplotlib.font_manager.FontProperties` prop'
def get_text_width_height_descent(self, s, prop, ismath):
raise NotImplementedError
'Return an instance of a :class:`GraphicsContextBase`'
def new_gc(self):
return GraphicsContextBase()
'Convert points to display units *points* a float or a numpy array of float return points converted to pixels You need to override this function (unless your backend doesn\'t have a dpi, eg, postscript or svg). Some imaging systems assume some value for pixels per inch:: points to pixels = points * pixels_per_inch/72.0 * dpi/72.0'
def points_to_pixels(self, points):
return points
'Copy properties from gc to self'
def copy_properties(self, gc):
self._alpha = gc._alpha self._antialiased = gc._antialiased self._capstyle = gc._capstyle self._cliprect = gc._cliprect self._clippath = gc._clippath self._dashes = gc._dashes self._joinstyle = gc._joinstyle self._linestyle = gc._linestyle self._linewidth = gc._linewidth self._rgb = gc._rgb self._hatch = gc._hatch self._url = gc._url self._snap = gc._snap
'Return the alpha value used for blending - not supported on all backends'
def get_alpha(self):
return self._alpha