def vector_lengths( X, P=<NUM_LIT>, axis=None ):

<EOL>warnings.warn('<STR_LIT>', DeprecationWarning)<EOL>import matplotlib.mlab as mlab<EOL>return mlab.vector_lengths( X, P=<NUM_LIT>, axis=axis )<EOL>


<EOL>warnings.warn('<STR_LIT>', DeprecationWarning)<EOL>import matplotlib.mlab as mlab<EOL>return mlab.distances_along_curve( X )<EOL>

This function has been moved to matplotlib.mlab -- please import
it from there


<EOL>warnings.warn('<STR_LIT>', DeprecationWarning)<EOL>import matplotlib.mlab as mlab<EOL>return mlab.path_length(X)<EOL>


<EOL>warnings.warn('<STR_LIT>', DeprecationWarning)<EOL>import matplotlib.mlab as mlab<EOL>return mlab.is_closed_polygon(X)<EOL>


def quad2cubic(q0x, q0y, q1x, q1y, q2x, q2y):

<EOL>warnings.warn('<STR_LIT>', DeprecationWarning)<EOL>import matplotlib.mlab as mlab<EOL>return mlab.quad2cubic(q0x, q0y, q1x, q1y, q2x, q2y)<EOL>


def __init__(self, fmt='<STR_LIT>', missing='<STR_LIT>', missingval=None):

converter.__init__(self, missing, missingval)<EOL>self.fmt = fmt<EOL>

use a :func:`time.strptime` format string for conversion


self.signals = set(signals)<EOL>self.callbacks = dict([(s, dict()) for s in signals])<EOL>self._cid = <NUM_LIT:0><EOL>

*signals* is a sequence of valid signals


if s not in self.signals:<EOL><INDENT>signals = list(self.signals)<EOL>signals.sort()<EOL>raise ValueError('<STR_LIT>'%(s, signals))<EOL><DEDENT>

make sure *s* is a valid signal or raise a ValueError


self._check_signal(s)<EOL>self._cid +=<NUM_LIT:1><EOL>self.callbacks[s][self._cid] = func<EOL>return self._cid<EOL>

register *func* to be called when a signal *s* is generated
func will be called


for eventname, callbackd in list(self.callbacks.items()):<EOL><INDENT>try: del callbackd[cid]<EOL>except KeyError: continue<EOL>else: return<EOL><DEDENT>

disconnect the callback registered with callback id *cid*


self._check_signal(s)<EOL>for func in list(self.callbacks[s].values()):<EOL><INDENT>func(*args, **kwargs)<EOL><DEDENT>

process signal *s*.  All of the functions registered to receive
callbacks on *s* will be called with *\*args* and *\*\*kwargs*


return re.compile("<STR_LIT:|>".join(map(re.escape, list(self.keys()))))<EOL>

Build re object based on the keys of the current dictionary


return self[match.group(<NUM_LIT:0>)]<EOL>


return self._make_regex().sub(self, text)<EOL>

Translate *text*, returns the modified text.


self.data.append(x)<EOL>if len(self.data) == self.max:<EOL><INDENT>self.cur = <NUM_LIT:0><EOL>self.__class__ = __Full<EOL><DEDENT>

append an element at the end of the buffer


return self.data<EOL>

Return a list of elements from the oldest to the newest.


if not len(self._elements): return self._default<EOL>else: return self._elements[self._pos]<EOL>


N = len(self._elements)<EOL>if self._pos<N-<NUM_LIT:1>: self._pos += <NUM_LIT:1><EOL>return self()<EOL>

move the position forward and return the current element


if self._pos><NUM_LIT:0>: self._pos -= <NUM_LIT:1><EOL>return self()<EOL>

move the position back and return the current element


self._elements = self._elements[:self._pos+<NUM_LIT:1>]<EOL>self._elements.append(o)<EOL>self._pos = len(self._elements)-<NUM_LIT:1><EOL>return self()<EOL>

push object onto stack at current position - all elements
occurring later than the current position are discarded


if not len(self._elements): return<EOL>self.push(self._elements[<NUM_LIT:0>])<EOL>return self()<EOL>

push the first element onto the top of the stack


self._pos = -<NUM_LIT:1><EOL>self._elements = []<EOL>


if o not in self._elements:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>old = self._elements[:]<EOL>self.clear()<EOL>bubbles = []<EOL>for thiso in old:<EOL><INDENT>if thiso==o: bubbles.append(thiso)<EOL>else: self.push(thiso)<EOL><DEDENT>for thiso in bubbles:<EOL><INDENT>self.push(o)<EOL><DEDENT>return o<EOL>

raise *o* to the top of the stack and return *o*.  *o* must be
in the stack


if o not in self._elements:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>old = self._elements[:]<EOL>self.clear()<EOL>for thiso in old:<EOL><INDENT>if thiso==o: continue<EOL>else: self.push(thiso)<EOL><DEDENT>


mapping = self._mapping<EOL>for key, val in list(mapping.items()):<EOL><INDENT>if key() is None:<EOL><INDENT>del mapping[key]<EOL>val.remove(key)<EOL><DEDENT><DEDENT>

Clean dead weak references from the dictionary


mapping = self._mapping<EOL>set_a = mapping.setdefault(ref(a), [ref(a)])<EOL>for arg in args:<EOL><INDENT>set_b = mapping.get(ref(arg))<EOL>if set_b is None:<EOL><INDENT>set_a.append(ref(arg))<EOL>mapping[ref(arg)] = set_a<EOL><DEDENT>elif set_b is not set_a:<EOL><INDENT>if len(set_b) > len(set_a):<EOL><INDENT>set_a, set_b = set_b, set_a<EOL><DEDENT>set_a.extend(set_b)<EOL>for elem in set_b:<EOL><INDENT>mapping[elem] = set_a<EOL><DEDENT><DEDENT><DEDENT>self.clean()<EOL>

Join given arguments into the same set.  Accepts one or more
arguments.


self.clean()<EOL>mapping = self._mapping<EOL>try:<EOL><INDENT>return mapping[ref(a)] is mapping[ref(b)]<EOL><DEDENT>except KeyError:<EOL><INDENT>return False<EOL><DEDENT>

Returns True if *a* and *b* are members of the same set.


self.clean()<EOL>class Token: pass<EOL>token = Token()<EOL>for group in self._mapping.values():<EOL><INDENT>if not group[-<NUM_LIT:1>] is token:<EOL><INDENT>yield [x() for x in group]<EOL>group.append(token)<EOL><DEDENT><DEDENT>for group in self._mapping.values():<EOL><INDENT>if group[-<NUM_LIT:1>] is token:<EOL><INDENT>del group[-<NUM_LIT:1>]<EOL><DEDENT><DEDENT>

Iterate over each of the disjoint sets as a list.

The iterator is invalid if interleaved with calls to join().


self.clean()<EOL>siblings = self._mapping.get(ref(a), [ref(a)])<EOL>return [x() for x in siblings]<EOL>

Returns all of the items joined with *a*, including itself.


isarray = hasattr(arg, '<STR_LIT>')<EOL>figsize_min = np.array((<NUM_LIT>,<NUM_LIT>)) <EOL>figsize_max = np.array((<NUM_LIT>,<NUM_LIT>)) <EOL>if isarray:<EOL><INDENT>nr,nc = arg.shape[:<NUM_LIT:2>]<EOL>arr_ratio = float(nr)/nc<EOL><DEDENT>else:<EOL><INDENT>arr_ratio = float(arg)<EOL><DEDENT>fig_height = rcParams['<STR_LIT>'][<NUM_LIT:1>]<EOL>newsize = np.array((fig_height/arr_ratio,fig_height))<EOL>newsize /= min(<NUM_LIT:1.0>,*(newsize/figsize_min))<EOL>newsize /= max(<NUM_LIT:1.0>,*(newsize/figsize_max))<EOL>newsize = np.clip(newsize,figsize_min,figsize_max)<EOL>return newsize<EOL>

Create a figure with specified aspect ratio.  If *arg* is a number,
use that aspect ratio.  If *arg* is an array, figaspect will
determine the width and height for a figure that would fit array
preserving aspect ratio.  The figure width, height in inches are
returned.  Be sure to create an axes with equal with and height,
eg

Example usage::

  # make a figure twice as tall as it is wide
  w, h = figaspect(2.)
  fig = Figure(figsize=(w,h))
  ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
  ax.imshow(A, **kwargs)

  # make a figure with the proper aspect for an array
  A = rand(5,3)
  w, h = figaspect(A)
  fig = Figure(figsize=(w,h))
  ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
  ax.imshow(A, **kwargs)

Thanks to Fernando Perez for this function


def __init__(self, left=None, bottom=None, right=None, top=None,<EOL>wspace=None, hspace=None):

self.validate = True<EOL>self.update(left, bottom, right, top, wspace, hspace)<EOL>

All dimensions are fraction of the figure width or height.
All values default to their rc params

The following attributes are available

*left*  = 0.125
    the left side of the subplots of the figure
*right* = 0.9
    the right side of the subplots of the figure
*bottom* = 0.1
    the bottom of the subplots of the figure
*top* = 0.9
    the top of the subplots of the figure
*wspace* = 0.2
    the amount of width reserved for blank space between subplots
*hspace* = 0.2
    the amount of height reserved for white space between subplots
*validate*
    make sure the params are in a legal state (*left*<*right*, etc)


def update(self,left=None, bottom=None, right=None, top=None,<EOL>wspace=None, hspace=None):

thisleft = getattr(self, '<STR_LIT:left>', None)<EOL>thisright = getattr(self, '<STR_LIT:right>', None)<EOL>thistop = getattr(self, '<STR_LIT>', None)<EOL>thisbottom = getattr(self, '<STR_LIT>', None)<EOL>thiswspace = getattr(self, '<STR_LIT>', None)<EOL>thishspace = getattr(self, '<STR_LIT>', None)<EOL>self._update_this('<STR_LIT:left>', left)<EOL>self._update_this('<STR_LIT:right>', right)<EOL>self._update_this('<STR_LIT>', bottom)<EOL>self._update_this('<STR_LIT>', top)<EOL>self._update_this('<STR_LIT>', wspace)<EOL>self._update_this('<STR_LIT>', hspace)<EOL>def reset():<EOL><INDENT>self.left = thisleft<EOL>self.right = thisright<EOL>self.top = thistop<EOL>self.bottom = thisbottom<EOL>self.wspace = thiswspace<EOL>self.hspace = thishspace<EOL><DEDENT>if self.validate:<EOL><INDENT>if self.left>=self.right:<EOL><INDENT>reset()<EOL>raise ValueError('<STR_LIT>')<EOL><DEDENT>if self.bottom>=self.top:<EOL><INDENT>reset()<EOL>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>

Update the current values.  If any kwarg is None, default to
the current value, if set, otherwise to rc


def __init__(self,<EOL>figsize   = None,  <EOL>dpi       = None,  <EOL>facecolor = None,  <EOL>edgecolor = None,  <EOL>linewidth = <NUM_LIT:1.0>,   <EOL>frameon = True,    <EOL>subplotpars = None, <EOL>):

Artist.__init__(self)<EOL>self.callbacks = cbook.CallbackRegistry(('<STR_LIT>', ))<EOL>if figsize is None  : figsize   = rcParams['<STR_LIT>']<EOL>if dpi is None      : dpi       = rcParams['<STR_LIT>']<EOL>if facecolor is None: facecolor = rcParams['<STR_LIT>']<EOL>if edgecolor is None: edgecolor = rcParams['<STR_LIT>']<EOL>self.dpi_scale_trans = Affine2D()<EOL>self.dpi = dpi<EOL>self.bbox_inches = Bbox.from_bounds(<NUM_LIT:0>, <NUM_LIT:0>, *figsize)<EOL>self.bbox = TransformedBbox(self.bbox_inches, self.dpi_scale_trans)<EOL>self.frameon = frameon<EOL>self.transFigure = BboxTransformTo(self.bbox)<EOL>self.patch = self.figurePatch = Rectangle(<EOL>xy=(<NUM_LIT:0>,<NUM_LIT:0>), width=<NUM_LIT:1>, height=<NUM_LIT:1>,<EOL>facecolor=facecolor, edgecolor=edgecolor,<EOL>linewidth=linewidth,<EOL>)<EOL>self._set_artist_props(self.patch)<EOL>self._hold = rcParams['<STR_LIT>']<EOL>self.canvas = None<EOL>if subplotpars is None:<EOL><INDENT>subplotpars = SubplotParams()<EOL><DEDENT>self.subplotpars = subplotpars<EOL>self._axstack = Stack()  <EOL>self.axes = []<EOL>self.clf()<EOL>self._cachedRenderer = None<EOL>

*figsize*
    w,h tuple in inches
*dpi*
    dots per inch
*facecolor*
    the figure patch facecolor; defaults to rc ``figure.facecolor``
*edgecolor*
    the figure patch edge color; defaults to rc ``figure.edgecolor``
*linewidth*
    the figure patch edge linewidth; the default linewidth of the frame
*frameon*
    if False, suppress drawing the figure frame
*subplotpars*
    a :class:`SubplotParams` instance, defaults to rc


def autofmt_xdate(self, bottom=<NUM_LIT>, rotation=<NUM_LIT:30>, ha='<STR_LIT:right>'):

allsubplots = np.alltrue([hasattr(ax, '<STR_LIT>') for ax in self.axes])<EOL>if len(self.axes)==<NUM_LIT:1>:<EOL><INDENT>for label in ax.get_xticklabels():<EOL><INDENT>label.set_ha(ha)<EOL>label.set_rotation(rotation)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if allsubplots:<EOL><INDENT>for ax in self.get_axes():<EOL><INDENT>if ax.is_last_row():<EOL><INDENT>for label in ax.get_xticklabels():<EOL><INDENT>label.set_ha(ha)<EOL>label.set_rotation(rotation)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for label in ax.get_xticklabels():<EOL><INDENT>label.set_visible(False)<EOL><DEDENT>ax.set_xlabel('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if allsubplots:<EOL><INDENT>self.subplots_adjust(bottom=bottom)<EOL><DEDENT>

Date ticklabels often overlap, so it is useful to rotate them
and right align them.  Also, a common use case is a number of
subplots with shared xaxes where the x-axis is date data.  The
ticklabels are often long, and it helps to rotate them on the
bottom subplot and turn them off on other subplots, as well as
turn off xlabels.

*bottom*
    the bottom of the subplots for :meth:`subplots_adjust`
*rotation*
    the rotation of the xtick labels
*ha*
    the horizontal alignment of the xticklabels


get a list of artists contained in the figure


if callable(self._contains): return self._contains(self,mouseevent)<EOL>inside = self.bbox.contains(mouseevent.x,mouseevent.y)<EOL>return inside,{}<EOL>

Test whether the mouse event occurred on the figure.

Returns True,{}


def get_window_extent(self, *args, **kwargs):

return self.bbox<EOL>

get the figure bounding box in display space; kwargs are void


x = kwargs.pop('<STR_LIT:x>', <NUM_LIT:0.5>)<EOL>y = kwargs.pop('<STR_LIT:y>', <NUM_LIT>)<EOL>if ('<STR_LIT>' not in kwargs) and ('<STR_LIT>' not in kwargs):<EOL><INDENT>kwargs['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>if ('<STR_LIT>' not in kwargs) and ('<STR_LIT>' not in kwargs):<EOL><INDENT>kwargs['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>t = self.text(x, y, t, **kwargs)<EOL>return t<EOL>

Add a centered title to the figure.

kwargs are :class:`matplotlib.text.Text` properties.  Using figure
coordinates, the defaults are:

  - *x* = 0.5
      the x location of text in figure coords

  - *y* = 0.98
      the y location of the text in figure coords

  - *horizontalalignment* = 'center'
      the horizontal alignment of the text

  - *verticalalignment* = 'top'
      the vertical alignment of the text

A :class:`matplotlib.text.Text` instance is returned.

Example::

  fig.subtitle('this is the figure title', fontsize=12)


self.canvas = canvas<EOL>

Set the canvas the contains the figure

ACCEPTS: a FigureCanvas instance


if b is None: self._hold = not self._hold<EOL>else: self._hold = b<EOL>

Set the hold state.  If hold is None (default), toggle the
hold state.  Else set the hold state to boolean value b.

Eg::

    hold()      # toggle hold
    hold(True)  # hold is on
    hold(False) # hold is off


if not self._hold: self.clf()<EOL>im = FigureImage(self, cmap, norm, xo, yo, origin)<EOL>im.set_array(X)<EOL>im.set_alpha(alpha)<EOL>if norm is None:<EOL><INDENT>im.set_clim(vmin, vmax)<EOL><DEDENT>self.images.append(im)<EOL>return im<EOL>

call signatures::

  figimage(X, **kwargs)

adds a non-resampled array *X* to the figure.

::

  figimage(X, xo, yo)

with pixel offsets *xo*, *yo*,

*X* must be a float array:

* If *X* is MxN, assume luminance (grayscale)
* If *X* is MxNx3, assume RGB
* If *X* is MxNx4, assume RGBA

Optional keyword arguments:

  =========   ==========================================================
  Keyword     Description
  =========   ==========================================================
  xo or yo    An integer, the *x* and *y* image offset in pixels
  cmap        a :class:`matplotlib.cm.ColorMap` instance, eg cm.jet.
              If None, default to the rc ``image.cmap`` value
  norm        a :class:`matplotlib.colors.Normalize` instance. The
              default is normalization().  This scales luminance -> 0-1
  vmin|vmax   are used to scale a luminance image to 0-1.  If either is
              None, the min and max of the luminance values will be
              used.  Note if you pass a norm instance, the settings for
              *vmin* and *vmax* will be ignored.
  alpha       the alpha blending value, default is 1.0
  origin      [ 'upper' | 'lower' ] Indicates where the [0,0] index of
              the array is in the upper left or lower left corner of
              the axes. Defaults to the rc image.origin value
  =========   ==========================================================

figimage complements the axes image
(:meth:`~matplotlib.axes.Axes.imshow`) which will be resampled
to fit the current axes.  If you want a resampled image to
fill the entire figure, you can define an
:class:`~matplotlib.axes.Axes` with size [0,1,0,1].

An :class:`matplotlib.image.FigureImage` instance is returned.

.. plot:: mpl_examples/pylab_examples/figimage_demo.py


def set_size_inches(self, *args, **kwargs):

forward = kwargs.get('<STR_LIT>', False)<EOL>if len(args)==<NUM_LIT:1>:<EOL><INDENT>w,h = args[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>w,h = args<EOL><DEDENT>dpival = self.dpi<EOL>self.bbox_inches.p1 = w, h<EOL>if forward:<EOL><INDENT>dpival = self.dpi<EOL>canvasw = w*dpival<EOL>canvash = h*dpival<EOL>manager = getattr(self.canvas, '<STR_LIT>', None)<EOL>if manager is not None:<EOL><INDENT>manager.resize(int(canvasw), int(canvash))<EOL><DEDENT><DEDENT>

set_size_inches(w,h, forward=False)

Set the figure size in inches

Usage::

     fig.set_size_inches(w,h)  # OR
     fig.set_size_inches((w,h) )

optional kwarg *forward=True* will cause the canvas size to be
automatically updated; eg you can resize the figure window
from the shell

WARNING: forward=True is broken on all backends except GTK*
and WX*

ACCEPTS: a w,h tuple with w,h in inches


return self.patch.get_edgecolor()<EOL>

Get the edge color of the Figure rectangle


return self.patch.get_facecolor()<EOL>

Get the face color of the Figure rectangle


return self.bbox_inches.width<EOL>


return self.bbox_inches.height<EOL>


return self.dpi<EOL>


return self.frameon<EOL>


Set the edge color of the Figure rectangle

ACCEPTS: any matplotlib color - see help(colors)


Set the face color of the Figure rectangle

ACCEPTS: any matplotlib color - see help(colors)


self.dpi = val<EOL>

Set the dots-per-inch of the figure

ACCEPTS: float


self.bbox_inches.x1 = val<EOL>

Set the width of the figure in inches

ACCEPTS: float


self.bbox_inches.y1 = val<EOL>

Set the height of the figure in inches

ACCEPTS: float


self.frameon = b<EOL>

Set whether the figure frame (background) is displayed or invisible

ACCEPTS: boolean


self.axes.remove(a)<EOL>self._axstack.remove(a)<EOL>keys = []<EOL>for key, thisax in self._seen.items():<EOL><INDENT>if a==thisax: del self._seen[key]<EOL><DEDENT>for func in self._axobservers: func(self)<EOL>

remove a from the figure and update the current axes


def fixitems(items):<EOL><INDENT>ret = []<EOL>for k, v in items:<EOL><INDENT>if iterable(v): v = tuple(v)<EOL>ret.append((k,v))<EOL><DEDENT>return tuple(ret)<EOL><DEDENT>def fixlist(args):<EOL><INDENT>ret = []<EOL>for a in args:<EOL><INDENT>if iterable(a): a = tuple(a)<EOL>ret.append(a)<EOL><DEDENT>return tuple(ret)<EOL><DEDENT>key = fixlist(args), fixitems(kwargs.items())<EOL>return key<EOL>

make a hashable key out of args and kwargs


key = self._make_key(*args, **kwargs)<EOL>if key in self._seen:<EOL><INDENT>ax = self._seen[key]<EOL>self.sca(ax)<EOL>return ax<EOL><DEDENT>if not len(args): return<EOL>if isinstance(args[<NUM_LIT:0>], Axes):<EOL><INDENT>a = args[<NUM_LIT:0>]<EOL>assert(a.get_figure() is self)<EOL><DEDENT>else:<EOL><INDENT>rect = args[<NUM_LIT:0>]<EOL>ispolar = kwargs.pop('<STR_LIT>', False)<EOL>projection = kwargs.pop('<STR_LIT>', None)<EOL>if ispolar:<EOL><INDENT>if projection is not None and projection != '<STR_LIT>':<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" +<EOL>"<STR_LIT>" %<EOL>projection)<EOL><DEDENT>projection = '<STR_LIT>'<EOL><DEDENT>a = projection_factory(projection, self, rect, **kwargs)<EOL><DEDENT>self.axes.append(a)<EOL>self._axstack.push(a)<EOL>self.sca(a)<EOL>self._seen[key] = a<EOL>return a<EOL>

Add an a axes with axes rect [*left*, *bottom*, *width*,
*height*] where all quantities are in fractions of figure
width and height.  kwargs are legal
:class:`~matplotlib.axes.Axes` kwargs plus *projection* which
sets the projection type of the axes.  (For backward
compatibility, ``polar=True`` may also be provided, which is
equivalent to ``projection='polar'``).  Valid values for
*projection* are: %(list)s.  Some of these projections support
additional kwargs, which may be provided to :meth:`add_axes`::

    rect = l,b,w,h
    fig.add_axes(rect)
    fig.add_axes(rect, frameon=False, axisbg='g')
    fig.add_axes(rect, polar=True)
    fig.add_axes(rect, projection='polar')
    fig.add_axes(ax)   # add an Axes instance

If the figure already has an axes with the same parameters,
then it will simply make that axes current and return it.  If
you do not want this behavior, eg. you want to force the
creation of a new axes, you must use a unique set of args and
kwargs.  The axes :attr:`~matplotlib.axes.Axes.label`
attribute has been exposed for this purpose.  Eg., if you want
two axes that are otherwise identical to be added to the
figure, make sure you give them unique labels::

    fig.add_axes(rect, label='axes1')
    fig.add_axes(rect, label='axes2')

The :class:`~matplotlib.axes.Axes` instance will be returned.

The following kwargs are supported:

%(Axes)s


kwargs = kwargs.copy()<EOL>if not len(args): return<EOL>if isinstance(args[<NUM_LIT:0>], SubplotBase):<EOL><INDENT>a = args[<NUM_LIT:0>]<EOL>assert(a.get_figure() is self)<EOL><DEDENT>else:<EOL><INDENT>ispolar = kwargs.pop('<STR_LIT>', False)<EOL>projection = kwargs.pop('<STR_LIT>', None)<EOL>if ispolar:<EOL><INDENT>if projection is not None and projection != '<STR_LIT>':<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" +<EOL>"<STR_LIT>" %<EOL>projection)<EOL><DEDENT>projection = '<STR_LIT>'<EOL><DEDENT>projection_class = get_projection_class(projection)<EOL>key = self._make_key(*args, **kwargs)<EOL>if key in self._seen:<EOL><INDENT>ax = self._seen[key]<EOL>if isinstance(ax, projection_class):<EOL><INDENT>self.sca(ax)<EOL>return ax<EOL><DEDENT>else:<EOL><INDENT>self.axes.remove(ax)<EOL>self._axstack.remove(ax)<EOL><DEDENT><DEDENT>a = subplot_class_factory(projection_class)(self, *args, **kwargs)<EOL>self._seen[key] = a<EOL><DEDENT>self.axes.append(a)<EOL>self._axstack.push(a)<EOL>self.sca(a)<EOL>return a<EOL>

Add a subplot.  Examples:

    fig.add_subplot(111)
    fig.add_subplot(1,1,1)            # equivalent but more general
    fig.add_subplot(212, axisbg='r')  # add subplot with red background
    fig.add_subplot(111, polar=True)  # add a polar subplot
    fig.add_subplot(sub)              # add Subplot instance sub

*kwargs* are legal :class:`!matplotlib.axes.Axes` kwargs plus
*projection*, which chooses a projection type for the axes.
(For backward compatibility, *polar=True* may also be
provided, which is equivalent to *projection='polar'*). Valid
values for *projection* are: %(list)s.  Some of these projections
support additional *kwargs*, which may be provided to
:meth:`add_axes`.

The :class:`~matplotlib.axes.Axes` instance will be returned.

If the figure already has a subplot with key (*args*,
*kwargs*) then it will simply make that subplot current and
return it.

The following kwargs are supported:

%(Axes)s


self.suppressComposite = None<EOL>self.callbacks = cbook.CallbackRegistry(('<STR_LIT>', ))<EOL>for ax in tuple(self.axes):  <EOL><INDENT>ax.cla()<EOL>self.delaxes(ax)         <EOL><DEDENT>toolbar = getattr(self.canvas, '<STR_LIT>', None)<EOL>if toolbar is not None:<EOL><INDENT>toolbar.update()<EOL><DEDENT>self._axstack.clear()<EOL>self._seen = {}<EOL>self.artists = []<EOL>self.lines = []<EOL>self.patches = []<EOL>self.texts=[]<EOL>self.images = []<EOL>self.legends = []<EOL>self._axobservers = []<EOL>


self.clf()<EOL>


<EOL>if not self.get_visible(): return<EOL>renderer.open_group('<STR_LIT>')<EOL>if self.frameon: self.patch.draw(renderer)<EOL>for p in self.patches: p.draw(renderer)<EOL>for l in self.lines: l.draw(renderer)<EOL>for a in self.artists: a.draw(renderer)<EOL>composite = renderer.option_image_nocomposite()<EOL>if self.suppressComposite is not None:<EOL><INDENT>composite = self.suppressComposite<EOL><DEDENT>if len(self.images)<=<NUM_LIT:1> or composite or not allequal([im.origin for im in self.images]):<EOL><INDENT>for im in self.images:<EOL><INDENT>im.draw(renderer)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>mag = renderer.get_image_magnification()<EOL>ims = [(im.make_image(mag), im.ox, im.oy)<EOL>for im in self.images]<EOL>im = _image.from_images(self.bbox.height * mag,<EOL>self.bbox.width * mag,<EOL>ims)<EOL>im.is_grayscale = False<EOL>l, b, w, h = self.bbox.bounds<EOL>clippath, affine = self.get_transformed_clip_path_and_affine()<EOL>renderer.draw_image(l, b, im, self.bbox,<EOL>clippath, affine)<EOL><DEDENT>for a in self.axes: a.draw(renderer)<EOL>for t in self.texts: t.draw(renderer)<EOL>for legend in self.legends:<EOL><INDENT>legend.draw(renderer)<EOL><DEDENT>renderer.close_group('<STR_LIT>')<EOL>self._cachedRenderer = renderer<EOL>self.canvas.draw_event(renderer)<EOL>

Render the figure using :class:`matplotlib.backend_bases.RendererBase` instance renderer


assert self._cachedRenderer is not None<EOL>a.draw(self._cachedRenderer)<EOL>

draw :class:`matplotlib.artist.Artist` instance *a* only --
this is available only after the figure is drawn


def legend(self, handles, labels, *args, **kwargs):

handles = flatten(handles)<EOL>l = Legend(self, handles, labels, *args, **kwargs)<EOL>self.legends.append(l)<EOL>return l<EOL>

Place a legend in the figure.  Labels are a sequence of
strings, handles is a sequence of
:class:`~matplotlib.lines.Line2D` or
:class:`~matplotlib.patches.Patch` instances, and loc can be a
string or an integer specifying the legend location

USAGE::

  legend( (line1, line2, line3),
          ('label1', 'label2', 'label3'),
          'upper right')

The *loc* location codes are::

  'best' : 0,          (currently not supported for figure legends)
  'upper right'  : 1,
  'upper left'   : 2,
  'lower left'   : 3,
  'lower right'  : 4,
  'right'        : 5,
  'center left'  : 6,
  'center right' : 7,
  'lower center' : 8,
  'upper center' : 9,
  'center'       : 10,

*loc* can also be an (x,y) tuple in figure coords, which
specifies the lower left of the legend box.  figure coords are
(0,0) is the left, bottom of the figure and 1,1 is the right,
top.

The legend instance is returned.  The following kwargs are supported

*loc*
    the location of the legend
*numpoints*
    the number of points in the legend line
*prop*
    a :class:`matplotlib.font_manager.FontProperties` instance
*pad*
    the fractional whitespace inside the legend border
*markerscale*
    the relative size of legend markers vs. original
*shadow*
    if True, draw a shadow behind legend
*labelsep*
    the vertical space between the legend entries
*handlelen*
    the length of the legend lines
*handletextsep*
    the space between the legend line and legend text
*axespad*
    the border between the axes and legend edge

.. plot:: mpl_examples/pylab_examples/figlegend_demo.py


def text(self, x, y, s, *args, **kwargs):

override = _process_text_args({}, *args, **kwargs)<EOL>t = Text(<EOL>x=x, y=y, text=s,<EOL>)<EOL>t.update(override)<EOL>self._set_artist_props(t)<EOL>self.texts.append(t)<EOL>return t<EOL>

Call signature::

  figtext(x, y, s, fontdict=None, **kwargs)

Add text to figure at location *x*, *y* (relative 0-1
coords). See :func:`~matplotlib.pyplot.text` for the meaning
of the other arguments.

kwargs control the :class:`~matplotlib.text.Text` properties:

%(Text)s


ax = self._axstack()<EOL>if ax is not None:<EOL><INDENT>ispolar = kwargs.get('<STR_LIT>', False)<EOL>projection = kwargs.get('<STR_LIT>', None)<EOL>if ispolar:<EOL><INDENT>if projection is not None and projection != '<STR_LIT>':<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" +<EOL>"<STR_LIT>" %<EOL>projection)<EOL><DEDENT>projection = '<STR_LIT>'<EOL><DEDENT>projection_class = get_projection_class(projection)<EOL>if isinstance(ax, projection_class):<EOL><INDENT>return ax<EOL><DEDENT><DEDENT>return self.add_subplot(<NUM_LIT>, **kwargs)<EOL>

Return the current axes, creating one if necessary

The following kwargs are supported
%(Axes)s


self._axstack.bubble(a)<EOL>for func in self._axobservers: func(self)<EOL>return a<EOL>

Set the current axes to be a and return a


whenever the axes state change, func(self) will be called


for key in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>if key not in kwargs:<EOL><INDENT>kwargs[key] = rcParams['<STR_LIT>'%key]<EOL><DEDENT><DEDENT>transparent = kwargs.pop('<STR_LIT>', False)<EOL>if transparent:<EOL><INDENT>original_figure_alpha = self.patch.get_alpha()<EOL>self.patch.set_alpha(<NUM_LIT:0.0>)<EOL>original_axes_alpha = []<EOL>for ax in self.axes:<EOL><INDENT>patch = ax.patch<EOL>original_axes_alpha.append(patch.get_alpha())<EOL>patch.set_alpha(<NUM_LIT:0.0>)<EOL><DEDENT><DEDENT>self.canvas.print_figure(*args, **kwargs)<EOL>if transparent:<EOL><INDENT>self.patch.set_alpha(original_figure_alpha)<EOL>for ax, alpha in zip(self.axes, original_axes_alpha):<EOL><INDENT>ax.patch.set_alpha(alpha)<EOL><DEDENT><DEDENT>

call signature::

  savefig(fname, dpi=None, facecolor='w', edgecolor='w',
          orientation='portrait', papertype=None, format=None,
          transparent=False):

Save the current figure.

The output formats available depend on the backend being used.

Arguments:

  *fname*:
    A string containing a path to a filename, or a Python file-like object.

    If *format* is *None* and *fname* is a string, the output
    format is deduced from the extension of the filename.

Keyword arguments:

  *dpi*: [ None | scalar > 0 ]
    The resolution in dots per inch.  If *None* it will default to
    the value ``savefig.dpi`` in the matplotlibrc file.

  *facecolor*, *edgecolor*:
    the colors of the figure rectangle

  *orientation*: [ 'landscape' | 'portrait' ]
    not supported on all backends; currently only on postscript output

  *papertype*:
    One of 'letter', 'legal', 'executive', 'ledger', 'a0' through
    'a10', 'b0' through 'b10'. Only supported for postscript
    output.

  *format*:
    One of the file extensions supported by the active
    backend.  Most backends support png, pdf, ps, eps and svg.

  *transparent*:
    If *True*, the figure patch and axes patches will all be
    transparent.  This is useful, for example, for displaying
    a plot on top of a colored background on a web page.  The
    transparency of these patches will be restored to their
    original values upon exit of this function.


def subplots_adjust(self, *args, **kwargs):

self.subplotpars.update(*args, **kwargs)<EOL>import matplotlib.axes<EOL>for ax in self.axes:<EOL><INDENT>if not isinstance(ax, matplotlib.axes.SubplotBase):<EOL><INDENT>if ax._sharex is not None and isinstance(ax._sharex, matplotlib.axes.SubplotBase):<EOL><INDENT>ax._sharex.update_params()<EOL>ax.set_position(ax._sharex.figbox)<EOL><DEDENT>elif ax._sharey is not None and isinstance(ax._sharey, matplotlib.axes.SubplotBase):<EOL><INDENT>ax._sharey.update_params()<EOL>ax.set_position(ax._sharey.figbox)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>ax.update_params()<EOL>ax.set_position(ax.figbox)<EOL><DEDENT><DEDENT>

fig.subplots_adjust(left=None, bottom=None, right=None, wspace=None, hspace=None)

Update the :class:`SubplotParams` with *kwargs* (defaulting to rc where
None) and update the subplot locations


def ginput(self, n=<NUM_LIT:1>, timeout=<NUM_LIT:30>, show_clicks=True):

blocking_mouse_input = BlockingMouseInput(self)<EOL>return blocking_mouse_input(n=n, timeout=timeout,<EOL>show_clicks=show_clicks)<EOL>

call signature::

  ginput(self, n=1, timeout=30, show_clicks=True)

Blocking call to interact with the figure.

This will wait for *n* clicks from the user and return a list of the
coordinates of each click.

If *timeout* is zero or negative, does not timeout.

If *n* is zero or negative, accumulate clicks until a middle click
(or potentially both mouse buttons at once) terminates the input.

Right clicking cancels last input.

The keyboard can also be used to select points in case your mouse
does not have one or more of the buttons.  The delete and backspace
keys act like right clicking (i.e., remove last point), the enter key
terminates input and any other key (not already used by the window
manager) selects a point.


blocking_input = BlockingKeyMouseInput(self)<EOL>return blocking_input(timeout=timeout)<EOL>

call signature::

  waitforbuttonpress(self, timeout=-1)

Blocking call to interact with the figure.

This will return True is a key was pressed, False if a mouse
button was pressed and None if *timeout* was reached without
either being pressed.

If *timeout* is negative, does not timeout.


currpos = <NUM_LIT:0><EOL>lasti = <NUM_LIT:0><EOL>result = []<EOL>for i, s in enumerate(strings):<EOL><INDENT>length = len(s)<EOL>if currpos + length < linelen:<EOL><INDENT>currpos += length + <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>result.append('<STR_LIT:U+0020>'.join(strings[lasti:i]))<EOL>lasti = i<EOL>currpos = length<EOL><DEDENT><DEDENT>result.append('<STR_LIT:U+0020>'.join(strings[lasti:]))<EOL>return '<STR_LIT:\n>'.join(result)<EOL>

Make one string from sequence of strings, with whitespace
    in between. The whitespace is chosen to form lines of at most
    linelen characters, if possible.


<EOL>if hasattr(obj, '<STR_LIT>'):<EOL><INDENT>return obj.pdfRepr()<EOL><DEDENT>elif isinstance(obj, float):<EOL><INDENT>if not npy.isfinite(obj):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>r = "<STR_LIT>" % obj<EOL>return r.rstrip('<STR_LIT:0>').rstrip('<STR_LIT:.>')<EOL><DEDENT>elif isinstance(obj, int):<EOL><INDENT>return "<STR_LIT>" % obj<EOL><DEDENT>elif is_string_like(obj):<EOL><INDENT>return '<STR_LIT:(>' + _string_escape_regex.sub(r'<STR_LIT>', obj) + '<STR_LIT:)>'<EOL><DEDENT>elif isinstance(obj, dict):<EOL><INDENT>r = ["<STR_LIT>"]<EOL>r.extend(["<STR_LIT>" % (Name(key).pdfRepr(), pdfRepr(val))<EOL>for key, val in list(obj.items())])<EOL>r.append("<STR_LIT>")<EOL>return fill(r)<EOL><DEDENT>elif isinstance(obj, (list, tuple)):<EOL><INDENT>r = ["<STR_LIT:[>"]<EOL>r.extend([pdfRepr(val) for val in obj])<EOL>r.append("<STR_LIT:]>")<EOL>return fill(r)<EOL><DEDENT>elif isinstance(obj, bool):<EOL><INDENT>return ['<STR_LIT:false>', '<STR_LIT:true>'][obj]<EOL><DEDENT>elif obj is None:<EOL><INDENT>return '<STR_LIT:null>'<EOL><DEDENT>elif isinstance(obj, datetime):<EOL><INDENT>r = obj.strftime('<STR_LIT>')<EOL>if time.daylight: z = time.altzone<EOL>else: z = time.timezone<EOL>if z == <NUM_LIT:0>: r += '<STR_LIT>'<EOL>elif z < <NUM_LIT:0>: r += "<STR_LIT>" % ((-z)//<NUM_LIT>, (-z)%<NUM_LIT>)<EOL>else: r += "<STR_LIT>" % (z//<NUM_LIT>, z%<NUM_LIT>)<EOL>return pdfRepr(r)<EOL><DEDENT>elif isinstance(obj, BboxBase):<EOL><INDENT>return fill([pdfRepr(val) for val in obj.bounds])<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>"% type(obj))<EOL><DEDENT>


def new_figure_manager(num, *args, **kwargs):

<EOL>FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>thisFig = FigureClass(*args, **kwargs)<EOL>canvas = FigureCanvasPdf(thisFig)<EOL>manager = FigureManagerPdf(canvas, num)<EOL>return manager<EOL>


def __init__(self, id, len, file, extra=None):

self.id = id            <EOL>self.len = len          <EOL>self.pdfFile = file<EOL>self.file = file.fh     <EOL>self.compressobj = None <EOL>if extra is None: self.extra = dict()<EOL>else: self.extra = extra<EOL>self.pdfFile.recordXref(self.id)<EOL>if rcParams['<STR_LIT>']:<EOL><INDENT>self.compressobj = zlib.compressobj(rcParams['<STR_LIT>'])<EOL><DEDENT>if self.len is None:<EOL><INDENT>self.file = StringIO()<EOL><DEDENT>else:<EOL><INDENT>self._writeHeader()<EOL>self.pos = self.file.tell()<EOL><DEDENT>

id: object id of stream; len: an unused Reference object for the
        length of the stream, or None (to use a memory buffer); file:
        a PdfFile; extra: a dictionary of extra key-value pairs to
        include in the stream header


self._flush()<EOL>if self.len is None:<EOL><INDENT>contents = self.file.getvalue()<EOL>self.len = len(contents)<EOL>self.file = self.pdfFile.fh<EOL>self._writeHeader()<EOL>self.file.write(contents)<EOL>self.file.write("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>length = self.file.tell() - self.pos<EOL>self.file.write("<STR_LIT>")<EOL>self.pdfFile.writeObject(self.len, length)<EOL><DEDENT>


if self.compressobj is None:<EOL><INDENT>self.file.write(data)<EOL><DEDENT>else:<EOL><INDENT>compressed = self.compressobj.compress(data)<EOL>self.file.write(compressed)<EOL><DEDENT>


if self.compressobj is not None:<EOL><INDENT>compressed = self.compressobj.flush()<EOL>self.file.write(compressed)<EOL>self.compressobj = None<EOL><DEDENT>


if is_string_like(fontprop):<EOL><INDENT>filename = fontprop<EOL><DEDENT>elif rcParams['<STR_LIT>']:<EOL><INDENT>filename = findfont(fontprop, fontext='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>filename = findfont(fontprop)<EOL><DEDENT>Fx = self.fontNames.get(filename)<EOL>if Fx is None:<EOL><INDENT>Fx = Name('<STR_LIT>' % self.nextFont)<EOL>self.fontNames[filename] = Fx<EOL>self.nextFont += <NUM_LIT:1><EOL><DEDENT>return Fx<EOL>

Select a font based on fontprop and return a name suitable for
Op.selectfont. If fontprop is a string, it will be interpreted
as the filename of the font.


def embedTTF(self, filename, characters):

font = FT2Font(str(filename))<EOL>fonttype = rcParams['<STR_LIT>']<EOL>def cvt(length, upe=font.units_per_EM, nearest=True):<EOL><INDENT>"<STR_LIT>"<EOL>value = length / upe * <NUM_LIT:1000><EOL>if nearest: return round(value)<EOL>if value < <NUM_LIT:0>: return floor(value)<EOL>else: return ceil(value)<EOL><DEDENT>def embedTTFType3(font, characters, descriptor):<EOL><INDENT>"""<STR_LIT>"""<EOL>widthsObject = self.reserveObject('<STR_LIT>')<EOL>fontdescObject = self.reserveObject('<STR_LIT>')<EOL>fontdictObject = self.reserveObject('<STR_LIT>')<EOL>charprocsObject = self.reserveObject('<STR_LIT>')<EOL>differencesArray = []<EOL>firstchar, lastchar = <NUM_LIT:0>, <NUM_LIT:255><EOL>bbox = [cvt(x, nearest=False) for x in font.bbox]<EOL>fontdict = {<EOL>'<STR_LIT>'            : Name('<STR_LIT>'),<EOL>'<STR_LIT>'        : ps_name,<EOL>'<STR_LIT>'       : firstchar,<EOL>'<STR_LIT>'        : lastchar,<EOL>'<STR_LIT>'  : fontdescObject,<EOL>'<STR_LIT>'         : Name('<STR_LIT>'),<EOL>'<STR_LIT:Name>'            : descriptor['<STR_LIT>'],<EOL>'<STR_LIT>'        : bbox,<EOL>'<STR_LIT>'      : [ <NUM_LIT>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT>, <NUM_LIT:0>, <NUM_LIT:0> ],<EOL>'<STR_LIT>'       : charprocsObject,<EOL>'<STR_LIT>'        : {<EOL>'<STR_LIT>'        : Name('<STR_LIT>'),<EOL>'<STR_LIT>' : differencesArray},<EOL>'<STR_LIT>'          : widthsObject<EOL>}<EOL>from encodings import cp1252<EOL>if hasattr(cp1252, '<STR_LIT>'):<EOL><INDENT>def decode_char(charcode):<EOL><INDENT>return cp1252.decoding_map[charcode] or <NUM_LIT:0><EOL><DEDENT><DEDENT>else:<EOL><INDENT>def decode_char(charcode):<EOL><INDENT>return ord(cp1252.decoding_table[charcode])<EOL><DEDENT><DEDENT>def get_char_width(charcode):<EOL><INDENT>str = decode_char(charcode)<EOL>width = font.load_char(str, flags=LOAD_NO_SCALE|LOAD_NO_HINTING).horiAdvance<EOL>return cvt(width)<EOL><DEDENT>widths = [ get_char_width(charcode) for charcode in range(firstchar, lastchar+<NUM_LIT:1>) ]<EOL>descriptor['<STR_LIT>'] = max(widths)<EOL>cmap = font.get_charmap()<EOL>glyph_ids = []<EOL>differences = []<EOL>multi_byte_chars = set()<EOL>for c in characters:<EOL><INDENT>ccode = c<EOL>gind = cmap.get(ccode) or <NUM_LIT:0><EOL>glyph_ids.append(gind)<EOL>glyph_name = font.get_glyph_name(gind)<EOL>if ccode <= <NUM_LIT:255>:<EOL><INDENT>differences.append((ccode, glyph_name))<EOL><DEDENT>else:<EOL><INDENT>multi_byte_chars.add(glyph_name)<EOL><DEDENT><DEDENT>differences.sort()<EOL>last_c = -<NUM_LIT:2><EOL>for c, name in differences:<EOL><INDENT>if c != last_c + <NUM_LIT:1>:<EOL><INDENT>differencesArray.append(c)<EOL><DEDENT>differencesArray.append(Name(name))<EOL>last_c = c<EOL><DEDENT>rawcharprocs = ttconv.get_pdf_charprocs(filename, glyph_ids)<EOL>charprocs = {}<EOL>charprocsRef = {}<EOL>for charname, stream in list(rawcharprocs.items()):<EOL><INDENT>charprocDict = { '<STR_LIT>': len(stream) }<EOL>if charname in multi_byte_chars:<EOL><INDENT>charprocDict['<STR_LIT>'] = Name('<STR_LIT>')<EOL>charprocDict['<STR_LIT>'] = Name('<STR_LIT>')<EOL>charprocDict['<STR_LIT>'] = bbox<EOL>stream = stream[stream.find("<STR_LIT>") + <NUM_LIT:2>:]<EOL><DEDENT>charprocObject = self.reserveObject('<STR_LIT>')<EOL>self.beginStream(charprocObject.id, None, charprocDict)<EOL>self.currentstream.write(stream)<EOL>self.endStream()<EOL>if charname in multi_byte_chars:<EOL><INDENT>name = self._get_xobject_symbol_name(filename, charname)<EOL>self.multi_byte_charprocs[name] = charprocObject<EOL><DEDENT>else:<EOL><INDENT>charprocs[charname] = charprocObject<EOL><DEDENT><DEDENT>self.writeObject(fontdictObject, fontdict)<EOL>self.writeObject(fontdescObject, descriptor)<EOL>self.writeObject(widthsObject, widths)<EOL>self.writeObject(charprocsObject, charprocs)<EOL>return fontdictObject<EOL><DEDENT>def embedTTFType42(font, characters, descriptor):<EOL><INDENT>"""<STR_LIT>"""<EOL>fontdescObject = self.reserveObject('<STR_LIT>')<EOL>cidFontDictObject = self.reserveObject('<STR_LIT>')<EOL>type0FontDictObject = self.reserveObject('<STR_LIT>')<EOL>cidToGidMapObject = self.reserveObject('<STR_LIT>')<EOL>fontfileObject = self.reserveObject('<STR_LIT>')<EOL>wObject = self.reserveObject('<STR_LIT>')<EOL>toUnicodeMapObject = self.reserveObject('<STR_LIT>')<EOL>cidFontDict = {<EOL>'<STR_LIT>'           : Name('<STR_LIT>'),<EOL>'<STR_LIT>'        : Name('<STR_LIT>'),<EOL>'<STR_LIT>'       : ps_name,<EOL>'<STR_LIT>'  : {<EOL>'<STR_LIT>'   : '<STR_LIT>',<EOL>'<STR_LIT>'   : '<STR_LIT>',<EOL>'<STR_LIT>' : <NUM_LIT:0> },<EOL>'<STR_LIT>' : fontdescObject,<EOL>'<STR_LIT>'              : wObject,<EOL>'<STR_LIT>'    : cidToGidMapObject<EOL>}<EOL>type0FontDict = {<EOL>'<STR_LIT>'            : Name('<STR_LIT>'),<EOL>'<STR_LIT>'         : Name('<STR_LIT>'),<EOL>'<STR_LIT>'        : ps_name,<EOL>'<STR_LIT>'        : Name('<STR_LIT>'),<EOL>'<STR_LIT>' : [cidFontDictObject],<EOL>'<STR_LIT>'       : toUnicodeMapObject<EOL>}<EOL>descriptor['<STR_LIT>'] = fontfileObject<EOL>length1Object = self.reserveObject('<STR_LIT>')<EOL>self.beginStream(<EOL>fontfileObject.id,<EOL>self.reserveObject('<STR_LIT>'),<EOL>{'<STR_LIT>': length1Object})<EOL>fontfile = open(filename, '<STR_LIT:rb>')<EOL>length1 = <NUM_LIT:0><EOL>while True:<EOL><INDENT>data = fontfile.read(<NUM_LIT>)<EOL>if not data: break<EOL>length1 += len(data)<EOL>self.currentstream.write(data)<EOL><DEDENT>fontfile.close()<EOL>self.endStream()<EOL>self.writeObject(length1Object, length1)<EOL>cid_to_gid_map = ['<STR_LIT>'] * <NUM_LIT><EOL>cmap = font.get_charmap()<EOL>unicode_mapping = []<EOL>widths = []<EOL>max_ccode = <NUM_LIT:0><EOL>for c in characters:<EOL><INDENT>ccode = c<EOL>gind = cmap.get(ccode) or <NUM_LIT:0><EOL>glyph = font.load_char(ccode, flags=LOAD_NO_HINTING)<EOL>widths.append((ccode, glyph.horiAdvance / <NUM_LIT:6>))<EOL>if ccode < <NUM_LIT>:<EOL><INDENT>cid_to_gid_map[ccode] = chr(gind)<EOL><DEDENT>max_ccode = max(ccode, max_ccode)<EOL><DEDENT>widths.sort()<EOL>cid_to_gid_map = cid_to_gid_map[:max_ccode + <NUM_LIT:1>]<EOL>last_ccode = -<NUM_LIT:2><EOL>w = []<EOL>max_width = <NUM_LIT:0><EOL>unicode_groups = []<EOL>for ccode, width in widths:<EOL><INDENT>if ccode != last_ccode + <NUM_LIT:1>:<EOL><INDENT>w.append(ccode)<EOL>w.append([width])<EOL>unicode_groups.append([ccode, ccode])<EOL><DEDENT>else:<EOL><INDENT>w[-<NUM_LIT:1>].append(width)<EOL>unicode_groups[-<NUM_LIT:1>][<NUM_LIT:1>] = ccode<EOL><DEDENT>max_width = max(max_width, width)<EOL>last_ccode = ccode<EOL><DEDENT>unicode_bfrange = []<EOL>for start, end in unicode_groups:<EOL><INDENT>unicode_bfrange.append(<EOL>"<STR_LIT>" %<EOL>(start, end,<EOL>"<STR_LIT:U+0020>".join(["<STR_LIT>" % x for x in range(start, end+<NUM_LIT:1>)])))<EOL><DEDENT>unicode_cmap = (self._identityToUnicodeCMap %<EOL>(len(unicode_groups),<EOL>"<STR_LIT:\n>".join(unicode_bfrange)))<EOL>cid_to_gid_map = "<STR_LIT>".join(cid_to_gid_map).encode("<STR_LIT>")<EOL>self.beginStream(cidToGidMapObject.id,<EOL>None,<EOL>{'<STR_LIT>':  len(cid_to_gid_map)})<EOL>self.currentstream.write(cid_to_gid_map)<EOL>self.endStream()<EOL>self.beginStream(toUnicodeMapObject.id,<EOL>None,<EOL>{'<STR_LIT>': unicode_cmap})<EOL>self.currentstream.write(unicode_cmap)<EOL>self.endStream()<EOL>descriptor['<STR_LIT>'] = max_width<EOL>self.writeObject(cidFontDictObject, cidFontDict)<EOL>self.writeObject(type0FontDictObject, type0FontDict)<EOL>self.writeObject(fontdescObject, descriptor)<EOL>self.writeObject(wObject, w)<EOL>return type0FontDictObject<EOL><DEDENT>ps_name = Name(font.get_sfnt()[(<NUM_LIT:1>,<NUM_LIT:0>,<NUM_LIT:0>,<NUM_LIT:6>)])<EOL>pclt = font.get_sfnt_table('<STR_LIT>')or { '<STR_LIT>': <NUM_LIT:0>, '<STR_LIT>': <NUM_LIT:0> }<EOL>post = font.get_sfnt_table('<STR_LIT>')or { '<STR_LIT>': (<NUM_LIT:0>,<NUM_LIT:0>) }<EOL>ff = font.face_flags<EOL>sf = font.style_flags<EOL>flags = <NUM_LIT:0><EOL>symbolic = False <EOL>if ff & FIXED_WIDTH: flags |= <NUM_LIT:1> << <NUM_LIT:0><EOL>if <NUM_LIT:0>: flags |= <NUM_LIT:1> << <NUM_LIT:1> <EOL>if symbolic: flags |= <NUM_LIT:1> << <NUM_LIT:2><EOL>else: flags |= <NUM_LIT:1> << <NUM_LIT:5><EOL>if sf & ITALIC: flags |= <NUM_LIT:1> << <NUM_LIT:6><EOL>if <NUM_LIT:0>: flags |= <NUM_LIT:1> << <NUM_LIT:16> <EOL>if <NUM_LIT:0>: flags |= <NUM_LIT:1> << <NUM_LIT> <EOL>if <NUM_LIT:0>: flags |= <NUM_LIT:1> << <NUM_LIT> <EOL>descriptor = {<EOL>'<STR_LIT>'        : Name('<STR_LIT>'),<EOL>'<STR_LIT>'    : ps_name,<EOL>'<STR_LIT>'       : flags,<EOL>'<STR_LIT>'    : [ cvt(x, nearest=False) for x in font.bbox ],<EOL>'<STR_LIT>'      : cvt(font.ascender, nearest=False),<EOL>'<STR_LIT>'     : cvt(font.descender, nearest=False),<EOL>'<STR_LIT>'   : cvt(pclt['<STR_LIT>'], nearest=False),<EOL>'<STR_LIT>'     : cvt(pclt['<STR_LIT>']),<EOL>'<STR_LIT>' : post['<STR_LIT>'][<NUM_LIT:1>], <EOL>'<STR_LIT>'       : <NUM_LIT:0> <EOL>}<EOL>if is_opentype_cff_font(filename):<EOL><INDENT>fonttype = <NUM_LIT><EOL>warnings.warn(("<STR_LIT>" +<EOL>"<STR_LIT>") %<EOL>os.path.basename(filename))<EOL><DEDENT>if fonttype == <NUM_LIT:3>:<EOL><INDENT>return embedTTFType3(font, characters, descriptor)<EOL><DEDENT>elif fonttype == <NUM_LIT>:<EOL><INDENT>return embedTTFType42(font, characters, descriptor)<EOL><DEDENT>

Embed the TTF font from the named file into the document.


state = self.alphaStates.get(alpha, None)<EOL>if state is not None:<EOL><INDENT>return state[<NUM_LIT:0>]<EOL><DEDENT>name = Name('<STR_LIT>' % self.nextAlphaState)<EOL>self.nextAlphaState += <NUM_LIT:1><EOL>self.alphaStates[alpha] =(name, { '<STR_LIT>': Name('<STR_LIT>'),<EOL>'<STR_LIT>': alpha, '<STR_LIT>': alpha })<EOL>return name<EOL>

Return name of an ExtGState that sets alpha to the given value


pair = self.images.get(image, None)<EOL>if pair is not None:<EOL><INDENT>return pair[<NUM_LIT:0>]<EOL><DEDENT>name = Name('<STR_LIT>' % self.nextImage)<EOL>ob = self.reserveObject('<STR_LIT>' % self.nextImage)<EOL>self.nextImage += <NUM_LIT:1><EOL>self.images[image] = (name, ob)<EOL>return name<EOL>

Return name of an image XObject representing the given image.


def markerObject(self, path, trans, fillp, lw):

key = (path, trans, fillp is not None, lw)<EOL>result = self.markers.get(key)<EOL>if result is None:<EOL><INDENT>name = Name('<STR_LIT>' % len(self.markers))<EOL>ob = self.reserveObject('<STR_LIT>' % len(self.markers))<EOL>self.markers[key] = (name, ob, path, trans, fillp, lw)<EOL><DEDENT>else:<EOL><INDENT>name = result[<NUM_LIT:0>]<EOL><DEDENT>return name<EOL>

Return name of a marker XObject representing the given path.


id = self.nextObject<EOL>self.nextObject += <NUM_LIT:1><EOL>self.xrefTable.append([None, <NUM_LIT:0>, name])<EOL>return Reference(id)<EOL>

Reserve an ID for an indirect object.
        The name is used for debugging in case we forget to print out
        the object with writeObject.


self.startxref = self.fh.tell()<EOL>self.write("<STR_LIT>" % self.nextObject)<EOL>i = <NUM_LIT:0><EOL>borken = False<EOL>for offset, generation, name in self.xrefTable:<EOL><INDENT>if offset is None:<EOL><INDENT>print('<STR_LIT>' % (i, name), file=sys.stderr)<EOL>borken = True<EOL><DEDENT>else:<EOL><INDENT>self.write("<STR_LIT>" % (offset, generation))<EOL><DEDENT>i += <NUM_LIT:1><EOL><DEDENT>if borken:<EOL><INDENT>raise AssertionError('<STR_LIT>')<EOL><DEDENT>


self.write("<STR_LIT>")<EOL>self.write(pdfRepr(<EOL>{'<STR_LIT>': self.nextObject,<EOL>'<STR_LIT>': self.rootObject,<EOL>'<STR_LIT>': self.infoObject }))<EOL>self.write("<STR_LIT>" % self.startxref)<EOL>


if isinstance(font, str):<EOL><INDENT>fname = font<EOL><DEDENT>else:<EOL><INDENT>fname = font.fname<EOL><DEDENT>realpath, stat_key = get_realpath_and_stat(fname)<EOL>used_characters = self.used_characters.setdefault(<EOL>stat_key, (realpath, set()))<EOL>used_characters[<NUM_LIT:1>].update([ord(x) for x in s])<EOL>

Keeps track of which characters are required from
        each font.


cmds = []<EOL>while (self._cliprect, self._clippath) != (cliprect, clippath)and self.parent is not None:<EOL><INDENT>cmds.extend(self.pop())<EOL><DEDENT>if (self._cliprect, self._clippath) != (cliprect, clippath):<EOL><INDENT>cmds.extend(self.push())<EOL>if self._cliprect != cliprect:<EOL><INDENT>cmds.extend([cliprect, Op.rectangle, Op.clip, Op.endpath])<EOL><DEDENT>if self._clippath != clippath:<EOL><INDENT>cmds.extend(<EOL>PdfFile.pathOperations(<EOL>*clippath.get_transformed_path_and_affine()) +<EOL>[Op.clip, Op.endpath])<EOL><DEDENT><DEDENT>return cmds<EOL>

Set clip rectangle. Calls self.pop() and self.push().


cmds = []<EOL>for params, cmd in self.commands:<EOL><INDENT>different = False<EOL>for p in params:<EOL><INDENT>ours = getattr(self, p)<EOL>theirs = getattr(other, p)<EOL>try:<EOL><INDENT>different = bool(ours != theirs)<EOL><DEDENT>except ValueError:<EOL><INDENT>ours = npy.asarray(ours)<EOL>theirs = npy.asarray(theirs)<EOL>different = ours.shape != theirs.shape or npy.any(ours != theirs)<EOL><DEDENT>if different:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if different:<EOL><INDENT>theirs = [getattr(other, p) for p in params]<EOL>cmds.extend(cmd(self, *theirs))<EOL>for p in params:<EOL><INDENT>setattr(self, p, getattr(other, p))<EOL><DEDENT><DEDENT><DEDENT>return cmds<EOL>

Copy properties of other into self and return PDF commands
needed to transform self into other.


GraphicsContextBase.copy_properties(self, other)<EOL>self._fillcolor = other._fillcolor<EOL>


cmds = []<EOL>while self.parent is not None:<EOL><INDENT>cmds.extend(self.pop())<EOL><DEDENT>return cmds<EOL>

Make sure every pushed graphics state is popped.


if matplotlib.is_interactive():<EOL><INDENT>figManager =  Gcf.get_active()<EOL>if figManager is not None:<EOL><INDENT>figManager.canvas.draw()<EOL><DEDENT><DEDENT>

Is called after every pylab drawing command


for manager in Gcf.get_all_fig_managers():<EOL><INDENT>manager.window.show()<EOL><DEDENT>if mainloop and gtk.main_level() == <NUM_LIT:0> andlen(Gcf.get_all_fig_managers())><NUM_LIT:0>:<EOL><INDENT>gtk.main()<EOL><DEDENT>

Show all the figures and enter the gtk main loop
This should be the last line of your script


FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>thisFig = FigureClass(*args, **kwargs)<EOL>canvas = FigureCanvasGTK(thisFig)<EOL>manager = FigureManagerGTK(canvas, num)<EOL>return manager<EOL>


self._renderer = RendererGDK (self, self.figure.dpi)<EOL>

Override by GTK backends to select a different renderer
        Renderer should provide the methods:
            set_pixmap ()
            set_width_height ()
        that are used by
            _render_figure() / _pixmap_prepare()


def _pixmap_prepare(self, width, height):

if _debug: print('<STR_LIT>' % fn_name())<EOL>create_pixmap = False<EOL>if width > self._pixmap_width:<EOL><INDENT>self._pixmap_width  = max (int (self._pixmap_width  * <NUM_LIT>),<EOL>width)<EOL>create_pixmap = True<EOL><DEDENT>if height > self._pixmap_height:<EOL><INDENT>self._pixmap_height = max (int (self._pixmap_height * <NUM_LIT>),<EOL>height)<EOL>create_pixmap = True<EOL><DEDENT>if create_pixmap:<EOL><INDENT>self._pixmap = gdk.Pixmap (self.window, self._pixmap_width,<EOL>self._pixmap_height)<EOL>self._renderer.set_pixmap (self._pixmap)<EOL><DEDENT>

Make sure _._pixmap is at least width, height,
create new pixmap if necessary


def _render_figure(self, pixmap, width, height):

self._renderer.set_width_height (width, height)<EOL>self.figure.draw (self._renderer)<EOL>

used by GTK and GTKcairo. GTKAgg overrides


if _debug: print('<STR_LIT>' % fn_name())<EOL>if GTK_WIDGET_DRAWABLE(self):<EOL><INDENT>if self._need_redraw:<EOL><INDENT>x, y, w, h = self.allocation<EOL>self._pixmap_prepare (w, h)<EOL>self._render_figure(self._pixmap, w, h)<EOL>self._need_redraw = False<EOL><DEDENT>x, y, w, h = event.area<EOL>self.window.draw_drawable (self.style.fg_gc[self.state],<EOL>self._pixmap, x, y, x, y, w, h)<EOL><DEDENT>return False<EOL>

Expose_event for all GTK backends. Should not be overridden.


<EOL>self.window.resize(width, height)<EOL>


def draw_rubberband(self, event, x0, y0, x1, y1):

drawable = self.canvas.window<EOL>if drawable is None:<EOL><INDENT>return<EOL><DEDENT>gc = drawable.new_gc()<EOL>height = self.canvas.figure.bbox.height<EOL>y1 = height - y1<EOL>y0 = height - y0<EOL>w = abs(x1 - x0)<EOL>h = abs(y1 - y0)<EOL>rect = [int(val)for val in (min(x0,x1), min(y0, y1), w, h)]<EOL>try: lastrect, imageBack = self._imageBack<EOL>except AttributeError:<EOL><INDENT>if event.inaxes is None:<EOL><INDENT>return<EOL><DEDENT>ax = event.inaxes<EOL>l,b,w,h = [int(val) for val in ax.bbox.bounds]<EOL>b = int(height)-(b+h)<EOL>axrect = l,b,w,h<EOL>self._imageBack = axrect, drawable.get_image(*axrect)<EOL>drawable.draw_rectangle(gc, False, *rect)<EOL>self._idle_draw_id = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>def idle_draw(*args):<EOL><INDENT>drawable.draw_image(gc, imageBack, <NUM_LIT:0>, <NUM_LIT:0>, *lastrect)<EOL>drawable.draw_rectangle(gc, False, *rect)<EOL>self._idle_draw_id = <NUM_LIT:0><EOL>return False<EOL><DEDENT>if self._idle_draw_id == <NUM_LIT:0>:<EOL><INDENT>self._idle_draw_id = gobject.idle_add(idle_draw)<EOL><DEDENT><DEDENT>


gtk.Toolbar.__init__(self)<EOL>self.canvas = canvas<EOL>self.win    = window<EOL>self.set_style(gtk.TOOLBAR_ICONS)<EOL>if gtk.pygtk_version >= (<NUM_LIT:2>,<NUM_LIT:4>,<NUM_LIT:0>):<EOL><INDENT>self._create_toolitems_2_4()<EOL>self.update = self._update_2_4<EOL>self.fileselect = FileChooserDialog(<EOL>title='<STR_LIT>',<EOL>parent=self.win,<EOL>filetypes=self.canvas.get_supported_filetypes(),<EOL>default_filetype=self.canvas.get_default_filetype())<EOL><DEDENT>else:<EOL><INDENT>self._create_toolitems_2_2()<EOL>self.update = self._update_2_2<EOL>self.fileselect = FileSelection(title='<STR_LIT>',<EOL>parent=self.win)<EOL><DEDENT>self.show_all()<EOL>self.update()<EOL>

figManager is the FigureManagerGTK instance that contains the
toolbar, with attributes figure, window and drawingArea


for a in self._active:<EOL><INDENT>a.xaxis.pan(direction)<EOL><DEDENT>self.canvas.draw()<EOL>return True<EOL>


for a in self._active:<EOL><INDENT>a.yaxis.pan(direction)<EOL><DEDENT>self.canvas.draw()<EOL>return True<EOL>


for a in self._active:<EOL><INDENT>a.xaxis.zoom(direction)<EOL><DEDENT>self.canvas.draw()<EOL>return True<EOL>


for a in self._active:<EOL><INDENT>a.yaxis.zoom(direction)<EOL><DEDENT>self.canvas.draw()<EOL>return True<EOL>


self._updateson = False<EOL>cbox = self.cbox_lineprops<EOL>for i in range(self._lastcnt-<NUM_LIT:1>,-<NUM_LIT:1>,-<NUM_LIT:1>):<EOL><INDENT>cbox.remove_text(i)<EOL><DEDENT>for line in self.lines:<EOL><INDENT>cbox.append_text(line.get_label())<EOL><DEDENT>cbox.set_active(<NUM_LIT:0>)<EOL>self._updateson = True<EOL>self._lastcnt = len(self.lines)<EOL>self.dlg.show()<EOL>


ind = self.cbox_lineprops.get_active()<EOL>line = self.lines[ind]<EOL>return line<EOL>


ind = self.cbox_linestyles.get_active()<EOL>ls = self.linestyles[ind]<EOL>return ls<EOL>


ind = self.cbox_markers.get_active()<EOL>m = self.markers[ind]<EOL>return m<EOL>


if not self._inited or not self._updateson: return<EOL>line = self.get_active_line()<EOL>ls = self.get_active_linestyle()<EOL>marker = self.get_active_marker()<EOL>line.set_linestyle(ls)<EOL>line.set_marker(marker)<EOL>button = self.wtree.get_widget('<STR_LIT>')<EOL>color = button.get_color()<EOL>r, g, b = [val/<NUM_LIT> for val in (color.red, color.green, color.blue)]<EOL>line.set_color((r,g,b))<EOL>button = self.wtree.get_widget('<STR_LIT>')<EOL>color = button.get_color()<EOL>r, g, b = [val/<NUM_LIT> for val in (color.red, color.green, color.blue)]<EOL>line.set_markerfacecolor((r,g,b))<EOL>line.figure.canvas.draw()<EOL>

update the active line props from the widgets


if not self._inited: return<EOL>self._updateson = False<EOL>line = self.get_active_line()<EOL>ls = line.get_linestyle()<EOL>if ls is None: ls = '<STR_LIT:None>'<EOL>self.cbox_linestyles.set_active(self.linestyled[ls])<EOL>marker = line.get_marker()<EOL>if marker is None: marker = '<STR_LIT:None>'<EOL>self.cbox_markers.set_active(self.markerd[marker])<EOL>r,g,b = colorConverter.to_rgb(line.get_color())<EOL>color = gtk.gdk.Color(*[int(val*<NUM_LIT>) for val in (r,g,b)])<EOL>button = self.wtree.get_widget('<STR_LIT>')<EOL>button.set_color(color)<EOL>r,g,b = colorConverter.to_rgb(line.get_markerfacecolor())<EOL>color = gtk.gdk.Color(*[int(val*<NUM_LIT>) for val in (r,g,b)])<EOL>button = self.wtree.get_widget('<STR_LIT>')<EOL>button.set_color(color)<EOL>self._updateson = True<EOL>


def new_figure_manager( num, *args, **kwargs ):

if DEBUG: print('<STR_LIT>')<EOL>FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>thisFig = FigureClass( *args, **kwargs )<EOL>canvas = FigureCanvasQTAgg( thisFig )<EOL>return FigureManagerQT( canvas, num )<EOL>


<EOL>if DEBUG: print('<STR_LIT>', self,self.get_width_height())<EOL>if type(self.replot) is bool: <EOL><INDENT>if self.replot:<EOL><INDENT>FigureCanvasAgg.draw(self)<EOL><DEDENT>if QtCore.QSysInfo.ByteOrder == QtCore.QSysInfo.LittleEndian:<EOL><INDENT>stringBuffer = self.renderer._renderer.tostring_bgra()<EOL><DEDENT>else:<EOL><INDENT>stringBuffer = self.renderer._renderer.tostring_argb()<EOL><DEDENT>qImage = QtGui.QImage(stringBuffer, self.renderer.width,<EOL>self.renderer.height,<EOL>QtGui.QImage.Format_ARGB32)<EOL>p = QtGui.QPainter(self)<EOL>p.drawPixmap(QtCore.QPoint(<NUM_LIT:0>, <NUM_LIT:0>), QtGui.QPixmap.fromImage(qImage))<EOL>if self.drawRect:<EOL><INDENT>p.setPen( QtGui.QPen( QtCore.Qt.black, <NUM_LIT:1>, QtCore.Qt.DotLine ) )<EOL>p.drawRect( self.rect[<NUM_LIT:0>], self.rect[<NUM_LIT:1>], self.rect[<NUM_LIT:2>], self.rect[<NUM_LIT:3>] )<EOL><DEDENT>p.end()<EOL><DEDENT>else:<EOL><INDENT>bbox = self.replot<EOL>l, b, r, t = bbox.extents<EOL>w = int(r) - int(l)<EOL>h = int(t) - int(b)<EOL>t = int(b) + h<EOL>reg = self.copy_from_bbox(bbox)<EOL>stringBuffer = reg.to_string_argb()<EOL>qImage = QtGui.QImage(stringBuffer, w, h, QtGui.QImage.Format_ARGB32)<EOL>pixmap = QtGui.QPixmap.fromImage(qImage)<EOL>p = QtGui.QPainter( self )<EOL>p.drawPixmap(QtCore.QPoint(l, self.renderer.height-t), pixmap)<EOL>p.end()<EOL><DEDENT>self.replot = False<EOL>self.drawRect = False<EOL>

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.


if DEBUG: print("<STR_LIT>", self)<EOL>self.replot = True<EOL>FigureCanvasAgg.draw(self)<EOL>self.update()<EOL>QtGui.qApp.processEvents()<EOL>

Draw the figure when xwindows is ready for the update


self.replot = bbox<EOL>l, b, w, h = bbox.bounds<EOL>t = b + h<EOL>self.update(l, self.renderer.height-t, w, h)<EOL>


if _debug: print('<STR_LIT>' % (self.__class__.__name__, _fn_name()))<EOL>FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>thisFig = FigureClass(*args, **kwargs)<EOL>canvas  = FigureCanvasCairo(thisFig)<EOL>manager = FigureManagerBase(canvas, num)<EOL>return manager<EOL>


if not is_string_like(msg):<EOL><INDENT>msg = '<STR_LIT:\n>'.join(map(str, msg))<EOL><DEDENT>return msg<EOL>

msg is a return arg from a raise.  Join with new lines


for manager in Gcf.get_all_fig_managers():<EOL><INDENT>manager.show()<EOL><DEDENT>import matplotlib<EOL>matplotlib.interactive(True)<EOL>if rcParams['<STR_LIT>']:<EOL><INDENT>os.environ['<STR_LIT>'] = '<STR_LIT:1>'<EOL><DEDENT>if show._needmain:<EOL><INDENT>Tk.mainloop()<EOL>show._needmain = False<EOL><DEDENT>

Show all the figures and enter the gtk mainloop

This should be the last line of your script.  This function sets
interactive mode to True, as detailed on
http://matplotlib.sf.net/interactive.html


_focus = windowing.FocusManager()<EOL>FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>figure = FigureClass(*args, **kwargs)<EOL>window = Tk.Tk()<EOL>canvas = FigureCanvasTkAgg(figure, master=window)<EOL>figManager = FigureManagerTkAgg(canvas, num, window)<EOL>if matplotlib.is_interactive():<EOL><INDENT>figManager.show()<EOL><DEDENT>return figManager<EOL>


d = self._idle<EOL>self._idle = False<EOL>def idle_draw(*args):<EOL><INDENT>self.draw()<EOL>self._idle = True<EOL><DEDENT>if d:<EOL><INDENT>self._tkcanvas.after_idle(idle_draw)<EOL><DEDENT>


return self._tkcanvas<EOL>

returns the Tk widget used to implement FigureCanvasTkAgg.
        Although the initial implementation uses a Tk canvas,  this routine
        is intended to hide that fact.


<EOL>w = event.widget.winfo_containing(event.x_root, event.y_root)<EOL>if w == self._tkcanvas:<EOL><INDENT>x = event.x_root - w.winfo_rootx()<EOL>y = event.y_root - w.winfo_rooty()<EOL>y = self.figure.bbox.height - y<EOL>step = event.delta/<NUM_LIT><EOL>FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=event)<EOL><DEDENT>


def destroy(*args):<EOL><INDENT>self.window = None<EOL>Gcf.destroy(self._num)<EOL><DEDENT>if not self._shown:<EOL><INDENT>self.canvas._tkcanvas.bind("<STR_LIT>", destroy)<EOL><DEDENT>_focus = windowing.FocusManager()<EOL>if not self._shown:<EOL><INDENT>self.window.deiconify()<EOL>if sys.platform == '<STR_LIT:win32>':<EOL><INDENT>self.window.update()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.canvas.draw()<EOL><DEDENT>self._shown = True<EOL>

this function doesn't segfault but causes the
PyEval_RestoreThread: NULL state bug on win32


pass<EOL>

For image backends - is not required
For GUI backends - this should be overriden if drawing should be done in
interactive python mode


for manager in Gcf.get_all_fig_managers():<EOL><INDENT>pass<EOL><DEDENT>

For image backends - is not required
For GUI backends - show() is usually the last line of a pylab script and
tells the backend that it is time to draw.  In interactive mode, this may
be a do nothing func.  See the GTK backend for an example of how to handle
interactive versus batch mode


<EOL>FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>thisFig = FigureClass(*args, **kwargs)<EOL>canvas = FigureCanvasTemplate(thisFig)<EOL>manager = FigureManagerTemplate(canvas, num)<EOL>return manager<EOL>


renderer = RendererTemplate(self.figure.dpi)<EOL>self.figure.draw(renderer)<EOL>


def print_foo(self, filename, *args, **kwargs):

pass<EOL>

Write out format foo.  The dpi, facecolor and edgecolor are restored
to their original values after this call, so you don't need to
save and restore them.


if matplotlib.is_interactive():<EOL><INDENT>figManager =  Gcf.get_active()<EOL>if figManager != None:<EOL><INDENT>figManager.canvas.draw()<EOL><DEDENT><DEDENT>

Is called after every pylab drawing command


if qt.QApplication.startingUp():<EOL><INDENT>if DEBUG: print("<STR_LIT>")<EOL>global qApp<EOL>qApp = qt.QApplication( ["<STR_LIT:U+0020>"] )<EOL>qt.QObject.connect( qApp, qt.SIGNAL( "<STR_LIT>" ),<EOL>qApp, qt.SLOT( "<STR_LIT>" ) )<EOL>_create_qApp.qAppCreatedHere = True<EOL><DEDENT>

Only one qApp can exist at a time, so check before creating one


for manager in Gcf.get_all_fig_managers():<EOL><INDENT>manager.window.show()<EOL><DEDENT>if DEBUG: print('<STR_LIT>')<EOL>figManager =  Gcf.get_active()<EOL>if figManager != None:<EOL><INDENT>figManager.canvas.draw()<EOL><DEDENT>if _create_qApp.qAppCreatedHere:<EOL><INDENT>qt.qApp.exec_loop()<EOL><DEDENT>

Show all the figures and enter the qt main loop
This should be the last line of your script


FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>thisFig = FigureClass( *args, **kwargs )<EOL>canvas = FigureCanvasQT( thisFig )<EOL>manager = FigureManagerQT( canvas, num )<EOL>return manager<EOL>


def exception_handler( type, value, tb ):

msg = '<STR_LIT>'<EOL>if hasattr(value, '<STR_LIT:filename>') and value.filename != None:<EOL><INDENT>msg = value.filename + '<STR_LIT>'<EOL><DEDENT>if hasattr(value, '<STR_LIT>') and value.strerror != None:<EOL><INDENT>msg += value.strerror<EOL><DEDENT>else:<EOL><INDENT>msg += str(value)<EOL><DEDENT>if len( msg ) : error_msg_qt( msg )<EOL>

Handle uncaught exceptions
    It does not catch SystemExit


self.window.resize(width, height)<EOL>


if _debug: print('<STR_LIT>' % fn_name())<EOL>FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>thisFig = FigureClass(*args, **kwargs)<EOL>canvas = FigureCanvasGTKCairo(thisFig)<EOL>return FigureManagerGTK(canvas, num)<EOL>


if _debug: print('<STR_LIT>' % (self.__class__.__name__, _fn_name()))<EOL>self._renderer = RendererGTKCairo (self.figure.dpi)<EOL>

Override to use cairo (rather than GDK) renderer


def __init__(self, width, height, dpi, vector_renderer, raster_renderer_class=None):

if raster_renderer_class is None:<EOL><INDENT>raster_renderer_class = RendererAgg<EOL><DEDENT>self._raster_renderer_class = raster_renderer_class<EOL>self._width = width<EOL>self._height = height<EOL>self.dpi = dpi<EOL>assert not vector_renderer.option_image_nocomposite()<EOL>self._vector_renderer = vector_renderer<EOL>self._raster_renderer = None<EOL>self._rasterizing = <NUM_LIT:0><EOL>self._set_current_renderer(vector_renderer)<EOL>

width: The width of the canvas in logical units

height: The height of the canvas in logical units

dpi: The dpi of the canvas

vector_renderer: An instance of a subclass of RendererBase
that will be used for the vector drawing.

raster_renderer_class: The renderer class to use for the
raster drawing.  If not provided, this will use the Agg
backend (which is currently the only viable option anyway.)


if self._rasterizing == <NUM_LIT:0>:<EOL><INDENT>self._raster_renderer = self._raster_renderer_class(<EOL>self._width*self.dpi, self._height*self.dpi, self.dpi)<EOL>self._set_current_renderer(self._raster_renderer)<EOL><DEDENT>self._rasterizing += <NUM_LIT:1><EOL>

Enter "raster" mode.  All subsequent drawing commands (until
stop_rasterizing is called) will be drawn with the raster
backend.

If start_rasterizing is called multiple times before
stop_rasterizing is called, this method has no effect.


self._rasterizing -= <NUM_LIT:1><EOL>if self._rasterizing == <NUM_LIT:0>:<EOL><INDENT>self._set_current_renderer(self._vector_renderer)<EOL>width, height = self._width * self.dpi, self._height * self.dpi<EOL>buffer, bounds = self._raster_renderer.tostring_rgba_minimized()<EOL>l, b, w, h = bounds<EOL>if w > <NUM_LIT:0> and h > <NUM_LIT:0>:<EOL><INDENT>image = frombuffer(buffer, w, h, True)<EOL>image.is_grayscale = False<EOL>image.flipud_out()<EOL>self._renderer.draw_image(l, height - b - h, image, None)<EOL><DEDENT>self._raster_renderer = None<EOL>self._rasterizing = False<EOL><DEDENT>

Exit "raster" mode.  All of the drawing that was done since
the last start_rasterizing command will be copied to the
vector backend by calling draw_image.

If stop_rasterizing is called multiple times before
start_rasterizing is called, this method has no effect.


<EOL>DEBUG_MSG("<STR_LIT>", <NUM_LIT:3>, None)<EOL>backend_wx._create_wx_app()<EOL>FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>fig = FigureClass(*args, **kwargs)<EOL>frame = FigureFrameWxAgg(num, fig)<EOL>figmgr = frame.get_figure_manager()<EOL>if matplotlib.is_interactive():<EOL><INDENT>figmgr.frame.Show()<EOL><DEDENT>return figmgr<EOL>


image = wx.EmptyImage(int(agg.width), int(agg.height))<EOL>image.SetData(agg.tostring_rgb())<EOL>if bbox is None:<EOL><INDENT>return image<EOL><DEDENT>else:<EOL><INDENT>return wx.ImageFromBitmap(_clipped_image_as_bitmap(image, bbox))<EOL><DEDENT>

Convert the region of the agg buffer bounded by bbox to a wx.Image.  If
bbox is None, the entire buffer is converted.

Note: agg must be a backend_agg.RendererAgg instance.


if bbox is None:<EOL><INDENT>return wx.BitmapFromImage(_py_convert_agg_to_wx_image(agg, None))<EOL><DEDENT>else:<EOL><INDENT>return _clipped_image_as_bitmap(<EOL>_py_convert_agg_to_wx_image(agg, None),<EOL>bbox)<EOL><DEDENT>

Convert the region of the agg buffer bounded by bbox to a wx.Bitmap.  If
bbox is None, the entire buffer is converted.

Note: agg must be a backend_agg.RendererAgg instance.


l, b, width, height = bbox.get_bounds()<EOL>r = l + width<EOL>t = b + height<EOL>srcBmp = wx.BitmapFromImage(image)<EOL>srcDC = wx.MemoryDC()<EOL>srcDC.SelectObject(srcBmp)<EOL>destBmp = wx.EmptyBitmap(int(width), int(height))<EOL>destDC = wx.MemoryDC()<EOL>destDC.SelectObject(destBmp)<EOL>destDC.BeginDrawing()<EOL>x = int(l)<EOL>y = int(image.GetHeight() - t)<EOL>destDC.Blit(<NUM_LIT:0>, <NUM_LIT:0>, int(width), int(height), srcDC, x, y)<EOL>destDC.EndDrawing()<EOL>srcDC.SelectObject(wx.NullBitmap)<EOL>destDC.SelectObject(wx.NullBitmap)<EOL>return destBmp<EOL>

Convert the region of a wx.Image bounded by bbox to a wx.Bitmap.


if bbox is None:<EOL><INDENT>image = wx.EmptyImage(int(agg.width), int(agg.height))<EOL>image.SetData(agg.tostring_rgb())<EOL>return image<EOL><DEDENT>else:<EOL><INDENT>return wx.ImageFromBitmap(_WX28_clipped_agg_as_bitmap(agg, bbox))<EOL><DEDENT>


if bbox is None:<EOL><INDENT>return wx.BitmapFromBufferRGBA(int(agg.width), int(agg.height),<EOL>agg.buffer_rgba(<NUM_LIT:0>, <NUM_LIT:0>))<EOL><DEDENT>else:<EOL><INDENT>return _WX28_clipped_agg_as_bitmap(agg, bbox)<EOL><DEDENT>


l, b, width, height = bbox.get_bounds()<EOL>r = l + width<EOL>t = b + height<EOL>srcBmp = wx.BitmapFromBufferRGBA(int(agg.width), int(agg.height),<EOL>agg.buffer_rgba(<NUM_LIT:0>, <NUM_LIT:0>))<EOL>srcDC = wx.MemoryDC()<EOL>srcDC.SelectObject(srcBmp)<EOL>destBmp = wx.EmptyBitmap(int(width), int(height))<EOL>destDC = wx.MemoryDC()<EOL>destDC.SelectObject(destBmp)<EOL>destDC.BeginDrawing()<EOL>x = int(l)<EOL>y = int(int(agg.height) - t)<EOL>destDC.Blit(<NUM_LIT:0>, <NUM_LIT:0>, int(width), int(height), srcDC, x, y)<EOL>destDC.EndDrawing()<EOL>srcDC.SelectObject(wx.NullBitmap)<EOL>destDC.SelectObject(wx.NullBitmap)<EOL>return destBmp<EOL>

Convert the region of a the agg buffer bounded by bbox to a wx.Bitmap.

Note: agg must be a backend_agg.RendererAgg instance.


global _convert_agg_to_wx_image<EOL>global _convert_agg_to_wx_bitmap<EOL>if getattr(wx, '<STR_LIT>', '<STR_LIT>')[<NUM_LIT:0>:<NUM_LIT:3>] < '<STR_LIT>':<EOL><INDENT>if state and _wxagg is not None:<EOL><INDENT>_convert_agg_to_wx_image  = _wxagg.convert_agg_to_wx_image<EOL>_convert_agg_to_wx_bitmap = _wxagg.convert_agg_to_wx_bitmap<EOL><DEDENT>else:<EOL><INDENT>_convert_agg_to_wx_image  = _py_convert_agg_to_wx_image<EOL>_convert_agg_to_wx_bitmap = _py_convert_agg_to_wx_bitmap<EOL><DEDENT><DEDENT>else:<EOL><INDENT>_convert_agg_to_wx_image  = _py_WX28_convert_agg_to_wx_image<EOL>_convert_agg_to_wx_bitmap = _py_WX28_convert_agg_to_wx_bitmap<EOL><DEDENT>

Enable or disable the WXAgg accelerator, if it is present and is also
compatible with whatever version of wxPython is in use.


DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>FigureCanvasAgg.draw(self)<EOL>self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None)<EOL>self._isDrawn = True<EOL>self.gui_repaint(drawDC=drawDC)<EOL>


if bbox is None:<EOL><INDENT>self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None)<EOL>self.gui_repaint()<EOL>return<EOL><DEDENT>l, b, w, h = bbox.bounds<EOL>r = l + w<EOL>t = b + h<EOL>x = int(l)<EOL>y = int(self.bitmap.GetHeight() - t)<EOL>srcBmp = _convert_agg_to_wx_bitmap(self.get_renderer(), None)<EOL>srcDC = wx.MemoryDC()<EOL>srcDC.SelectObject(srcBmp)<EOL>destDC = wx.MemoryDC()<EOL>destDC.SelectObject(self.bitmap)<EOL>destDC.BeginDrawing()<EOL>destDC.Blit(x, y, int(w), int(h), srcDC, x, y)<EOL>destDC.EndDrawing()<EOL>destDC.SelectObject(wx.NullBitmap)<EOL>srcDC.SelectObject(wx.NullBitmap)<EOL>self.gui_repaint()<EOL>

Transfer the region of the agg buffer defined by bbox to the display.
If bbox is None, the entire buffer is transferred.


for manager in Gcf.get_all_fig_managers():<EOL><INDENT>manager.show()<EOL><DEDENT>if show._needmain:<EOL><INDENT>_thread.start_new_thread(Fltk_run_interactive,())<EOL><DEDENT>show._needmain = False<EOL>

Show all the figures and enter the fltk mainloop in another thread
This allows to keep hand in interractive python session
Warning: does not work under windows
This should be the last line of your script


for manager in Gcf.get_all_fig_managers():<EOL><INDENT>manager.show()<EOL><DEDENT>if show._needmain:<EOL><INDENT>Fltk.Fl.run()<EOL>show._needmain = False<EOL><DEDENT>

Show all the figures and enter the fltk mainloop

This should be the last line of your script


FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>figure = FigureClass(*args, **kwargs)<EOL>window = Fltk.Fl_Double_Window(<NUM_LIT:10>,<NUM_LIT:10>,<NUM_LIT:30>,<NUM_LIT:30>)<EOL>canvas = FigureCanvasFltkAgg(figure)<EOL>window.end()<EOL>window.show()<EOL>window.make_current()<EOL>figManager = FigureManagerFltkAgg(canvas, num, window)<EOL>if matplotlib.is_interactive():<EOL><INDENT>figManager.show()<EOL><DEDENT>return figManager<EOL>


if DEBUG: print('<STR_LIT>')<EOL>FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>thisFig = FigureClass( *args, **kwargs )<EOL>canvas = FigureCanvasQTAgg( thisFig )<EOL>return FigureManagerQTAgg( canvas, num )<EOL>


FigureCanvasQT.paintEvent( self, e )<EOL>if DEBUG: print('<STR_LIT>', self,self.get_width_height())<EOL>p = qt.QPainter( self )<EOL>if type(self.replot) is bool: <EOL><INDENT>if self.replot:<EOL><INDENT>FigureCanvasAgg.draw( self )<EOL>if ( qt.QImage.systemByteOrder() == qt.QImage.LittleEndian ):<EOL><INDENT>stringBuffer = self.renderer._renderer.tostring_bgra()<EOL><DEDENT>else:<EOL><INDENT>stringBuffer = self.renderer._renderer.tostring_argb()<EOL><DEDENT>qImage = qt.QImage( stringBuffer, self.renderer.width,<EOL>self.renderer.height, <NUM_LIT:32>, None, <NUM_LIT:0>,<EOL>qt.QImage.IgnoreEndian )<EOL>self.pixmap.convertFromImage( qImage, qt.QPixmap.Color )<EOL><DEDENT>p.drawPixmap( qt.QPoint( <NUM_LIT:0>, <NUM_LIT:0> ), self.pixmap )<EOL>if ( self.drawRect ):<EOL><INDENT>p.setPen( qt.QPen( qt.Qt.black, <NUM_LIT:1>, qt.Qt.DotLine ) )<EOL>p.drawRect( self.rect[<NUM_LIT:0>], self.rect[<NUM_LIT:1>], self.rect[<NUM_LIT:2>], self.rect[<NUM_LIT:3>] )<EOL><DEDENT><DEDENT>else:<EOL><INDENT>bbox = self.replot<EOL>l, b, r, t = bbox.extents<EOL>w = int(r) - int(l)<EOL>h = int(t) - int(b)<EOL>reg = self.copy_from_bbox(bbox)<EOL>stringBuffer = reg.to_string_argb()<EOL>qImage = qt.QImage(stringBuffer, w, h, <NUM_LIT:32>, None, <NUM_LIT:0>, qt.QImage.IgnoreEndian)<EOL>self.pixmap.convertFromImage(qImage, qt.QPixmap.Color)<EOL>p.drawPixmap(qt.QPoint(l, self.renderer.height-t), self.pixmap)<EOL><DEDENT>p.end()<EOL>self.replot = False<EOL>self.drawRect = False<EOL>

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.


if DEBUG: print("<STR_LIT>", self)<EOL>self.replot = True<EOL>FigureCanvasAgg.draw(self)<EOL>self.repaint(False)<EOL>

Draw the figure when xwindows is ready for the update


self.replot = bbox<EOL>self.repaint(False)<EOL>


FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>thisFig = FigureClass(*args, **kwargs)<EOL>canvas  = FigureCanvasGDK(thisFig)<EOL>manager = FigureManagerBase(canvas, num)<EOL>return manager<EOL>


def set_width_height (self, width, height):

self.width, self.height = width, height<EOL>

w,h is the figure w,h not the pixmap w,h


def _draw_rotated_text(self, gc, x, y, s, prop, angle):

<EOL>gdrawable = self.gdkDrawable<EOL>ggc = gc.gdkGC<EOL>layout, inkRect, logicalRect = self._get_pango_layout(s, prop)<EOL>l, b, w, h = inkRect<EOL>x = int(x-h)<EOL>y = int(y-w)<EOL>if x < <NUM_LIT:0> or y < <NUM_LIT:0>: <EOL><INDENT>return<EOL><DEDENT>key = (x,y,s,angle,hash(prop))<EOL>imageVert = self.rotated.get(key)<EOL>if imageVert != None:<EOL><INDENT>gdrawable.draw_image(ggc, imageVert, <NUM_LIT:0>, <NUM_LIT:0>, x, y, h, w)<EOL>return<EOL><DEDENT>imageBack = gdrawable.get_image(x, y, w, h)<EOL>imageVert = gdrawable.get_image(x, y, h, w)<EOL>imageFlip = gtk.gdk.Image(type=gdk.IMAGE_FASTEST,<EOL>visual=gdrawable.get_visual(),<EOL>width=w, height=h)<EOL>if imageFlip == None or imageBack == None or imageVert == None:<EOL><INDENT>warnings.warn("<STR_LIT>")<EOL>return<EOL><DEDENT>imageFlip.set_colormap(self._cmap)<EOL>for i in range(w):<EOL><INDENT>for j in range(h):<EOL><INDENT>imageFlip.put_pixel(i, j, imageVert.get_pixel(j,w-i-<NUM_LIT:1>) )<EOL><DEDENT><DEDENT>gdrawable.draw_image(ggc, imageFlip, <NUM_LIT:0>, <NUM_LIT:0>, x, y, w, h)<EOL>gdrawable.draw_layout(ggc, x, y-b, layout)<EOL>imageIn  = gdrawable.get_image(x, y, w, h)<EOL>for i in range(w):<EOL><INDENT>for j in range(h):<EOL><INDENT>imageVert.put_pixel(j, i, imageIn.get_pixel(w-i-<NUM_LIT:1>,j) )<EOL><DEDENT><DEDENT>gdrawable.draw_image(ggc, imageBack, <NUM_LIT:0>, <NUM_LIT:0>, x, y, w, h)<EOL>gdrawable.draw_image(ggc, imageVert, <NUM_LIT:0>, <NUM_LIT:0>, x, y, h, w)<EOL>self.rotated[key] = imageVert<EOL>

Draw the text rotated 90 degrees, other angles are not supported


<EOL>key = self.dpi, s, hash(prop)<EOL>value = self.layoutd.get(key)<EOL>if value != None:<EOL><INDENT>return value<EOL><DEDENT>size = prop.get_size_in_points() * self.dpi / <NUM_LIT><EOL>size = round(size)<EOL>font_str = '<STR_LIT>' % (prop.get_name(), prop.get_style(), size,)<EOL>font = pango.FontDescription(font_str)<EOL>font.set_weight(self.fontweights[prop.get_weight()])<EOL>layout = self.gtkDA.create_pango_layout(s)<EOL>layout.set_font_description(font)<EOL>inkRect, logicalRect = layout.get_pixel_extents()<EOL>self.layoutd[key] = layout, inkRect, logicalRect<EOL>return layout, inkRect, logicalRect<EOL>

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


try:<EOL><INDENT>return self._cached[tuple(rgb)]<EOL><DEDENT>except KeyError:<EOL><INDENT>color = self._cached[tuple(rgb)] =self._cmap.alloc_color(<EOL>int(rgb[<NUM_LIT:0>]*<NUM_LIT>),int(rgb[<NUM_LIT:1>]*<NUM_LIT>),int(rgb[<NUM_LIT:2>]*<NUM_LIT>))<EOL>return color<EOL><DEDENT>

rgb - an RGB tuple (three 0.0-1.0 values)
return an allocated gtk.gdk.Color


if DEBUG: print('<STR_LIT>')<EOL>FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>thisFig = FigureClass(*args, **kwargs)<EOL>canvas = FigureCanvasGTKAgg(thisFig)<EOL>return FigureManagerGTKAgg(canvas, num)<EOL>if DEBUG: print('<STR_LIT>')<EOL>


<EOL>if backend.startswith('<STR_LIT>'):<EOL><INDENT>backend_name = backend[<NUM_LIT:9>:]<EOL><DEDENT>else:<EOL><INDENT>backend_name = '<STR_LIT>'+backend<EOL>backend_name = backend_name.lower() <EOL>backend_name = '<STR_LIT>'%backend_name.lower()<EOL><DEDENT>backend_mod = __import__(backend_name,<EOL>globals(),locals(),[backend_name])<EOL>new_figure_manager = backend_mod.new_figure_manager<EOL>def do_nothing_show(*args, **kwargs):<EOL><INDENT>frame = inspect.currentframe()<EOL>fname = frame.f_back.f_code.co_filename<EOL>if fname in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>warnings.warn("""<STR_LIT>""" %<EOL>(backend, matplotlib.matplotlib_fname()))<EOL><DEDENT><DEDENT>def do_nothing(*args, **kwargs): pass<EOL>backend_version = getattr(backend_mod,'<STR_LIT>', '<STR_LIT>')<EOL>show = getattr(backend_mod, '<STR_LIT>', do_nothing_show)<EOL>draw_if_interactive = getattr(backend_mod, '<STR_LIT>', do_nothing)<EOL>if backend.lower() in ['<STR_LIT>','<STR_LIT>']:<EOL><INDENT>Toolbar = backend_mod.Toolbar<EOL>__all__.append('<STR_LIT>')<EOL><DEDENT>matplotlib.verbose.report('<STR_LIT>' % (backend,backend_version))<EOL>return new_figure_manager, draw_if_interactive, show<EOL>

return new_figure_manager, draw_if_interactive and show for pylab


if __debug__: verbose.report('<STR_LIT>',<EOL>'<STR_LIT>')<EOL>FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>thisFig = FigureClass(*args, **kwargs)<EOL>canvas = FigureCanvasAgg(thisFig)<EOL>manager = FigureManagerBase(canvas, num)<EOL>return manager<EOL>


def draw_mathtext(self, gc, x, y, s, prop, angle):

if __debug__: verbose.report('<STR_LIT>',<EOL>'<STR_LIT>')<EOL>ox, oy, width, height, descent, font_image, used_characters =self.mathtext_parser.parse(s, self.dpi, prop)<EOL>x = int(x) + ox<EOL>y = int(y) - oy<EOL>self._renderer.draw_text_image(font_image, x, y + <NUM_LIT:1>, angle, gc)<EOL>

Draw the math text using matplotlib.mathtext


def draw_text(self, gc, x, y, s, prop, angle, ismath):

if __debug__: verbose.report('<STR_LIT>', '<STR_LIT>')<EOL>if ismath:<EOL><INDENT>return self.draw_mathtext(gc, x, y, s, prop, angle)<EOL><DEDENT>font = self._get_agg_font(prop)<EOL>if font is None: return None<EOL>if len(s) == <NUM_LIT:1> and ord(s) > <NUM_LIT>:<EOL><INDENT>font.load_char(ord(s), flags=LOAD_FORCE_AUTOHINT)<EOL><DEDENT>else:<EOL><INDENT>font.set_text(s, <NUM_LIT:0>, flags=LOAD_FORCE_AUTOHINT)<EOL><DEDENT>font.draw_glyphs_to_bitmap()<EOL>self._renderer.draw_text_image(font.get_image(), int(x), int(y) + <NUM_LIT:1>, angle, gc)<EOL>


def get_text_width_height_descent(self, s, prop, ismath):

if ismath=='<STR_LIT>':<EOL><INDENT>size = prop.get_size_in_points()<EOL>texmanager = self.get_texmanager()<EOL>Z = texmanager.get_grey(s, size, self.dpi)<EOL>m,n = Z.shape<EOL>return n, m, <NUM_LIT:0><EOL><DEDENT>if ismath:<EOL><INDENT>ox, oy, width, height, descent, fonts, used_characters =self.mathtext_parser.parse(s, self.dpi, prop)<EOL>return width, height, descent<EOL><DEDENT>font = self._get_agg_font(prop)<EOL>font.set_text(s, <NUM_LIT:0.0>, flags=LOAD_FORCE_AUTOHINT)  <EOL>w, h = font.get_width_height()<EOL>d = font.get_descent()<EOL>w /= <NUM_LIT>  <EOL>h /= <NUM_LIT><EOL>d /= <NUM_LIT><EOL>return w, h, d<EOL>

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


return self.width, self.height<EOL>

return the canvas width and height in display coords


if __debug__: verbose.report('<STR_LIT>',<EOL>'<STR_LIT>')<EOL>key = hash(prop)<EOL>font = self._fontd.get(key)<EOL>if font is None:<EOL><INDENT>fname = findfont(prop)<EOL>font = self._fontd.get(fname)<EOL>if font is None:<EOL><INDENT>font = FT2Font(str(fname))<EOL>self._fontd[fname] = font<EOL><DEDENT>self._fontd[key] = font<EOL><DEDENT>font.clear()<EOL>size = prop.get_size_in_points()<EOL>font.set_size(size, self.dpi)<EOL>return font<EOL>

Get the font for text instance t, cacheing for efficiency


if __debug__: verbose.report('<STR_LIT>',<EOL>'<STR_LIT>')<EOL>return points*self.dpi/<NUM_LIT><EOL>

convert point measures to pixes using dpi and the pixels per
inch of the display


if __debug__: verbose.report('<STR_LIT>', '<STR_LIT>')<EOL>self.renderer = self.get_renderer()<EOL>self.figure.draw(self.renderer)<EOL>


traceback.print_exc(type, value, tb)<EOL>print()<EOL>pdb.pm()<EOL>

Code due to Thomas Heller - published in Python Cookbook (O'Reilley)


dialog =wx.MessageDialog(parent  = parent,<EOL>message = msg,<EOL>caption = '<STR_LIT>',<EOL>style=wx.OK | wx.CENTRE)<EOL>dialog.ShowModal()<EOL>dialog.Destroy()<EOL>return None<EOL>

Signal an error condition -- in a GUI, popup a error dialog


if not is_string_like(msg):<EOL><INDENT>msg = '<STR_LIT:\n>'.join(map(str, msg))<EOL><DEDENT>return msg<EOL>

msg is a return arg from a raise.  Join with new lines


wxapp = wx.GetApp()<EOL>if wxapp is None:<EOL><INDENT>wxapp = wx.PySimpleApp()<EOL>wxapp.SetExitOnFrameDelete(True)<EOL>_create_wx_app.theWxApp = wxapp<EOL><DEDENT>

Creates a wx.PySimpleApp instance if a wx.App has not been created.


DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, None)<EOL>if matplotlib.is_interactive():<EOL><INDENT>figManager = Gcf.get_active()<EOL>if figManager is not None:<EOL><INDENT>figManager.canvas.draw()<EOL><DEDENT><DEDENT>

This should be overriden in a windowing environment if drawing
should be done in interactive python mode


DEBUG_MSG("<STR_LIT>", <NUM_LIT:3>, None)<EOL>for figwin in Gcf.get_all_fig_managers():<EOL><INDENT>figwin.frame.Show()<EOL><DEDENT>if show._needmain and not matplotlib.is_interactive():<EOL><INDENT>wxapp = wx.GetApp()<EOL>if wxapp is not None:<EOL><INDENT>imlr = getattr(wxapp, '<STR_LIT>', lambda: False)<EOL>if not imlr():<EOL><INDENT>wxapp.MainLoop()<EOL><DEDENT><DEDENT>show._needmain = False<EOL><DEDENT>

Current implementation assumes that matplotlib is executed in a PyCrust
shell. It appears to be possible to execute wxPython applications from
within a PyCrust without having to ensure that wxPython has been created
in a secondary thread (e.g. SciPy gui_thread).

Unfortunately, gui_thread seems to introduce a number of further
dependencies on SciPy modules, which I do not wish to introduce
into the backend at this point. If there is a need I will look
into this in a later release.


<EOL>DEBUG_MSG("<STR_LIT>", <NUM_LIT:3>, None)<EOL>_create_wx_app()<EOL>FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>fig = FigureClass(*args, **kwargs)<EOL>frame = FigureFrameWx(num, fig)<EOL>figmgr = frame.get_figure_manager()<EOL>if matplotlib.is_interactive():<EOL><INDENT>figmgr.frame.Show()<EOL><DEDENT>return figmgr<EOL>


basedir = os.path.join(rcParams['<STR_LIT>'],'<STR_LIT>')<EOL>bmpFilename = os.path.normpath(os.path.join(basedir, filename))<EOL>if not os.path.exists(bmpFilename):<EOL><INDENT>raise IOError('<STR_LIT>'%bmpFilename)<EOL><DEDENT>bmp = wx.Bitmap(bmpFilename)<EOL>return bmp<EOL>

Load a bitmap file from the backends/images subdirectory in which the
matplotlib library is installed. The filename parameter should not
contain any path information as this is determined automatically.

Returns a wx.Bitmap object


DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>if wx.VERSION_STRING < "<STR_LIT>":<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>self.width  = bitmap.GetWidth()<EOL>self.height = bitmap.GetHeight()<EOL>self.bitmap = bitmap<EOL>self.fontd = {}<EOL>self.dpi = dpi<EOL>self.gc = None<EOL>

Initialise a wxWindows renderer instance.


<EOL>if ismath: s = self.strip_math(s)<EOL>if self.gc is None:<EOL><INDENT>gc = self.new_gc()<EOL><DEDENT>else:<EOL><INDENT>gc = self.gc<EOL><DEDENT>gfx_ctx = gc.gfx_ctx<EOL>font = self.get_wx_font(s, prop)<EOL>gfx_ctx.SetFont(font, wx.BLACK)<EOL>w, h, descent, leading = gfx_ctx.GetFullTextExtent(s)<EOL>return w, h, descent<EOL>

get the width and height in display coords of the string s
with FontPropertry prop


return self.width, self.height<EOL>


if ismath: s = self.strip_math(s)<EOL>DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>gc.select()<EOL>self.handle_clip_rectangle(gc)<EOL>gfx_ctx = gc.gfx_ctx<EOL>font = self.get_wx_font(s, prop)<EOL>color = gc.get_wxcolour(gc.get_rgb())<EOL>gfx_ctx.SetFont(font, color)<EOL>w, h, d = self.get_text_width_height_descent(s, prop, ismath)<EOL>x = int(x)<EOL>y = int(y-h)<EOL>if angle == <NUM_LIT:0.0>:<EOL><INDENT>gfx_ctx.DrawText(s, x, y)<EOL><DEDENT>else:<EOL><INDENT>rads = angle / <NUM_LIT> * math.pi<EOL>xo = h * math.sin(rads)<EOL>yo = h * math.cos(rads)<EOL>gfx_ctx.DrawRotatedText(s, x - xo, y - yo, rads)<EOL><DEDENT>gc.unselect()<EOL>

Render the matplotlib.text.Text instance
None)


DEBUG_MSG('<STR_LIT>', <NUM_LIT:2>, self)<EOL>self.gc = GraphicsContextWx(self.bitmap, self)<EOL>self.gc.select()<EOL>self.gc.unselect()<EOL>return self.gc<EOL>

Return an instance of a GraphicsContextWx, and sets the current gc copy


<EOL>assert self.gc != None, "<STR_LIT>"<EOL>return self.gc<EOL>


DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>key = hash(prop)<EOL>fontprop = prop<EOL>fontname = fontprop.get_name()<EOL>font = self.fontd.get(key)<EOL>if font is not None:<EOL><INDENT>return font<EOL><DEDENT>wxFontname = self.fontnames.get(fontname, wx.ROMAN)<EOL>wxFacename = '<STR_LIT>' <EOL>size = self.points_to_pixels(fontprop.get_size_in_points())<EOL>font =wx.Font(int(size+<NUM_LIT:0.5>),             <EOL>wxFontname,                <EOL>self.fontangles[fontprop.get_style()],   <EOL>self.fontweights[fontprop.get_weight()], <EOL>False,                     <EOL>wxFacename)                <EOL>self.fontd[key] = font<EOL>return font<EOL>

Return a wx font.  Cache instances in a font dictionary for
efficiency


return points*(PIXELS_PER_INCH/<NUM_LIT>*self.dpi/<NUM_LIT>)<EOL>


if sys.platform=='<STR_LIT:win32>':<EOL><INDENT>self.dc.SelectObject(self.bitmap)<EOL>self.IsSelected = True<EOL><DEDENT>

Select the current bitmap into this wxDC instance


if sys.platform=='<STR_LIT:win32>':<EOL><INDENT>self.dc.SelectObject(wx.NullBitmap)<EOL>self.IsSelected = False<EOL><DEDENT>

Select a Null bitmasp into this wxDC instance


def set_foreground(self, fg, isRGB=None):

<EOL>DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>self.select()<EOL>GraphicsContextBase.set_foreground(self, fg, isRGB)<EOL>self._pen.SetColour(self.get_wxcolour(self.get_rgb()))<EOL>self.gfx_ctx.SetPen(self._pen)<EOL>self.unselect()<EOL>

Set the foreground color.  fg can be a matlab format string, a
html hex color string, an rgb unit tuple, or a float between 0
and 1.  In the latter case, grayscale is used.


DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>self.select()<EOL>if w><NUM_LIT:0> and w<<NUM_LIT:1>: w = <NUM_LIT:1><EOL>GraphicsContextBase.set_linewidth(self, w)<EOL>lw = int(self.renderer.points_to_pixels(self._linewidth))<EOL>if lw==<NUM_LIT:0>: lw = <NUM_LIT:1><EOL>self._pen.SetWidth(lw)<EOL>self.gfx_ctx.SetPen(self._pen)<EOL>self.unselect()<EOL>


Set the capstyle as a string in ('butt', 'round', 'projecting')


Set the join style to be one of ('miter', 'round', 'bevel')


DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>self.select()<EOL>GraphicsContextBase.set_linestyle(self, ls)<EOL>try:<EOL><INDENT>self._style = GraphicsContextWx._dashd_wx[ls]<EOL><DEDENT>except KeyError:<EOL><INDENT>self._style = wx.LONG_DASH<EOL><DEDENT>if wx.Platform == '<STR_LIT>':<EOL><INDENT>self.set_linewidth(<NUM_LIT:1>)<EOL><DEDENT>self._pen.SetStyle(self._style)<EOL>self.gfx_ctx.SetPen(self._pen)<EOL>self.unselect()<EOL>


DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>if len(color) == <NUM_LIT:3>:<EOL><INDENT>r, g, b = color<EOL>r *= <NUM_LIT:255><EOL>g *= <NUM_LIT:255><EOL>b *= <NUM_LIT:255><EOL>return wx.Colour(red=int(r), green=int(g), blue=int(b))<EOL><DEDENT>else:<EOL><INDENT>r, g, b, a = color<EOL>r *= <NUM_LIT:255><EOL>g *= <NUM_LIT:255><EOL>b *= <NUM_LIT:255><EOL>a *= <NUM_LIT:255><EOL>return wx.Colour(red=int(r), green=int(g), blue=int(b), alpha=int(a))<EOL><DEDENT>


FigureCanvasBase.__init__(self, figure)<EOL>l,b,w,h = figure.bbox.bounds<EOL>w = int(math.ceil(w))<EOL>h = int(math.ceil(h))<EOL>wx.Panel.__init__(self, parent, id, size=wx.Size(w, h))<EOL>def do_nothing(*args, **kwargs):<EOL><INDENT>warnings.warn('<STR_LIT>'%backend_version)<EOL>pass<EOL><DEDENT>try:<EOL><INDENT>getattr(self, '<STR_LIT>')<EOL><DEDENT>except AttributeError:<EOL><INDENT>self.SetInitialSize = getattr(self, '<STR_LIT>', do_nothing)<EOL><DEDENT>if not hasattr(self,'<STR_LIT>'):<EOL><INDENT>self.IsShownOnScreen = getattr(self, '<STR_LIT>', lambda *args: True)<EOL><DEDENT>self.bitmap =wx.EmptyBitmap(w, h)<EOL>DEBUG_MSG("<STR_LIT>" % (w,h), <NUM_LIT:2>, self)<EOL>self._isDrawn = False<EOL>bind(self, wx.EVT_SIZE, self._onSize)<EOL>bind(self, wx.EVT_PAINT, self._onPaint)<EOL>bind(self, wx.EVT_ERASE_BACKGROUND, self._onEraseBackground)<EOL>bind(self, wx.EVT_KEY_DOWN, self._onKeyDown)<EOL>bind(self, wx.EVT_KEY_UP, self._onKeyUp)<EOL>bind(self, wx.EVT_RIGHT_DOWN, self._onRightButtonDown)<EOL>bind(self, wx.EVT_RIGHT_DCLICK, self._onRightButtonDown)<EOL>bind(self, wx.EVT_RIGHT_UP, self._onRightButtonUp)<EOL>bind(self, wx.EVT_MOUSEWHEEL, self._onMouseWheel)<EOL>bind(self, wx.EVT_LEFT_DOWN, self._onLeftButtonDown)<EOL>bind(self, wx.EVT_LEFT_DCLICK, self._onLeftButtonDown)<EOL>bind(self, wx.EVT_LEFT_UP, self._onLeftButtonUp)<EOL>bind(self, wx.EVT_MOTION, self._onMotion)<EOL>bind(self, wx.EVT_LEAVE_WINDOW, self._onLeave)<EOL>bind(self, wx.EVT_ENTER_WINDOW, self._onEnter)<EOL>bind(self, wx.EVT_IDLE, self._onIdle)<EOL>self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)<EOL>self.macros = {} <EOL>self.Printer_Init()<EOL>

Initialise a FigureWx instance.

- Initialise the FigureCanvasBase and wxPanel parents.
- Set event handlers for:
  EVT_SIZE  (Resize event)
  EVT_PAINT (Paint event)


bmp_obj = wx.BitmapDataObject()<EOL>bmp_obj.SetBitmap(self.bitmap)<EOL>wx.TheClipboard.Open()<EOL>wx.TheClipboard.SetData(bmp_obj)<EOL>wx.TheClipboard.Close()<EOL>

copy bitmap of canvas to system clipboard


initialize printer settings using wx methods


dmsg = """<STR_LIT>"""<EOL>dlg = wx.Dialog(self, -<NUM_LIT:1>, '<STR_LIT>' , (-<NUM_LIT:1>,-<NUM_LIT:1>))<EOL>df = dlg.GetFont()<EOL>df.SetWeight(wx.NORMAL)<EOL>df.SetPointSize(<NUM_LIT:11>)<EOL>dlg.SetFont(df)<EOL>x_wid = wx.TextCtrl(dlg,-<NUM_LIT:1>,value="<STR_LIT>" % self.printer_width, size=(<NUM_LIT>,-<NUM_LIT:1>))<EOL>x_mrg = wx.TextCtrl(dlg,-<NUM_LIT:1>,value="<STR_LIT>" % self.printer_margin,size=(<NUM_LIT>,-<NUM_LIT:1>))<EOL>sizerAll = wx.BoxSizer(wx.VERTICAL)<EOL>sizerAll.Add(wx.StaticText(dlg,-<NUM_LIT:1>,dmsg),<EOL><NUM_LIT:0>, wx.ALL | wx.EXPAND, <NUM_LIT:5>)<EOL>sizer = wx.FlexGridSizer(<NUM_LIT:0>,<NUM_LIT:3>)<EOL>sizerAll.Add(sizer, <NUM_LIT:0>, wx.ALL | wx.EXPAND, <NUM_LIT:5>)<EOL>sizer.Add(wx.StaticText(dlg,-<NUM_LIT:1>,'<STR_LIT>'),<EOL><NUM_LIT:1>, wx.ALIGN_LEFT|wx.ALL, <NUM_LIT:2>)<EOL>sizer.Add(x_wid,<EOL><NUM_LIT:1>, wx.ALIGN_LEFT|wx.ALL, <NUM_LIT:2>)<EOL>sizer.Add(wx.StaticText(dlg,-<NUM_LIT:1>,'<STR_LIT>'),<EOL><NUM_LIT:1>, wx.ALIGN_LEFT|wx.ALL, <NUM_LIT:2>)<EOL>sizer.Add(wx.StaticText(dlg,-<NUM_LIT:1>,'<STR_LIT>'),<EOL><NUM_LIT:1>, wx.ALIGN_LEFT|wx.ALL, <NUM_LIT:2>)<EOL>sizer.Add(x_mrg,<EOL><NUM_LIT:1>, wx.ALIGN_LEFT|wx.ALL, <NUM_LIT:2>)<EOL>sizer.Add(wx.StaticText(dlg,-<NUM_LIT:1>,'<STR_LIT>'),<EOL><NUM_LIT:1>, wx.ALIGN_LEFT|wx.ALL, <NUM_LIT:2>)<EOL>btn = wx.Button(dlg,wx.ID_OK, "<STR_LIT>")<EOL>btn.SetDefault()<EOL>sizer.Add(btn, <NUM_LIT:1>, wx.ALIGN_LEFT, <NUM_LIT:5>)<EOL>btn = wx.Button(dlg,wx.ID_CANCEL, "<STR_LIT>")<EOL>sizer.Add(btn, <NUM_LIT:1>, wx.ALIGN_LEFT, <NUM_LIT:5>)<EOL>dlg.SetSizer(sizerAll)<EOL>dlg.SetAutoLayout(True)<EOL>sizerAll.Fit(dlg)<EOL>if dlg.ShowModal() == wx.ID_OK:<EOL><INDENT>try:<EOL><INDENT>self.printer_width  = float(x_wid.GetValue())<EOL>self.printer_margin = float(x_mrg.GetValue())<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if ((self.printer_width + self.printer_margin) > <NUM_LIT>):<EOL><INDENT>self.printerData.SetOrientation(wx.LANDSCAPE)<EOL><DEDENT>else:<EOL><INDENT>self.printerData.SetOrientation(wx.PORTRAIT)<EOL><DEDENT>dlg.Destroy()<EOL>return<EOL>

set up figure for printing.  The standard wx Printer
        Setup Dialog seems to die easily. Therefore, this setup
        simply asks for image width and margin for printing.


if hasattr(self, '<STR_LIT>'):<EOL><INDENT>data = wx.PageSetupDialogData()<EOL>data.SetPrintData(self.printerData)<EOL><DEDENT>else:<EOL><INDENT>data = wx.PageSetupDialogData()<EOL><DEDENT>data.SetMarginTopLeft( (<NUM_LIT:15>, <NUM_LIT:15>) )<EOL>data.SetMarginBottomRight( (<NUM_LIT:15>, <NUM_LIT:15>) )<EOL>dlg = wx.PageSetupDialog(self, data)<EOL>if dlg.ShowModal() == wx.ID_OK:<EOL><INDENT>data = dlg.GetPageSetupData()<EOL>tl = data.GetMarginTopLeft()<EOL>br = data.GetMarginBottomRight()<EOL><DEDENT>self.printerData = wx.PrintData(data.GetPrintData())<EOL>dlg.Destroy()<EOL>

set up figure for printing.  Using the standard wx Printer
        Setup Dialog.


po1  = PrintoutWx(self, width=self.printer_width,<EOL>margin=self.printer_margin)<EOL>po2  = PrintoutWx(self, width=self.printer_width,<EOL>margin=self.printer_margin)<EOL>self.preview = wx.PrintPreview(po1,po2,self.printerData)<EOL>if not self.preview.Ok():  print("<STR_LIT>")<EOL>self.preview.SetZoom(<NUM_LIT:50>)<EOL>frameInst= self<EOL>while not isinstance(frameInst, wx.Frame):<EOL><INDENT>frameInst= frameInst.GetParent()<EOL><DEDENT>frame = wx.PreviewFrame(self.preview, frameInst, "<STR_LIT>")<EOL>frame.Initialize()<EOL>frame.SetPosition(self.GetPosition())<EOL>frame.SetSize((<NUM_LIT>,<NUM_LIT>))<EOL>frame.Centre(wx.BOTH)<EOL>frame.Show(True)<EOL>self.gui_repaint()<EOL>

generate Print Preview with wx Print mechanism


pdd = wx.PrintDialogData()<EOL>pdd.SetPrintData(self.printerData)<EOL>pdd.SetToPage(<NUM_LIT:1>)<EOL>printer  = wx.Printer(pdd)<EOL>printout  = PrintoutWx(self, width=int(self.printer_width),<EOL>margin=int(self.printer_margin))<EOL>print_ok = printer.Print(self, printout, True)<EOL>if wx.VERSION_STRING >= '<STR_LIT>':<EOL><INDENT>if not print_ok and not printer.GetLastError() == wx.PRINTER_CANCELLED:<EOL><INDENT>wx.MessageBox("""<STR_LIT>""",<EOL>"<STR_LIT>", wx.OK)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not print_ok:<EOL><INDENT>wx.MessageBox("""<STR_LIT>""",<EOL>"<STR_LIT>", wx.OK)<EOL><DEDENT><DEDENT>printout.Destroy()<EOL>self.gui_repaint()<EOL>


DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>self._isDrawn = False  <EOL>if hasattr(self,'<STR_LIT>'):<EOL><INDENT>self._idletimer.Restart(IDLE_DELAY)<EOL><DEDENT>else:<EOL><INDENT>self._idletimer = wx.FutureCall(IDLE_DELAY,self._onDrawIdle)<EOL><DEDENT>


DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>self.renderer = RendererWx(self.bitmap, self.figure.dpi)<EOL>self.figure.draw(self.renderer)<EOL>self._isDrawn = True<EOL>self.gui_repaint(drawDC=drawDC)<EOL>

Render the figure using RendererWx instance renderer, or using a
previously defined renderer if none is specified.


if hasattr(self, '<STR_LIT>'):<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>id = wx.NewId()<EOL>timer = wx.Timer(self, id=id)<EOL>if timeout > <NUM_LIT:0>:<EOL><INDENT>timer.Start(timeout*<NUM_LIT:1000>, oneShot=True)<EOL>bind(self, wx.EVT_TIMER, self.stop_event_loop, id=id)<EOL><DEDENT>self._event_loop = wx.EventLoop()<EOL>self._event_loop.Run()<EOL>timer.Stop()<EOL>

Start an event loop.  This is used to start a blocking event
loop so that interactive functions, such as ginput and
waitforbuttonpress, can wait for events.  This should not be
confused with the main GUI event loop, which is always running
and has nothing to do with this.

Call signature::

start_event_loop(self,timeout=0)

This call blocks until a callback function triggers
stop_event_loop() or *timeout* is reached.  If *timeout* is
<=0, never timeout.

Raises RuntimeError if event loop is already running.


if hasattr(self,'<STR_LIT>'):<EOL><INDENT>if self._event_loop.IsRunning():<EOL><INDENT>self._event_loop.Exit()<EOL><DEDENT>del self._event_loop<EOL><DEDENT>

Stop an event loop.  This is used to stop a blocking event
loop so that interactive functions, such as ginput and
waitforbuttonpress, can wait for events.

Call signature::

stop_event_loop_default(self)


default_filetype = self.get_default_filetype()<EOL>filetypes = self.get_supported_filetypes_grouped()<EOL>sorted_filetypes = list(filetypes.items())<EOL>sorted_filetypes.sort()<EOL>wildcards = []<EOL>extensions = []<EOL>filter_index = <NUM_LIT:0><EOL>for i, (name, exts) in enumerate(sorted_filetypes):<EOL><INDENT>ext_list = '<STR_LIT:;>'.join(['<STR_LIT>' % ext for ext in exts])<EOL>extensions.append(exts[<NUM_LIT:0>])<EOL>wildcard = '<STR_LIT>' % (name, ext_list, ext_list)<EOL>if default_filetype in exts:<EOL><INDENT>filter_index = i<EOL><DEDENT>wildcards.append(wildcard)<EOL><DEDENT>wildcards = '<STR_LIT:|>'.join(wildcards)<EOL>return wildcards, extensions, filter_index<EOL>

return the wildcard string for the filesave dialog


DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>if self.IsShownOnScreen():<EOL><INDENT>if drawDC is None:<EOL><INDENT>drawDC=wx.ClientDC(self)<EOL><DEDENT>drawDC.BeginDrawing()<EOL>drawDC.DrawBitmap(self.bitmap, <NUM_LIT:0>, <NUM_LIT:0>)<EOL>drawDC.EndDrawing()<EOL><DEDENT>else:<EOL><INDENT>pass<EOL><DEDENT>

Performs update of the displayed image on the GUI canvas, using the
supplied device context.  If drawDC is None, a ClientDC will be used to
redraw the image.