From: <lee...@us...> - 2009-07-14 19:22:01
|
Revision: 7259 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7259&view=rev Author: leejjoon Date: 2009-07-14 19:21:47 +0000 (Tue, 14 Jul 2009) Log Message: ----------- Fix a few bugs in ConnectionStyle classes. Add ConnectionPatch. Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/patches.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-07-12 03:20:53 UTC (rev 7258) +++ trunk/matplotlib/CHANGELOG 2009-07-14 19:21:47 UTC (rev 7259) @@ -1,3 +1,6 @@ +2009-07-14 Fix a few bugs in ConnectionStyle algorithms. Add + ConnectionPatch class. -JJL + 2009-07-11 Added a fillstyle Line2D property for half filled markers -- see examples/pylab_examples/fillstyle_demo.py JDH Modified: trunk/matplotlib/lib/matplotlib/patches.py =================================================================== --- trunk/matplotlib/lib/matplotlib/patches.py 2009-07-12 03:20:53 UTC (rev 7258) +++ trunk/matplotlib/lib/matplotlib/patches.py 2009-07-14 19:21:47 UTC (rev 7259) @@ -1729,8 +1729,8 @@ """ def __init__(self, pad=0.3): - self.pad = pad - super(BoxStyle.RArrow, self).__init__() + #self.pad = pad + super(BoxStyle.RArrow, self).__init__(pad) def transmute(self, x0, y0, width, height, mutation_size): @@ -2466,7 +2466,7 @@ cosA, sinA = math.cos(self.angleA/180.*math.pi),\ math.sin(self.angleA/180.*math.pi), cosB, sinB = math.cos(self.angleB/180.*math.pi),\ - -math.sin(self.angleB/180.*math.pi), + math.sin(self.angleB/180.*math.pi), cx, cy = get_intersection(x1, y1, cosA, sinA, x2, y2, cosB, sinB) @@ -2478,9 +2478,15 @@ vertices.append((cx, cy)) codes.append(Path.LINETO) else: - vertices.extend([(cx - self.rad * cosA, cy - self.rad * sinA), + dx1, dy1 = x1-cx, y1-cy + d1 = (dx1**2 + dy1**2)**.5 + f1 = self.rad/d1 + dx2, dy2 = x2-cx, y2-cy + d2 = (dx2**2 + dy2**2)**.5 + f2 = self.rad/d2 + vertices.extend([(cx + dx1*f1, cy + dy1*f1), (cx, cy), - (cx + self.rad * cosB, cy + self.rad * sinB)]) + (cx + dx2*f2, cy + dy2*f2)]) codes.extend([Path.LINETO, Path.CURVE3, Path.CURVE3]) vertices.append((x2, y2)) @@ -2623,7 +2629,8 @@ #angle = self.angle % 180. #if angle < 0. or angle > 180.: # angle - theta0 = (self.angle%180.)/180.*math.pi + #theta0 = (self.angle%180.)/180.*math.pi + theta0 = self.angle/180.*math.pi #theta0 = (((self.angle+90)%180.) - 90.)/180.*math.pi dtheta = theta1 - theta0 dl = dd*math.sin(dtheta) @@ -3744,3 +3751,302 @@ gc.restore() renderer.close_group('patch') + + +class ConnectionPatch(FancyArrowPatch): + """ + A :class:`~matplotlib.patches.ConnectionPatch` class is to make + connecting lines between two points (possibly in different axes). + """ + def __str__(self): + return "ConnectionPatch((%g,%g),(%g,%g))" % \ + (self.xy1[0],self.xy1[1],self.xy2[0],self.xy2[1]) + + def __init__(self, xyA, xyB, coordsA, coordsB=None, + axesA=None, axesB=None, + arrowstyle="-", + arrow_transmuter=None, + connectionstyle="arc3", + connector=None, + patchA=None, + patchB=None, + shrinkA=0., + shrinkB=0., + mutation_scale=10., + mutation_aspect=None, + clip_on=False, + **kwargs): + """ + Connect point *xyA* in *coordsA* with point *xyB* in *coordsB* + + + Valid keys are + + + =============== ====================================================== + Key Description + =============== ====================================================== + arrowstyle the arrow style + connectionstyle the connection style + relpos default is (0.5, 0.5) + patchA default is bounding box of the text + patchB default is None + shrinkA default is 2 points + shrinkB default is 2 points + mutation_scale default is text size (in points) + mutation_aspect default is 1. + ? any key for :class:`matplotlib.patches.PathPatch` + =============== ====================================================== + + + *coordsA* and *coordsB* are strings that indicate the + coordinates of *xyA* and *xyB*. + + ================= =================================================== + Property Description + ================= =================================================== + 'figure points' points from the lower left corner of the figure + 'figure pixels' pixels from the lower left corner of the figure + 'figure fraction' 0,0 is lower left of figure and 1,1 is upper, right + 'axes points' points from lower left corner of axes + 'axes pixels' pixels from lower left corner of axes + 'axes fraction' 0,1 is lower left of axes and 1,1 is upper right + 'data' use the coordinate system of the object being + annotated (default) + 'offset points' Specify an offset (in points) from the *xy* value + + 'polar' you can specify *theta*, *r* for the annotation, + even in cartesian plots. Note that if you + are using a polar axes, you do not need + to specify polar for the coordinate + system since that is the native "data" coordinate + system. + ================= =================================================== + + """ + if coordsB is None: + coordsB = coordsA + # we'll draw ourself after the artist we annotate by default + self.xy1 = xyA + self.xy2 = xyB + self.coords1 = coordsA + self.coords2 = coordsB + + self.axesA = axesA + self.axesB = axesB + + FancyArrowPatch.__init__(self, + posA=(0,0), posB=(1,1), + arrowstyle=arrowstyle, + arrow_transmuter=arrow_transmuter, + connectionstyle=connectionstyle, + connector=connector, + patchA=patchA, + patchB=patchB, + shrinkA=shrinkA, + shrinkB=shrinkB, + mutation_scale=mutation_scale, + mutation_aspect=mutation_aspect, + clip_on=clip_on, + **kwargs) + + # if True, draw annotation only if self.xy is inside the axes + self._annotation_clip = None + + __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd + + + def _get_xy(self, x, y, s, axes=None): + """ + caculate the pixel position of given point + """ + + if axes is None: + axes = self.axes + + if s=='data': + trans = axes.transData + x = float(self.convert_xunits(x)) + y = float(self.convert_yunits(y)) + return trans.transform_point((x, y)) + elif s=='offset points': + # convert the data point + dx, dy = self.xy + + # prevent recursion + if self.xycoords == 'offset points': + return self._get_xy(dx, dy, 'data') + + dx, dy = self._get_xy(dx, dy, self.xycoords) + + # convert the offset + dpi = self.figure.get_dpi() + x *= dpi/72. + y *= dpi/72. + + # add the offset to the data point + x += dx + y += dy + + return x, y + elif s=='polar': + theta, r = x, y + x = r*np.cos(theta) + y = r*np.sin(theta) + trans = axes.transData + return trans.transform_point((x,y)) + elif s=='figure points': + #points from the lower left corner of the figure + dpi = self.figure.dpi + l,b,w,h = self.figure.bbox.bounds + r = l+w + t = b+h + + x *= dpi/72. + y *= dpi/72. + if x<0: + x = r + x + if y<0: + y = t + y + return x,y + elif s=='figure pixels': + #pixels from the lower left corner of the figure + l,b,w,h = self.figure.bbox.bounds + r = l+w + t = b+h + if x<0: + x = r + x + if y<0: + y = t + y + return x, y + elif s=='figure fraction': + #(0,0) is lower left, (1,1) is upper right of figure + trans = self.figure.transFigure + return trans.transform_point((x,y)) + elif s=='axes points': + #points from the lower left corner of the axes + dpi = self.figure.dpi + l,b,w,h = axes.bbox.bounds + r = l+w + t = b+h + if x<0: + x = r + x*dpi/72. + else: + x = l + x*dpi/72. + if y<0: + y = t + y*dpi/72. + else: + y = b + y*dpi/72. + return x, y + elif s=='axes pixels': + #pixels from the lower left corner of the axes + + l,b,w,h = axes.bbox.bounds + r = l+w + t = b+h + if x<0: + x = r + x + else: + x = l + x + if y<0: + y = t + y + else: + y = b + y + return x, y + elif s=='axes fraction': + #(0,0) is lower left, (1,1) is upper right of axes + trans = axes.transAxes + return trans.transform_point((x, y)) + + def set_annotation_clip(self, b): + """ + set *annotation_clip* attribute. + + * True : the annotation will only be drawn when self.xy is inside the axes. + * False : the annotation will always be drawn regardless of its position. + * None : the self.xy will be checked only if *xycoords* is "data" + """ + self._annotation_clip = b + + def get_annotation_clip(self): + """ + Return *annotation_clip* attribute. + See :meth:`set_annotation_clip` for the meaning of return values. + """ + return self._annotation_clip + + + def get_path_in_displaycoord(self): + """ + Return the mutated path of the arrow in the display coord + """ + + x, y = self.xy1 + posA = self._get_xy(x, y, self.coords1, self.axesA) + + x, y = self.xy2 + posB = self._get_xy(x, y, self.coords1, self.axesB) + + _path = self.get_connectionstyle()(posA, posB, + patchA=self.patchA, + patchB=self.patchB, + shrinkA=self.shrinkA, + shrinkB=self.shrinkB + ) + + + + _path, fillable = self.get_arrowstyle()(_path, + self.get_mutation_scale(), + self.get_linewidth(), + self.get_mutation_aspect() + ) + + return _path, fillable + + + + def _check_xy(self, renderer): + """ + check if the annotation need to + be drawn. + """ + + b = self.get_annotation_clip() + + + if b or (b is None and self.coords1 == "data"): + x, y = self.xy1 + xy_pixel = self._get_xy(x, y, self.coords1, self.axesA) + if not self.axes.contains_point(xy_pixel): + return False + + if b or (b is None and self.coords2 == "data"): + x, y = self.xy2 + xy_pixel = self._get_xy(x, y, self.coords2, self.axesB) + if self.axesB is None: + axes = self.axes + else: + axes = self.axesB + if not axes.contains_point(xy_pixel): + return False + + return True + + + def draw(self, renderer): + """ + Draw. + """ + + if renderer is not None: + self._renderer = renderer + if not self.get_visible(): return + + if not self._check_xy(renderer): + return + + FancyArrowPatch.draw(self, renderer) + + + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lee...@us...> - 2009-07-14 21:19:01
|
Revision: 7261 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7261&view=rev Author: leejjoon Date: 2009-07-14 21:18:58 +0000 (Tue, 14 Jul 2009) Log Message: ----------- axes_grid : minor improvements in anchored_artists and inset_locator. Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/mpl_toolkits/axes_grid/__init__.py trunk/matplotlib/lib/mpl_toolkits/axes_grid/anchored_artists.py trunk/matplotlib/lib/mpl_toolkits/axes_grid/axes_grid.py trunk/matplotlib/lib/mpl_toolkits/axes_grid/inset_locator.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-07-14 21:11:53 UTC (rev 7260) +++ trunk/matplotlib/CHANGELOG 2009-07-14 21:18:58 UTC (rev 7261) @@ -1,3 +1,6 @@ +2009-07-14 axes_grid : minor improvements in anchored_artists and + inset_locator. -JJL + 2009-07-14 Fix a few bugs in ConnectionStyle algorithms. Add ConnectionPatch class. -JJL Modified: trunk/matplotlib/lib/mpl_toolkits/axes_grid/__init__.py =================================================================== --- trunk/matplotlib/lib/mpl_toolkits/axes_grid/__init__.py 2009-07-14 21:11:53 UTC (rev 7260) +++ trunk/matplotlib/lib/mpl_toolkits/axes_grid/__init__.py 2009-07-14 21:18:58 UTC (rev 7261) @@ -1,10 +1,6 @@ -""" -AxesGrid -""" - import axes_size as Size from axes_divider import Divider, SubplotDivider, LocatableAxes, \ make_axes_locatable -from axes_grid import AxesGrid +from axes_grid import Grid, ImageGrid, AxesGrid #from axes_divider import make_axes_locatable Modified: trunk/matplotlib/lib/mpl_toolkits/axes_grid/anchored_artists.py =================================================================== --- trunk/matplotlib/lib/mpl_toolkits/axes_grid/anchored_artists.py 2009-07-14 21:11:53 UTC (rev 7260) +++ trunk/matplotlib/lib/mpl_toolkits/axes_grid/anchored_artists.py 2009-07-14 21:18:58 UTC (rev 7261) @@ -21,34 +21,37 @@ **kwargs) -class AnchoredSizeBar(AnchoredOffsetbox): - def __init__(self, transform, size, label, loc, - pad=0.1, borderpad=0.1, sep=2, prop=None, frameon=True): - """ - Draw a horizontal bar with the size in data coordinate of the give axes. - A label will be drawn underneath (center-alinged). - pad, borderpad in fraction of the legend font size (or prop) - sep in points. - """ - self.size_bar = AuxTransformBox(transform) - self.size_bar.add_artist(Rectangle((0,0), size, 0, fc="none")) +class AnchoredDrawingArea(AnchoredOffsetbox): + def __init__(self, width, height, xdescent, ydescent, + loc, pad=0.4, borderpad=0.5, prop=None, frameon=True, + **kwargs): - self.txt_label = TextArea(label, minimumdescent=False) + self.da = DrawingArea(width, height, xdescent, ydescent, clip=True) + self.drawing_area = self.da + + super(AnchoredDrawingArea, self).__init__(loc, pad=pad, borderpad=borderpad, + child=self.da, + prop=None, + frameon=frameon, + **kwargs) - self._box = VPacker(children=[self.size_bar, self.txt_label], - align="center", - pad=0, sep=sep) +class AnchoredAuxTransformBox(AnchoredOffsetbox): + def __init__(self, transform, loc, + pad=0.4, borderpad=0.5, prop=None, frameon=True, **kwargs): + self.drawing_area = AuxTransformBox(transform) + AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad, - child=self._box, + child=self.drawing_area, prop=prop, - frameon=frameon) + frameon=frameon, + **kwargs) class AnchoredEllipse(AnchoredOffsetbox): def __init__(self, transform, width, height, angle, loc, - pad=0.1, borderpad=0.1, prop=None, frameon=True): + pad=0.1, borderpad=0.1, prop=None, frameon=True, **kwargs): """ Draw an ellipse the size in data coordinate of the give axes. @@ -61,20 +64,32 @@ AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad, child=self._box, prop=prop, - frameon=frameon) + frameon=frameon, **kwargs) -class AnchoredDrawingArea(AnchoredOffsetbox): - def __init__(self, width, height, xdescent, ydescent, - loc, pad=0.4, borderpad=0.5, prop=None, frameon=True): +class AnchoredSizeBar(AnchoredOffsetbox): + def __init__(self, transform, size, label, loc, + pad=0.1, borderpad=0.1, sep=2, prop=None, frameon=True, + **kwargs): + """ + Draw a horizontal bar with the size in data coordinate of the give axes. + A label will be drawn underneath (center-alinged). - self.da = DrawingArea(width, height, xdescent, ydescent, clip=True) + pad, borderpad in fraction of the legend font size (or prop) + sep in points. + """ + self.size_bar = AuxTransformBox(transform) + self.size_bar.add_artist(Rectangle((0,0), size, 0, fc="none")) - super(AnchoredDrawingArea, self).__init__(loc, pad=pad, borderpad=borderpad, - child=self.da, - prop=None, - frameon=frameon) + self.txt_label = TextArea(label, minimumdescent=False) + self._box = VPacker(children=[self.size_bar, self.txt_label], + align="center", + pad=0, sep=sep) + AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad, + child=self._box, + prop=prop, + frameon=frameon, **kwargs) Modified: trunk/matplotlib/lib/mpl_toolkits/axes_grid/axes_grid.py =================================================================== --- trunk/matplotlib/lib/mpl_toolkits/axes_grid/axes_grid.py 2009-07-14 21:11:53 UTC (rev 7260) +++ trunk/matplotlib/lib/mpl_toolkits/axes_grid/axes_grid.py 2009-07-14 21:18:58 UTC (rev 7261) @@ -168,7 +168,7 @@ axes_class=None, ): """ - Build an :class:`AxesGrid` instance with a grid nrows*ncols + Build an :class:`Grid` instance with a grid nrows*ncols :class:`~matplotlib.axes.Axes` in :class:`~matplotlib.figure.Figure` *fig* with *rect=[left, bottom, width, height]* (in @@ -184,7 +184,8 @@ axes_pad 0.02 float| pad betweein axes given in inches add_all True [ True | False ] share_all False [ True | False ] - aspect True [ True | False ] + share_x True [ True | False ] + share_y True [ True | False ] label_mode "L" [ "L" | "1" | "all" ] axes_class None a type object which must be a subclass of :class:`~matplotlib.axes.Axes` @@ -406,14 +407,14 @@ _tick_only(ax, bottom_on=False, left_on=False) -class AxesGrid(Grid): +class ImageGrid(Grid): """ A class that creates a grid of Axes. In matplotlib, the axes location (and size) is specified in the normalized figure coordinates. This may not be ideal for images that needs to be displayed with a given aspect ratio. For example, displaying images of a same size with some fixed padding between them cannot - be easily done in matplotlib. AxesGrid is used in such case. + be easily done in matplotlib. ImageGrid is used in such case. """ def __init__(self, fig, @@ -433,7 +434,7 @@ axes_class=None, ): """ - Build an :class:`AxesGrid` instance with a grid nrows*ncols + Build an :class:`ImageGrid` instance with a grid nrows*ncols :class:`~matplotlib.axes.Axes` in :class:`~matplotlib.figure.Figure` *fig* with *rect=[left, bottom, width, height]* (in @@ -661,6 +662,7 @@ self._divider.set_vertical(v) +AxesGrid = ImageGrid @@ -689,7 +691,7 @@ F.subplots_adjust(left=0.05, right=0.98) - grid = AxesGrid(F, 131, # similar to subplot(111) + grid = ImageGrid(F, 131, # similar to subplot(111) nrows_ncols = (2, 2), direction="row", axes_pad = 0.05, @@ -708,7 +710,7 @@ plt.ion() - grid = AxesGrid(F, 132, # similar to subplot(111) + grid = ImageGrid(F, 132, # similar to subplot(111) nrows_ncols = (2, 2), direction="row", axes_pad = 0.0, @@ -733,7 +735,7 @@ - grid = AxesGrid(F, 133, # similar to subplot(122) + grid = ImageGrid(F, 133, # similar to subplot(122) nrows_ncols = (2, 2), direction="row", axes_pad = 0.1, Modified: trunk/matplotlib/lib/mpl_toolkits/axes_grid/inset_locator.py =================================================================== --- trunk/matplotlib/lib/mpl_toolkits/axes_grid/inset_locator.py 2009-07-14 21:11:53 UTC (rev 7260) +++ trunk/matplotlib/lib/mpl_toolkits/axes_grid/inset_locator.py 2009-07-14 21:18:58 UTC (rev 7261) @@ -239,6 +239,23 @@ self.loc1, self.loc2) +class BboxConnectorPatch(BboxConnector): + + def __init__(self, bbox1, bbox2, loc1a, loc2a, loc1b, loc2b, **kwargs): + if "transform" in kwargs: + raise ValueError("transform should not be set") + BboxConnector.__init__(self, bbox1, bbox2, loc1a, loc2a, **kwargs) + self.loc1b = loc1b + self.loc2b = loc2b + + def get_path(self): + path1 = self.connect_bbox(self.bbox1, self.bbox2, self.loc1, self.loc2) + path2 = self.connect_bbox(self.bbox2, self.bbox1, self.loc2b, self.loc1b) + path_merged = list(path1.vertices) + list (path2.vertices) + [path1.vertices[0]] + return Path(path_merged) + + + def _add_inset_axes(parent_axes, inset_axes): parent_axes.figure.add_axes(inset_axes) inset_axes.set_navigate(False) @@ -285,7 +302,9 @@ inset_axes = axes_class(parent_axes.figure, parent_axes.get_position(), **axes_kwargs) - axes_locator = AnchoredZoomLocator(parent_axes, zoom=zoom, loc=loc) + axes_locator = AnchoredZoomLocator(parent_axes, zoom=zoom, loc=loc, + bbox_to_anchor=None, bbox_transform=None, + **kwargs) inset_axes.set_axes_locator(axes_locator) _add_inset_axes(parent_axes, inset_axes) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lee...@us...> - 2009-07-14 21:24:12
|
Revision: 7262 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7262&view=rev Author: leejjoon Date: 2009-07-14 21:24:07 +0000 (Tue, 14 Jul 2009) Log Message: ----------- initial submission of the annotation guide. Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/doc/users/plotting.rst Added Paths: ----------- trunk/matplotlib/doc/users/plotting/annotation.rst trunk/matplotlib/doc/users/plotting/examples/anchored_box01.py trunk/matplotlib/doc/users/plotting/examples/anchored_box02.py trunk/matplotlib/doc/users/plotting/examples/anchored_box03.py trunk/matplotlib/doc/users/plotting/examples/anchored_box04.py trunk/matplotlib/doc/users/plotting/examples/annotate_explain.py trunk/matplotlib/doc/users/plotting/examples/annotate_simple01.py trunk/matplotlib/doc/users/plotting/examples/annotate_simple02.py trunk/matplotlib/doc/users/plotting/examples/annotate_simple03.py trunk/matplotlib/doc/users/plotting/examples/annotate_simple04.py trunk/matplotlib/doc/users/plotting/examples/annotate_text_arrow.py trunk/matplotlib/doc/users/plotting/examples/axes_zoom_effect.py trunk/matplotlib/doc/users/plotting/examples/connect_simple01.py trunk/matplotlib/doc/users/plotting/examples/connectionstyle_demo.py trunk/matplotlib/doc/users/plotting/examples/custom_boxstyle01.py trunk/matplotlib/doc/users/plotting/examples/custom_boxstyle02.py trunk/matplotlib/doc/users/plotting/examples/simple_annotate01.py trunk/matplotlib/examples/pylab_examples/axes_zoom_effect.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-07-14 21:18:58 UTC (rev 7261) +++ trunk/matplotlib/CHANGELOG 2009-07-14 21:24:07 UTC (rev 7262) @@ -1,3 +1,5 @@ +2009-07-14 initial submission of the annotation guide. -JJL + 2009-07-14 axes_grid : minor improvements in anchored_artists and inset_locator. -JJL Added: trunk/matplotlib/doc/users/plotting/annotation.rst =================================================================== --- trunk/matplotlib/doc/users/plotting/annotation.rst (rev 0) +++ trunk/matplotlib/doc/users/plotting/annotation.rst 2009-07-14 21:24:07 UTC (rev 7262) @@ -0,0 +1,332 @@ +.. _plotting-guide-annotation: + +**************** +Annotating Axes +**************** + +Do not proceed unless you already have read +:func:`~matplotlib.pyplot.text` and :func:`~matplotlib.pyplot.annotate`! + + +Annotating with Text with Box +============================= + +Let's start with a simple example. + +.. plot:: users/plotting/examples/annotate_text_arrow.py + + +The :func:`~matplotlib.pyplot.text` function in the pyplot module (or +text method of the Axes class) takes bbox keyword argument, and when +given, a box around the text is drawn. :: + + bbox_props = dict(boxstyle="rarrow,pad=0.3", fc="cyan", ec="b", lw=2) + t = ax.text(0, 0, "Direction", ha="center", va="center", rotation=45, + size=15, + bbox=bbox_props) + + +The patch object associated with the text can be accessed by:: + + bb = t.get_bbox_patch() + +The return value is an instance of FancyBboxPatch and the patch +properties like facecolor, edgewidth, etc. can be accessed and +modified as usual. To change the shape of the box, use *set_boxstyle* +method. :: + + bb.set_boxstyle("rarrow", pad=0.6) + +The arguments are the name of the box style with its attributes as +keyword arguments. Currently, followign box styles are implemented. + + ========== ============== ========================== + Class Name Attrs + ========== ============== ========================== + LArrow ``larrow`` pad=0.3 + RArrow ``rarrow`` pad=0.3 + Round ``round`` pad=0.3,rounding_size=None + Round4 ``round4`` pad=0.3,rounding_size=None + Roundtooth ``roundtooth`` pad=0.3,tooth_size=None + Sawtooth ``sawtooth`` pad=0.3,tooth_size=None + Square ``square`` pad=0.3 + ========== ============== ========================== + +.. plot:: mpl_examples/pylab_examples/fancybox_demo2.py + + +Note that the attrubutes arguments can be specified within the style +name with separating comma (this form can be used as "boxstyle" value +of bbox argument when initializing the text instance) :: + + bb.set_boxstyle("rarrow,pad=0.6") + + + + +Annotating with Arrow +===================== + +The :func:`~matplotlib.pyplot.annotate` function in the pyplot module +(or annotate method of the Axes class) is used to draw an arrow +connecting two points on the plot. :: + + ax.annotate("Annotation", + xy=(x1, y1), xycoords='data', + xytext=(x2, y2), textcoords='offset points', + ) + +This annotates a point at ``xy`` in the given coordinate (``xycoords``) +with the text at ``xytext`` given in ``textcoords``. Often, the +annotated point is specified in the *data* coordinate and the annotating +text in *offset points*. +See :func:`~matplotlib.pyplot.annotate` for available coordinate systems. + +An arrow connecting two point (xy & xytext) can be optionally drawn by +specifying the ``arrowprops`` argument. To draw only an arrow, use +empty string as the first argument. :: + + ax.annotate("", + xy=(0.2, 0.2), xycoords='data', + xytext=(0.8, 0.8), textcoords='data', + arrowprops=dict(arrowstyle="->", + connectionstyle="arc3"), + ) + +.. plot:: users/plotting/examples/annotate_simple01.py + +The arrow drawing takes a few steps. + +1. a connecting path between two points are created. This is + controlled by ``connectionstyle`` key value. + +2. If patch object is given (*patchA* & *patchB*), the path is clipped to + avoid the patch. + +3. The path is further shrinked by given amount of pixels (*shirnkA* + & *shrinkB*) + +4. The path is transmuted to arrow patch, which is controlled by the + ``arrowstyle`` key value. + + +.. plot:: users/plotting/examples/annotate_explain.py + + +The creation of the connecting path between two points is controlled by +``connectionstyle`` key and follwing styles are available. + + ========== ============================================= + Name Attrs + ========== ============================================= + ``angle`` angleA=90,angleB=0,rad=0.0 + ``angle3`` angleA=90,angleB=0 + ``arc`` angleA=0,angleB=0,armA=None,armB=None,rad=0.0 + ``arc3`` rad=0.0 + ``bar`` armA=0.0,armB=0.0,fraction=0.3,angle=None + ========== ============================================= + +Note that "3" in ``angle3`` and ``arc3`` is meant to indicate that the +resulting path is a quadratic spline segment (three control +points). As will be discussed below, some arrow style option only can +be used when the connecting path is a quadratic spline. + +The behavior of each connection style is (limitedly) demonstrated in the +example below. (Warning : The behavior of the ``bar`` style is currently not +well defined, it may be changed in the future). + +.. plot:: users/plotting/examples/connectionstyle_demo.py + + +The connecting path (after clipping and shrinking) is then mutated to +an arrow patch, according to the given ``arrowstyle``. + + ========== ============================================= + Name Attrs + ========== ============================================= + ``-`` None + ``->`` head_length=0.4,head_width=0.2 + ``-[`` widthB=1.0,lengthB=0.2,angleB=None + ``-|>`` head_length=0.4,head_width=0.2 + ``<-`` head_length=0.4,head_width=0.2 + ``<->`` head_length=0.4,head_width=0.2 + ``<|-`` head_length=0.4,head_width=0.2 + ``<|-|>`` head_length=0.4,head_width=0.2 + ``fancy`` head_length=0.4,head_width=0.4,tail_width=0.4 + ``simple`` head_length=0.5,head_width=0.5,tail_width=0.2 + ``wedge`` tail_width=0.3,shrink_factor=0.5 + ========== ============================================= + +.. plot:: mpl_examples/pylab_examples/fancyarrow_demo.py + +Some arrowstyles only work with connection style that generates a +quadratic-spline segment. They are ``fancy``, ``simple``, and ``wedge``. +For these arrow styles, you must use "angle3" or "arc3" connection +style. + +If the annotation string is given, the patchA is set to the bbox patch +of the text by default. + +.. plot:: users/plotting/examples/annotate_simple02.py + +As in the text command, a box around the text can be drawn using +the ``bbox`` argument. + +.. plot:: users/plotting/examples/annotate_simple03.py + +By default, the starting point is set to the center of the text +extent. This can be adjusted with ``relpos`` key value. The values +are normalized to the extent of the text. For example, (0,0) means +lower-left corner and (1,1) means top-right. + +.. plot:: users/plotting/examples/annotate_simple04.py + + +Using ConnectorPatch +==================== + +The ConnectorPatch is like an annotation without a text. While the +annotate function is recommended in most of situation, the +ConnectorPatch is useful when you want to connect points in different +axes. :: + + from matplotlib.patches import ConnectionPatch + xy = (0.2, 0.2) + con = ConnectionPatch(xyA=xy, xyB=xy, coordsA="data", coordsB="data", + axesA=ax1, axesB=ax2) + ax2.add_artist(con) + +The above code connects point xy in data coordinate of ``ax1`` to +point xy int data coordiante of ``ax2``. Here is a simple example. + +.. plot:: users/plotting/examples/connect_simple01.py + + +While the ConnectorPatch instance can be added to any axes, but you +may want it to be added to the axes in the latter (?) of the axes +drawing order to prevent overlap (?) by other axes. + + +Placing Artist at the anchored location of the Axes +=================================================== + +There are class of artist that can be placed at the anchored location +of the Axes. A common example is the legend. This type of artists can +be created by using the OffsetBox class. A few predefined classes are +available in ``mpl_toolkits.axes_grid.anchored_artists``. :: + + from mpl_toolkits.axes_grid.anchored_artists import AnchoredText + at = AnchoredText("Figure 1a", + prop=dict(size=8), frameon=True, + loc=2, + ) + at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") + ax.add_artist(at) + + +.. plot:: users/plotting/examples/anchored_box01.py + + +The *loc* keyword has same meaning as in the legend command. + +A simple application is when the size of the artist (or collection of +artists) is knwon in pixel size during the time of creation. For +example, If you want to draw a circle with fixed size of 20 pixel x 20 +pixel (radius = 10 pixel), you can utilize +``AnchoredDrawingArea``. The instance is created with a size of the +drawing area (in pixel). And user can add arbitrary artist to the +drawing area. Note that the extents of the artists that are added to +the drawing area has nothing to do with the placement of the drawing +area itself. The initial size only matters. :: + + from mpl_toolkits.axes_grid.anchored_artists import AnchoredDrawingArea + + ada = AnchoredDrawingArea(20, 20, 0, 0, + loc=1, pad=0., frameon=False) + p1 = Circle((10, 10), 10) + ada.drawing_area.add_artist(p1) + p2 = Circle((30, 10), 5, fc="r") + ada.drawing_area.add_artist(p2) + +The artists that are added to the drawing area should not have +transform set (they will be overridden) and the dimension of those +artists are interpreted as a pixel coordinate, i.e., the radius of the +circles in above example are 10 pixel and 5 pixel, respectively. + +.. plot:: users/plotting/examples/anchored_box02.py + +Sometimes, you want to your artists scale with data coordinate (or +other coordinate than canvas pixel). You can use +``AnchoredAuxTransformBox`` class. This is similar to +``AnchoredDrawingArea`` except that the extent of the artist is +determined during the drawing time respecting the specified transform. :: + + from mpl_toolkits.axes_grid.anchored_artists import AnchoredAuxTransformBox + + box = AnchoredAuxTransformBox(ax.transData, loc=2) + el = Ellipse((0,0), width=0.1, height=0.4, angle=30) # in data coordinates! + box.drawing_area.add_artist(el) + +The ellipse in the above example will have width and height +corresponds to 0.1 and 0.4 in data coordinate and will be +automatically scaled when the view limits of the axes change. + +.. plot:: users/plotting/examples/anchored_box03.py + +As in the legend, the bbox_to_anchor argument can be set. Using the +HPacker and VPacker, you can have an arrangement(?) of artist as in the +legend (as a matter of fact, this is how the legend is created). + +.. plot:: users/plotting/examples/anchored_box04.py + +Note that unlike the legend, the ``bbox_transform`` is set +to IdentityTransform by default. + +Advanced Topics +*************** + +Zoom effect between Axes +======================== + +mpl_toolkits.axes_grid.inset_locator defines some patch classs useful +for interconnect two axes. Understanding the code requires some +knowledge of how mpl's transform works. But, utilizing it will be +straight forward. + + +.. plot:: mpl_examples/pylab_examples/axes_zoom_effect.py + + +Define Custom BoxStyle +====================== + +You can use a custom box style. The value for the ``boxstyle`` can be a +callable object in following forms.:: + + def __call__(self, x0, y0, width, height, mutation_size, + aspect_ratio=1.): + """ + Given the location and size of the box, return the path of + the box around it. + + - *x0*, *y0*, *width*, *height* : location and size of the box + - *mutation_size* : a reference scale for the mutation. + - *aspect_ratio* : aspect-ration for the mutation. + """ + path = ... + return path + +Here is a complete example. + +.. plot:: users/plotting/examples/custom_boxstyle01.py + +However, it is recommended that you derive from the +matplotlib.patches.BoxStyle._Base as demonstrated below. + +.. plot:: users/plotting/examples/custom_boxstyle02.py + :include-source: + + +Similarly, you can define custom ConnectionStyle and Custome ArrowStyle. +See the source code of ``lib/matplotlib/patches.py`` and check +how each style class is defined. Added: trunk/matplotlib/doc/users/plotting/examples/anchored_box01.py =================================================================== --- trunk/matplotlib/doc/users/plotting/examples/anchored_box01.py (rev 0) +++ trunk/matplotlib/doc/users/plotting/examples/anchored_box01.py 2009-07-14 21:24:07 UTC (rev 7262) @@ -0,0 +1,14 @@ +import matplotlib.pyplot as plt +from mpl_toolkits.axes_grid.anchored_artists import AnchoredText + +fig=plt.figure(1, figsize=(3,3)) +ax = plt.subplot(111) + +at = AnchoredText("Figure 1a", + prop=dict(size=15), frameon=True, + loc=2, + ) +at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") +ax.add_artist(at) + +plt.show() Added: trunk/matplotlib/doc/users/plotting/examples/anchored_box02.py =================================================================== --- trunk/matplotlib/doc/users/plotting/examples/anchored_box02.py (rev 0) +++ trunk/matplotlib/doc/users/plotting/examples/anchored_box02.py 2009-07-14 21:24:07 UTC (rev 7262) @@ -0,0 +1,18 @@ +from matplotlib.patches import Circle +import matplotlib.pyplot as plt +from mpl_toolkits.axes_grid.anchored_artists import AnchoredDrawingArea + +fig=plt.figure(1, figsize=(3,3)) +ax = plt.subplot(111) + + +ada = AnchoredDrawingArea(40, 20, 0, 0, + loc=1, pad=0., frameon=False) +p1 = Circle((10, 10), 10) +ada.drawing_area.add_artist(p1) +p2 = Circle((30, 10), 5, fc="r") +ada.drawing_area.add_artist(p2) + +ax.add_artist(ada) + +plt.show() Added: trunk/matplotlib/doc/users/plotting/examples/anchored_box03.py =================================================================== --- trunk/matplotlib/doc/users/plotting/examples/anchored_box03.py (rev 0) +++ trunk/matplotlib/doc/users/plotting/examples/anchored_box03.py 2009-07-14 21:24:07 UTC (rev 7262) @@ -0,0 +1,14 @@ +from matplotlib.patches import Ellipse +import matplotlib.pyplot as plt +from mpl_toolkits.axes_grid.anchored_artists import AnchoredAuxTransformBox + +fig=plt.figure(1, figsize=(3,3)) +ax = plt.subplot(111) + +box = AnchoredAuxTransformBox(ax.transData, loc=2) +el = Ellipse((0,0), width=0.1, height=0.4, angle=30) # in data coordinates! +box.drawing_area.add_artist(el) + +ax.add_artist(box) + +plt.show() Added: trunk/matplotlib/doc/users/plotting/examples/anchored_box04.py =================================================================== --- trunk/matplotlib/doc/users/plotting/examples/anchored_box04.py (rev 0) +++ trunk/matplotlib/doc/users/plotting/examples/anchored_box04.py 2009-07-14 21:24:07 UTC (rev 7262) @@ -0,0 +1,35 @@ +from matplotlib.patches import Ellipse +import matplotlib.pyplot as plt +from matplotlib.offsetbox import AnchoredOffsetbox, TextArea, DrawingArea, HPacker + +fig=plt.figure(1, figsize=(3,3)) +ax = plt.subplot(111) + +box1 = TextArea(" Test : ", textprops=dict(color="k")) + +box2 = DrawingArea(60, 20, 0, 0) +el1 = Ellipse((10, 10), width=16, height=5, angle=30, fc="r") +el2 = Ellipse((30, 10), width=16, height=5, angle=170, fc="g") +el3 = Ellipse((50, 10), width=16, height=5, angle=230, fc="b") +box2.add_artist(el1) +box2.add_artist(el2) +box2.add_artist(el3) + + +box = HPacker(children=[box1, box2], + align="center", + pad=0, sep=5) + +anchored_box = AnchoredOffsetbox(loc=3, + child=box, pad=0., + frameon=True, + bbox_to_anchor=(0., 1.02), + bbox_transform=ax.transAxes, + borderpad=0., + ) + + +ax.add_artist(anchored_box) + +fig.subplots_adjust(top=0.8) +plt.show() Added: trunk/matplotlib/doc/users/plotting/examples/annotate_explain.py =================================================================== --- trunk/matplotlib/doc/users/plotting/examples/annotate_explain.py (rev 0) +++ trunk/matplotlib/doc/users/plotting/examples/annotate_explain.py 2009-07-14 21:24:07 UTC (rev 7262) @@ -0,0 +1,103 @@ + +import matplotlib.pyplot as plt +import matplotlib.patches as mpatches + +x1, y1 = 0.3, 0.3 +x2, y2 = 0.7, 0.7 + +fig = plt.figure(1, figsize=(8,3)) +fig.clf() +from mpl_toolkits.axes_grid.axes_grid import AxesGrid +from mpl_toolkits.axes_grid.anchored_artists import AnchoredText + +#from matplotlib.font_manager import FontProperties + +def add_at(ax, t, loc=2): + fp = dict(size=10) + _at = AnchoredText(t, loc=loc, prop=fp) + ax.add_artist(_at) + return _at + + +grid = AxesGrid(fig, 111, (1, 4), label_mode="1", share_all=True) + +grid[0].set_autoscale_on(False) + +ax = grid[0] +ax.plot([x1, x2], [y1, y2], ".") +el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2) +ax.add_artist(el) +ax.annotate("", + xy=(x1, y1), xycoords='data', + xytext=(x2, y2), textcoords='data', + arrowprops=dict(arrowstyle="-", #linestyle="dashed", + color="0.5", + patchB=None, + shrinkB=0, + connectionstyle="arc3,rad=0.3", + ), + ) + +add_at(ax, "connect", loc=2) + +ax = grid[1] +ax.plot([x1, x2], [y1, y2], ".") +el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2) +ax.add_artist(el) +ax.annotate("", + xy=(x1, y1), xycoords='data', + xytext=(x2, y2), textcoords='data', + arrowprops=dict(arrowstyle="-", #linestyle="dashed", + color="0.5", + patchB=el, + shrinkB=0, + connectionstyle="arc3,rad=0.3", + ), + ) + +add_at(ax, "clip", loc=2) + + +ax = grid[2] +ax.plot([x1, x2], [y1, y2], ".") +el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2) +ax.add_artist(el) +ax.annotate("", + xy=(x1, y1), xycoords='data', + xytext=(x2, y2), textcoords='data', + arrowprops=dict(arrowstyle="-", #linestyle="dashed", + color="0.5", + patchB=el, + shrinkB=5, + connectionstyle="arc3,rad=0.3", + ), + ) + +add_at(ax, "shrink", loc=2) + + +ax = grid[3] +ax.plot([x1, x2], [y1, y2], ".") +el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2) +ax.add_artist(el) +ax.annotate("", + xy=(x1, y1), xycoords='data', + xytext=(x2, y2), textcoords='data', + arrowprops=dict(arrowstyle="fancy", #linestyle="dashed", + color="0.5", + patchB=el, + shrinkB=5, + connectionstyle="arc3,rad=0.3", + ), + ) + +add_at(ax, "mutate", loc=2) + +grid[0].set_xlim(0, 1) +grid[0].set_ylim(0, 1) +grid[0].axis["bottom"].toggle(ticklabels=False) +grid[0].axis["left"].toggle(ticklabels=False) +fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95) + +plt.draw() +plt.show() Added: trunk/matplotlib/doc/users/plotting/examples/annotate_simple01.py =================================================================== --- trunk/matplotlib/doc/users/plotting/examples/annotate_simple01.py (rev 0) +++ trunk/matplotlib/doc/users/plotting/examples/annotate_simple01.py 2009-07-14 21:24:07 UTC (rev 7262) @@ -0,0 +1,14 @@ +import matplotlib.pyplot as plt + +plt.figure(1, figsize=(3,3)) +ax = plt.subplot(111) + +ax.annotate("", + xy=(0.2, 0.2), xycoords='data', + xytext=(0.8, 0.8), textcoords='data', + arrowprops=dict(arrowstyle="->", + connectionstyle="arc3"), + ) + +plt.show() + Added: trunk/matplotlib/doc/users/plotting/examples/annotate_simple02.py =================================================================== --- trunk/matplotlib/doc/users/plotting/examples/annotate_simple02.py (rev 0) +++ trunk/matplotlib/doc/users/plotting/examples/annotate_simple02.py 2009-07-14 21:24:07 UTC (rev 7262) @@ -0,0 +1,15 @@ +import matplotlib.pyplot as plt + +plt.figure(1, figsize=(3,3)) +ax = plt.subplot(111) + +ax.annotate("Test", + xy=(0.2, 0.2), xycoords='data', + xytext=(0.8, 0.8), textcoords='data', + size=20, va="center", ha="center", + arrowprops=dict(arrowstyle="simple", + connectionstyle="arc3,rad=-0.2"), + ) + +plt.show() + Added: trunk/matplotlib/doc/users/plotting/examples/annotate_simple03.py =================================================================== --- trunk/matplotlib/doc/users/plotting/examples/annotate_simple03.py (rev 0) +++ trunk/matplotlib/doc/users/plotting/examples/annotate_simple03.py 2009-07-14 21:24:07 UTC (rev 7262) @@ -0,0 +1,17 @@ +import matplotlib.pyplot as plt + +plt.figure(1, figsize=(3,3)) +ax = plt.subplot(111) + +ann = ax.annotate("Test", + xy=(0.2, 0.2), xycoords='data', + xytext=(0.8, 0.8), textcoords='data', + size=20, va="center", ha="center", + bbox=dict(boxstyle="round4", fc="w"), + arrowprops=dict(arrowstyle="-|>", + connectionstyle="arc3,rad=-0.2", + fc="w"), + ) + +plt.show() + Added: trunk/matplotlib/doc/users/plotting/examples/annotate_simple04.py =================================================================== --- trunk/matplotlib/doc/users/plotting/examples/annotate_simple04.py (rev 0) +++ trunk/matplotlib/doc/users/plotting/examples/annotate_simple04.py 2009-07-14 21:24:07 UTC (rev 7262) @@ -0,0 +1,29 @@ +import matplotlib.pyplot as plt + +plt.figure(1, figsize=(3,3)) +ax = plt.subplot(111) + +ann = ax.annotate("Test", + xy=(0.2, 0.2), xycoords='data', + xytext=(0.8, 0.8), textcoords='data', + size=20, va="center", ha="center", + bbox=dict(boxstyle="round4", fc="w"), + arrowprops=dict(arrowstyle="-|>", + connectionstyle="arc3,rad=0.2", + relpos=(0., 0.), + fc="w"), + ) + +ann = ax.annotate("Test", + xy=(0.2, 0.2), xycoords='data', + xytext=(0.8, 0.8), textcoords='data', + size=20, va="center", ha="center", + bbox=dict(boxstyle="round4", fc="w"), + arrowprops=dict(arrowstyle="-|>", + connectionstyle="arc3,rad=-0.2", + relpos=(1., 0.), + fc="w"), + ) + +plt.show() + Added: trunk/matplotlib/doc/users/plotting/examples/annotate_text_arrow.py =================================================================== --- trunk/matplotlib/doc/users/plotting/examples/annotate_text_arrow.py (rev 0) +++ trunk/matplotlib/doc/users/plotting/examples/annotate_text_arrow.py 2009-07-14 21:24:07 UTC (rev 7262) @@ -0,0 +1,38 @@ + +import numpy.random +import matplotlib.pyplot as plt + +fig = plt.figure(1, figsize=(5,5)) +fig.clf() + +ax = fig.add_subplot(111) +ax.set_aspect(1) + +x1 = -1 + numpy.random.randn(100) +y1 = -1 + numpy.random.randn(100) +x2 = 1. + numpy.random.randn(100) +y2 = 1. + numpy.random.randn(100) + +ax.scatter(x1, y1, color="r") +ax.scatter(x2, y2, color="g") + +bbox_props = dict(boxstyle="round", fc="w", ec="0.5", alpha=0.9) +ax.text(-2, -2, "Sample A", ha="center", va="center", size=20, + bbox=bbox_props) +ax.text(2, 2, "Sample B", ha="center", va="center", size=20, + bbox=bbox_props) + + +bbox_props = dict(boxstyle="rarrow", fc=(0.8,0.9,0.9), ec="b", lw=2) +t = ax.text(0, 0, "Direction", ha="center", va="center", rotation=45, + size=15, + bbox=bbox_props) + +bb = t.get_bbox_patch() +bb.set_boxstyle("rarrow", pad=0.6) + +ax.set_xlim(-4, 4) +ax.set_ylim(-4, 4) + +plt.draw() +plt.show() Added: trunk/matplotlib/doc/users/plotting/examples/axes_zoom_effect.py =================================================================== --- trunk/matplotlib/doc/users/plotting/examples/axes_zoom_effect.py (rev 0) +++ trunk/matplotlib/doc/users/plotting/examples/axes_zoom_effect.py 2009-07-14 21:24:07 UTC (rev 7262) @@ -0,0 +1 @@ +../../../../examples/pylab_examples/axes_zoom_effect.py \ No newline at end of file Added: trunk/matplotlib/doc/users/plotting/examples/connect_simple01.py =================================================================== --- trunk/matplotlib/doc/users/plotting/examples/connect_simple01.py (rev 0) +++ trunk/matplotlib/doc/users/plotting/examples/connect_simple01.py 2009-07-14 21:24:07 UTC (rev 7262) @@ -0,0 +1,31 @@ +from matplotlib.patches import ConnectionPatch +import matplotlib.pyplot as plt + +fig = plt.figure(1, figsize=(6,3)) +ax1 = plt.subplot(121) +xyA=(0.2, 0.2) +xyB=(0.8, 0.8) +coordsA="data" +coordsB="data" +con = ConnectionPatch(xyA, xyB, coordsA, coordsB, + arrowstyle="-|>", shrinkA=5, shrinkB=5, + mutation_scale=20, fc="w") +ax1.plot([xyA[0], xyB[0]], [xyA[1], xyB[1]], "o") +ax1.add_artist(con) + +ax2 = plt.subplot(122) +#xyA=(0.7, 0.7) +xy=(0.3, 0.2) +coordsA="data" +coordsB="data" +con = ConnectionPatch(xyA=xy, xyB=xy, coordsA=coordsA, coordsB=coordsB, + axesA=ax2, axesB=ax1, + arrowstyle="->", shrinkB=5) +ax2.add_artist(con) + +ax1.set_xlim(0, 1) +ax1.set_ylim(0, 1) +ax2.set_xlim(0, .5) +ax2.set_ylim(0, .5) +plt.draw() +plt.show() Added: trunk/matplotlib/doc/users/plotting/examples/connectionstyle_demo.py =================================================================== --- trunk/matplotlib/doc/users/plotting/examples/connectionstyle_demo.py (rev 0) +++ trunk/matplotlib/doc/users/plotting/examples/connectionstyle_demo.py 2009-07-14 21:24:07 UTC (rev 7262) @@ -0,0 +1,109 @@ + +import matplotlib.pyplot as plt +import matplotlib.patches as mpatches + +fig = plt.figure(1, figsize=(8,5)) +fig.clf() +from mpl_toolkits.axes_grid.axes_grid import AxesGrid +from mpl_toolkits.axes_grid.anchored_artists import AnchoredText + +#from matplotlib.font_manager import FontProperties + +def add_at(ax, t, loc=2): + fp = dict(size=8) + _at = AnchoredText(t, loc=loc, prop=fp) + ax.add_artist(_at) + return _at + + +grid = AxesGrid(fig, 111, (3, 5), label_mode="1", share_all=True) + +grid[0].set_autoscale_on(False) + + +x1, y1 = 0.3, 0.3 +x2, y2 = 0.7, 0.7 + + +def demo_con_style(ax, connectionstyle, label=None): + + if label is None: + label = connectionstyle + + x1, y1 = 0.3, 0.2 + x2, y2 = 0.8, 0.6 + + ax.plot([x1, x2], [y1, y2], ".") + ax.annotate("", + xy=(x1, y1), xycoords='data', + xytext=(x2, y2), textcoords='data', + arrowprops=dict(arrowstyle="->", #linestyle="dashed", + color="0.5", + shrinkA=5, shrinkB=5, + patchA=None, + patchB=None, + connectionstyle=connectionstyle, + ), + ) + + add_at(ax, label, loc=2) + +column = grid.axes_column[0] + +demo_con_style(column[0], "angle3,angleA=90,angleB=0", + label="angle3,\nangleA=90,\nangleB=0") +demo_con_style(column[1], "angle3,angleA=0,angleB=90", + label="angle3,\nangleA=0,\nangleB=90") + + + +column = grid.axes_column[1] + +demo_con_style(column[0], "arc3,rad=0.") +demo_con_style(column[1], "arc3,rad=0.3") +demo_con_style(column[2], "arc3,rad=-0.3") + + + +column = grid.axes_column[2] + +demo_con_style(column[0], "angle,angleA=-90,angleB=180,rad=0", + label="angle,\nangleA=-90,\nangleB=180,\nrad=0") +demo_con_style(column[1], "angle,angleA=-90,angleB=180,rad=5", + label="angle,\nangleA=-90,\nangleB=180,\nrad=5") +demo_con_style(column[2], "angle,angleA=-90,angleB=10,rad=5", + label="angle,\nangleA=-90,\nangleB=10,\nrad=0") + + +column = grid.axes_column[3] + +demo_con_style(column[0], "arc,angleA=-90,angleB=0,armA=30,armB=30,rad=0", + label="arc,\nangleA=-90,\nangleB=0,\narmA=30,\narmB=30,\nrad=0") +demo_con_style(column[1], "arc,angleA=-90,angleB=0,armA=30,armB=30,rad=5", + label="arc,\nangleA=-90,\nangleB=0,\narmA=30,\narmB=30,\nrad=5") +demo_con_style(column[2], "arc,angleA=-90,angleB=0,armA=0,armB=40,rad=0", + label="arc,\nangleA=-90,\nangleB=0,\narmA=0,\narmB=40,\nrad=0") + + +column = grid.axes_column[4] + +demo_con_style(column[0], "bar,fraction=0.3", + label="bar,\nfraction=0.3") +demo_con_style(column[1], "bar,fraction=-0.3", + label="bar,\nfraction=-0.3") +demo_con_style(column[2], "bar,angle=180,fraction=-0.2", + label="bar,\nangle=180,\nfraction=-0.2") + + +#demo_con_style(column[1], "arc3,rad=0.3") +#demo_con_style(column[2], "arc3,rad=-0.3") + + +grid[0].set_xlim(0, 1) +grid[0].set_ylim(0, 1) +grid.axes_llc.axis["bottom"].toggle(ticklabels=False) +grid.axes_llc.axis["left"].toggle(ticklabels=False) +fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95) + +plt.draw() +plt.show() Added: trunk/matplotlib/doc/users/plotting/examples/custom_boxstyle01.py =================================================================== --- trunk/matplotlib/doc/users/plotting/examples/custom_boxstyle01.py (rev 0) +++ trunk/matplotlib/doc/users/plotting/examples/custom_boxstyle01.py 2009-07-14 21:24:07 UTC (rev 7262) @@ -0,0 +1,47 @@ +from matplotlib.path import Path + +def custom_box_style(x0, y0, width, height, mutation_size, mutation_aspect=1): + """ + Given the location and size of the box, return the path of + the box around it. + + - *x0*, *y0*, *width*, *height* : location and size of the box + - *mutation_size* : a reference scale for the mutation. + - *aspect_ratio* : aspect-ration for the mutation. + """ + + # note that we are ignoring mutation_aspect. This is okay in general. + + # padding + mypad = 0.3 + pad = mutation_size * mypad + + # width and height with padding added. + width, height = width + 2.*pad, \ + height + 2.*pad, + + # boundary of the padded box + x0, y0 = x0-pad, y0-pad, + x1, y1 = x0+width, y0 + height + + cp = [(x0, y0), + (x1, y0), (x1, y1), (x0, y1), + (x0-pad, (y0+y1)/2.), (x0, y0), + (x0, y0)] + + com = [Path.MOVETO, + Path.LINETO, Path.LINETO, Path.LINETO, + Path.LINETO, Path.LINETO, + Path.CLOSEPOLY] + + path = Path(cp, com) + + return path + + +import matplotlib.pyplot as plt + +plt.figure(1, figsize=(3,3)) +ax = plt.subplot(111) +ax.text(0.5, 0.5, "Test", size=30, va="center", ha="center", + bbox=dict(boxstyle=custom_box_style, alpha=0.2)) Added: trunk/matplotlib/doc/users/plotting/examples/custom_boxstyle02.py =================================================================== --- trunk/matplotlib/doc/users/plotting/examples/custom_boxstyle02.py (rev 0) +++ trunk/matplotlib/doc/users/plotting/examples/custom_boxstyle02.py 2009-07-14 21:24:07 UTC (rev 7262) @@ -0,0 +1,74 @@ +from matplotlib.path import Path +from matplotlib.patches import BoxStyle +import matplotlib.pyplot as plt + +# we may derive from matplotlib.patches.BoxStyle._Base class. +# You need to overide transmute method in this case. + +class MyStyle(BoxStyle._Base): + """ + A simple box. + """ + + def __init__(self, pad=0.3): + """ + The arguments need to be floating numbers and need to have + default values. + + *pad* + amount of padding + """ + + self.pad = pad + super(MyStyle, self).__init__() + + def transmute(self, x0, y0, width, height, mutation_size): + """ + Given the location and size of the box, return the path of + the box around it. + + - *x0*, *y0*, *width*, *height* : location and size of the box + - *mutation_size* : a reference scale for the mutation. + + Often, the *mutation_size* is the font size of the text. + You don't need to worry about the rotation as it is + automatically taken care of. + """ + + # padding + pad = mutation_size * self.pad + + # width and height with padding added. + width, height = width + 2.*pad, \ + height + 2.*pad, + + # boundary of the padded box + x0, y0 = x0-pad, y0-pad, + x1, y1 = x0+width, y0 + height + + cp = [(x0, y0), + (x1, y0), (x1, y1), (x0, y1), + (x0-pad, (y0+y1)/2.), (x0, y0), + (x0, y0)] + + com = [Path.MOVETO, + Path.LINETO, Path.LINETO, Path.LINETO, + Path.LINETO, Path.LINETO, + Path.CLOSEPOLY] + + path = Path(cp, com) + + return path + + +# register the custom style +BoxStyle._style_list["angled"] = MyStyle + +plt.figure(1, figsize=(3,3)) +ax = plt.subplot(111) +ax.text(0.5, 0.5, "Test", size=30, va="center", ha="center", rotation=30, + bbox=dict(boxstyle="angled,pad=0.5", alpha=0.2)) + +del BoxStyle._style_list["angled"] + +plt.show() Added: trunk/matplotlib/doc/users/plotting/examples/simple_annotate01.py =================================================================== --- trunk/matplotlib/doc/users/plotting/examples/simple_annotate01.py (rev 0) +++ trunk/matplotlib/doc/users/plotting/examples/simple_annotate01.py 2009-07-14 21:24:07 UTC (rev 7262) @@ -0,0 +1,131 @@ + +import matplotlib.pyplot as plt +import matplotlib.patches as mpatches + +x1, y1 = 0.3, 0.3 +x2, y2 = 0.7, 0.7 + +fig = plt.figure(1) +fig.clf() +from mpl_toolkits.axes_grid.axes_grid import Grid +from mpl_toolkits.axes_grid.anchored_artists import AnchoredText + +from matplotlib.font_manager import FontProperties + +def add_at(ax, t, loc=2): + fp = dict(size=10) + _at = AnchoredText(t, loc=loc, prop=fp) + ax.add_artist(_at) + return _at + + +grid = Grid(fig, 111, (4, 4), label_mode="1", share_all=True) + +grid[0].set_autoscale_on(False) + +ax = grid[0] +ax.plot([x1, x2], [y1, y2], "o") +ax.annotate("", + xy=(x1, y1), xycoords='data', + xytext=(x2, y2), textcoords='data', + arrowprops=dict(arrowstyle="->")) + +add_at(ax, "A $->$ B", loc=2) + +ax = grid[1] +ax.plot([x1, x2], [y1, y2], "o") +ax.annotate("", + xy=(x1, y1), xycoords='data', + xytext=(x2, y2), textcoords='data', + arrowprops=dict(arrowstyle="->", + connectionstyle="arc3,rad=0.3")) + +add_at(ax, "connectionstyle=arc3", loc=2) + + +ax = grid[2] +ax.plot([x1, x2], [y1, y2], "o") +ax.annotate("", + xy=(x1, y1), xycoords='data', + xytext=(x2, y2), textcoords='data', + arrowprops=dict(arrowstyle="->", + connectionstyle="arc3,rad=0.3", + shrinkB=5, + ) + ) + +add_at(ax, "shrinkB=5", loc=2) + + +ax = grid[3] +ax.plot([x1, x2], [y1, y2], "o") +el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.5) +ax.add_artist(el) +ax.annotate("", + xy=(x1, y1), xycoords='data', + xytext=(x2, y2), textcoords='data', + arrowprops=dict(arrowstyle="->", + connectionstyle="arc3,rad=0.2", + ) + ) + + +ax = grid[4] +ax.plot([x1, x2], [y1, y2], "o") +el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.5) +ax.add_artist(el) +ax.annotate("", + xy=(x1, y1), xycoords='data', + xytext=(x2, y2), textcoords='data', + arrowprops=dict(arrowstyle="->", + connectionstyle="arc3,rad=0.2", + patchB=el, + ) + ) + + +add_at(ax, "patchB", loc=2) + + + +ax = grid[5] +ax.plot([x1], [y1], "o") +ax.annotate("Test", + xy=(x1, y1), xycoords='data', + xytext=(x2, y2), textcoords='data', + ha="center", va="center", + bbox=dict(boxstyle="round", + fc="w", + ), + arrowprops=dict(arrowstyle="->", + #connectionstyle="arc3,rad=0.2", + ) + ) + + +add_at(ax, "annotate", loc=2) + + +ax = grid[6] +ax.plot([x1], [y1], "o") +ax.annotate("Test", + xy=(x1, y1), xycoords='data', + xytext=(x2, y2), textcoords='data', + ha="center", va="center", + bbox=dict(boxstyle="round", + fc="w", + ), + arrowprops=dict(arrowstyle="->", + #connectionstyle="arc3,rad=0.2", + relpos=(0., 0.) + ) + ) + + +add_at(ax, "relpos=(0,0)", loc=2) + + + +#ax.set_xlim(0, 1) +#ax.set_ylim(0, 1) +plt.draw() Modified: trunk/matplotlib/doc/users/plotting.rst =================================================================== --- trunk/matplotlib/doc/users/plotting.rst 2009-07-14 21:18:58 UTC (rev 7261) +++ trunk/matplotlib/doc/users/plotting.rst 2009-07-14 21:24:07 UTC (rev 7262) @@ -146,5 +146,11 @@ :ref:`plotting-guide-legend` +Annotating plot +=============== +:func:`~matplotlib.pyplot.text` and :func:`~matplotlib.pyplot.annotate` + +:ref:`plotting-guide-annotation` + TODO; see :ref:`how-to-contribute-docs`. Added: trunk/matplotlib/examples/pylab_examples/axes_zoom_effect.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/axes_zoom_effect.py (rev 0) +++ trunk/matplotlib/examples/pylab_examples/axes_zoom_effect.py 2009-07-14 21:24:07 UTC (rev 7262) @@ -0,0 +1,120 @@ +from matplotlib.transforms import Bbox, TransformedBbox, \ + blended_transform_factory + +from mpl_toolkits.axes_grid.inset_locator import BboxPatch, BboxConnector,\ + BboxConnectorPatch + + +def connect_bbox(bbox1, bbox2, + loc1a, loc2a, loc1b, loc2b, + prop_lines, prop_patches=None): + if prop_patches is None: + prop_patches = prop_lines.copy() + prop_patches["alpha"] = prop_patches.get("alpha", 1)*0.2 + + c1 = BboxConnector(bbox1, bbox2, loc1=loc1a, loc2=loc2a, **prop_lines) + c1.set_clip_on(False) + c2 = BboxConnector(bbox1, bbox2, loc1=loc1b, loc2=loc2b, **prop_lines) + c2.set_clip_on(False) + + bbox_patch1 = BboxPatch(bbox1, **prop_patches) + bbox_patch2 = BboxPatch(bbox2, **prop_patches) + + p = BboxConnectorPatch(bbox1, bbox2, + #loc1a=3, loc2a=2, loc1b=4, loc2b=1, + loc1a=loc1a, loc2a=loc2a, loc1b=loc1b, loc2b=loc2b, + **prop_patches) + p.set_clip_on(False) + + return c1, c2, bbox_patch1, bbox_patch2, p + + +def zoom_effect01(ax1, ax2, xmin, xmax, **kwargs): + u""" + ax1 : the main axes + ax1 : the zoomed axes + (xmin,xmax) : the limits of the colored area in both plot axes. + + connect ax1 & ax2. The x-range of (xmin, xmax) in both axes will + be marked. The keywords parameters will be used ti create + patches. + + """ + + trans1 = blended_transform_factory(ax1.transData, ax1.transAxes) + trans2 = blended_transform_factory(ax2.transData, ax2.transAxes) + + bbox = Bbox.from_extents(xmin, 0, xmax, 1) + + mybbox1 = TransformedBbox(bbox, trans1) + mybbox2 = TransformedBbox(bbox, trans2) + + prop_patches=kwargs.copy() + prop_patches["ec"]="none" + prop_patches["alpha"]="0.2" + + c1, c2, bbox_patch1, bbox_patch2, p = \ + connect_bbox(mybbox1, mybbox2, + loc1a=3, loc2a=2, loc1b=4, loc2b=1, + prop_lines=kwargs, prop_patches=prop_patches) + + ax1.add_patch(bbox_patch1) + ax2.add_patch(bbox_patch2) + ax2.add_patch(c1) + ax2.add_patch(c2) + ax2.add_patch(p) + + return c1, c2, bbox_patch1, bbox_patch2, p + + +def zoom_effect02(ax1, ax2, **kwargs): + u""" + ax1 : the main axes + ax1 : the zoomed axes + + Similar to zoom_effect01. The xmin & xmax will be taken from the + ax1.viewLim. + """ + + tt = ax1.transScale + (ax1.transLimits + ax2.transAxes) + trans = blended_transform_factory(ax2.transData, tt) + + mybbox1 = ax1.bbox + mybbox2 = TransformedBbox(ax1.viewLim, trans) + + prop_patches=kwargs.copy() + prop_patches["ec"]="none" + prop_patches["alpha"]="0.2" + + c1, c2, bbox_patch1, bbox_patch2, p = \ + connect_bbox(mybbox1, mybbox2, + loc1a=3, loc2a=2, loc1b=4, loc2b=1, + prop_lines=kwargs, prop_patches=prop_patches) + + ax1.add_patch(bbox_patch1) + ax2.add_patch(bbox_patch2) + ax2.add_patch(c1) + ax2.add_patch(c2) + ax2.add_patch(p) + + return c1, c2, bbox_patch1, bbox_patch2, p + + +if __name__ == "__main__": + import matplotlib.pyplot as plt + + plt.figure(1, figsize=(5,5)) + ax1 = plt.subplot(221) + ax2 = plt.subplot(212) + ax2.set_xlim(0, 1) + ax2.set_xlim(0, 5) + zoom_effect01(ax1, ax2, 0.2, 0.8) + + + ax1 = plt.subplot(222) + ax1.set_xlim(2, 3) + ax2.set_xlim(0, 5) + zoom_effect02(ax1, ax2) + + plt.show() + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <he...@us...> - 2009-07-17 07:24:08
|
Revision: 7265 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7265&view=rev Author: heeres Date: 2009-07-17 07:24:06 +0000 (Fri, 17 Jul 2009) Log Message: ----------- mplot3d: add bar3d, improve z-sort, hist3d example Modified Paths: -------------- trunk/matplotlib/lib/mpl_toolkits/mplot3d/art3d.py trunk/matplotlib/lib/mpl_toolkits/mplot3d/axes3d.py Added Paths: ----------- trunk/matplotlib/examples/mplot3d/hist3d_demo.py Added: trunk/matplotlib/examples/mplot3d/hist3d_demo.py =================================================================== --- trunk/matplotlib/examples/mplot3d/hist3d_demo.py (rev 0) +++ trunk/matplotlib/examples/mplot3d/hist3d_demo.py 2009-07-17 07:24:06 UTC (rev 7265) @@ -0,0 +1,27 @@ +from mpl_toolkits.mplot3d import Axes3D +from matplotlib.collections import PolyCollection +from matplotlib.colors import colorConverter +import pylab +import random +import numpy as np + +fig = pylab.figure() +ax = Axes3D(fig) +x = np.random.rand(100) * 4 +y = np.random.rand(100) * 4 +hist, xedges, yedges = np.histogram2d(x, y, bins=4) + +elements = (len(xedges) - 1) * (len(yedges) - 1) +xpos, ypos = np.meshgrid( + [xedges[i] + 0.25 for i in range(len(xedges) - 1)], + [yedges[i] + 0.25 for i in range(len(yedges) - 1)]) +xpos = xpos.flatten() +ypos = ypos.flatten() +zpos = [0] * elements +dx = [0.5] * elements +dy = [0.5] * elements +dz = hist.flatten() +ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b') + +pylab.show() + Modified: trunk/matplotlib/lib/mpl_toolkits/mplot3d/art3d.py =================================================================== --- trunk/matplotlib/lib/mpl_toolkits/mplot3d/art3d.py 2009-07-16 20:53:24 UTC (rev 7264) +++ trunk/matplotlib/lib/mpl_toolkits/mplot3d/art3d.py 2009-07-17 07:24:06 UTC (rev 7265) @@ -271,6 +271,7 @@ PolyCollection.__init__(self, verts, *args, **kwargs) self._zsort = 1 + self._sort_zpos = None def get_vector(self, segments3d): """Optimize points for projection""" @@ -287,7 +288,6 @@ ones = np.ones(len(xs)) self._vec = np.array([xs, ys, zs, ones]) self._segis = segis - self._sort_zpos = min(zs) def set_verts(self, verts, closed=True): '''Set 3D vertices.''' @@ -297,9 +297,13 @@ def set_3d_properties(self): self._zsort = 1 + self._sort_zpos = None self._facecolors3d = PolyCollection.get_facecolors(self) self._edgecolors3d = PolyCollection.get_edgecolors(self) + def set_sort_zpos(self, val): + self._sort_zpos = val + def do_3d_projection(self, renderer): ''' Perform the 3D projection for this object. @@ -315,17 +319,19 @@ # This extra fuss is to re-order face / edge colors cface = self._facecolors3d - if len(self._edgecolors3d) != len(cface): - cedge = cface - else: - cedge = self._edgecolors3d + cedge = self._edgecolors3d + if len(cface) != len(xyzlist): + cface = cface.repeat(len(xyzlist), axis=0) + if len(cedge) != len(xyzlist): + if len(cedge) == 0: + cedge = cface + cedge = cedge.repeat(len(xyzlist), axis=0) # if required sort by depth (furthest drawn first) if self._zsort: - z_segments_2d = [(min(zs), zip(xs, ys), fc, ec) for + z_segments_2d = [(np.average(zs), zip(xs, ys), fc, ec) for (xs, ys, zs), fc, ec in zip(xyzlist, cface, cedge)] - z_segments_2d.sort() - z_segments_2d.reverse() + z_segments_2d.sort(reverse=True) else: raise ValueError, "whoops" @@ -339,9 +345,12 @@ self._edgecolors2d = self._edgecolors3d # Return zorder value - zvec = np.array([[0], [0], [self._sort_zpos], [1]]) - ztrans = proj3d.proj_transform_vec(zvec, renderer.M) - return ztrans[2][0] + if self._sort_zpos is not None: + zvec = np.array([[0], [0], [self._sort_zpos], [1]]) + ztrans = proj3d.proj_transform_vec(zvec, renderer.M) + return ztrans[2][0] + else: + return np.min(tzs) def set_facecolor(self, colors): PolyCollection.set_facecolor(self, colors) Modified: trunk/matplotlib/lib/mpl_toolkits/mplot3d/axes3d.py =================================================================== --- trunk/matplotlib/lib/mpl_toolkits/mplot3d/axes3d.py 2009-07-16 20:53:24 UTC (rev 7264) +++ trunk/matplotlib/lib/mpl_toolkits/mplot3d/axes3d.py 2009-07-17 07:24:06 UTC (rev 7265) @@ -625,6 +625,20 @@ return polyc + def _generate_normals(self, polygons): + ''' + Generate normals for polygons by using the first three points. + This normal of course might not make sense for polygons with + more than three points not lying in a plane. + ''' + + normals = [] + for verts in polygons: + v1 = np.array(verts[0]) - np.array(verts[1]) + v2 = np.array(verts[2]) - np.array(verts[0]) + normals.append(np.cross(v1, v2)) + return normals + def _shade_colors(self, color, normals): shade = [] for n in normals: @@ -733,6 +747,7 @@ colors2 = self._shade_colors(color, normals) polycol = art3d.Poly3DCollection(polyverts, facecolors=colors, edgecolors=colors2) + polycol.set_sort_zpos(z) self.add_collection3d(polycol) for col in colls: @@ -792,6 +807,7 @@ colls = cset.collections for z1, z2, linec in zip(levels, levels[1:], colls): art3d.poly_collection_2d_to_3d(linec, z1) + linec.set_sort_zpos(z1) self.auto_scale_xyz(X, Y, Z, had_data) return cset @@ -813,10 +829,13 @@ if type(col) is collections.PolyCollection: art3d.poly_collection_2d_to_3d(col, zs=zs, zdir=zdir) + col.set_sort_zpos(min(zs)) elif type(col) is collections.LineCollection: art3d.line_collection_2d_to_3d(col, zs=zs, zdir=zdir) + col.set_sort_zpos(min(zs)) elif type(col) is collections.PatchCollection: art3d.patch_collection_2d_to_3d(col, zs=zs, zdir=zdir) + col.set_sort_zpos(min(zs)) Axes.add_collection(self, col) @@ -902,6 +921,64 @@ return patches + def bar3d(self, x, y, z, dx, dy, dz, color='b'): + ''' + Generate a 3D bar, or multiple bars. + + When generating multiple bars, x, y, z have to be arrays. + dx, dy, dz can still be scalars. + ''' + + had_data = self.has_data() + + if not cbook.iterable(x): + print 'not interable' + x, y, z = [x], [y], [z] + if not cbook.iterable(dx): + dx, dy, dz = [dx], [dy], [dz] + if len(dx) == 1: + dx = dx * len(x) + dy = dy * len(x) + dz = dz * len(x) + + minx, miny, minz = 1e20, 1e20, 1e20 + maxx, maxy, maxz = -1e20, -1e20, -1e20 + + polys = [] + for xi, yi, zi, dxi, dyi, dzi in zip(x, y, z, dx, dy, dz): + minx = min(xi, minx) + maxx = max(xi + dxi, maxx) + miny = min(yi, miny) + maxy = max(yi + dyi, maxy) + minz = min(zi, minz) + maxz = max(zi + dzi, maxz) + + polys.extend([ + ((xi, yi, zi), (xi + dxi, yi, zi), + (xi + dxi, yi + dyi, zi), (xi, yi + dyi, zi)), + ((xi, yi, zi + dzi), (xi + dxi, yi, zi + dzi), + (xi + dxi, yi + dyi, zi + dzi), (xi, yi + dyi, zi + dzi)), + + ((xi, yi, zi), (xi + dxi, yi, zi), + (xi + dxi, yi, zi + dzi), (xi, yi, zi + dzi)), + ((xi, yi + dyi, zi), (xi + dxi, yi + dyi, zi), + (xi + dxi, yi + dyi, zi + dzi), (xi, yi + dyi, zi + dzi)), + + ((xi, yi, zi), (xi, yi + dyi, zi), + (xi, yi + dyi, zi + dzi), (xi, yi, zi + dzi)), + ((xi + dxi, yi, zi), (xi + dxi, yi + dyi, zi), + (xi + dxi, yi + dyi, zi + dzi), (xi + dxi, yi, zi + dzi)), + ]) + + color = np.array(colorConverter.to_rgba(color)) + normals = self._generate_normals(polys) + colors = self._shade_colors(color, normals) + + col = art3d.Poly3DCollection(polys, facecolor=colors) + self.add_collection(col) + + self.auto_scale_xyz((minx, maxx), (miny, maxy), (minz, maxz), had_data) + def get_test_data(delta=0.05): ''' Return a tuple X, Y, Z with a test data set. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ef...@us...> - 2009-07-17 19:03:22
|
Revision: 7268 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7268&view=rev Author: efiring Date: 2009-07-17 19:03:07 +0000 (Fri, 17 Jul 2009) Log Message: ----------- Remove swig fossils remaining from old version of agg wrapper Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/src/_backend_agg.cpp Removed Paths: ------------- trunk/matplotlib/src/agg.cxx trunk/matplotlib/src/swig_runtime.h Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-07-17 18:44:30 UTC (rev 7267) +++ trunk/matplotlib/CHANGELOG 2009-07-17 19:03:07 UTC (rev 7268) @@ -1,3 +1,5 @@ +2009-07-17 Removed fossils from swig version of agg backend. - EF + 2009-07-14 initial submission of the annotation guide. -JJL 2009-07-14 axes_grid : minor improvements in anchored_artists and @@ -3,5 +5,5 @@ inset_locator. -JJL -2009-07-14 Fix a few bugs in ConnectionStyle algorithms. Add +2009-07-14 Fix a few bugs in ConnectionStyle algorithms. Add ConnectionPatch class. -JJL Modified: trunk/matplotlib/src/_backend_agg.cpp =================================================================== --- trunk/matplotlib/src/_backend_agg.cpp 2009-07-17 18:44:30 UTC (rev 7267) +++ trunk/matplotlib/src/_backend_agg.cpp 2009-07-17 19:03:07 UTC (rev 7268) @@ -34,7 +34,6 @@ #include "agg_conv_shorten_path.h" #include "util/agg_color_conv_rgb8.h" -#include "swig_runtime.h" #include "MPL_isnan.h" #include "numpy/arrayobject.h" Deleted: trunk/matplotlib/src/agg.cxx =================================================================== --- trunk/matplotlib/src/agg.cxx 2009-07-17 18:44:30 UTC (rev 7267) +++ trunk/matplotlib/src/agg.cxx 2009-07-17 19:03:07 UTC (rev 7268) @@ -1,31983 +0,0 @@ -/* ---------------------------------------------------------------------------- - * This file was automatically generated by SWIG (http://www.swig.org). - * Version 1.3.31 - * - * This file is not intended to be easily readable and contains a number of - * coding conventions designed to improve portability and efficiency. Do not make - * changes to this file unless you know what you are doing--modify the SWIG - * interface file instead. - * ----------------------------------------------------------------------------- */ - -#define SWIGPYTHON -#define SWIG_PYTHON_DIRECTOR_NO_VTABLE - -#ifdef __cplusplus -template<class T> class SwigValueWrapper { - T *tt; -public: - SwigValueWrapper() : tt(0) { } - SwigValueWrapper(const SwigValueWrapper<T>& rhs) : tt(new T(*rhs.tt)) { } - SwigValueWrapper(const T& t) : tt(new T(t)) { } - ~SwigValueWrapper() { delete tt; } - SwigValueWrapper& operator=(const T& t) { delete tt; tt = new T(t); return *this; } - operator T&() const { return *tt; } - T *operator&() { return tt; } -private: - SwigValueWrapper& operator=(const SwigValueWrapper<T>& rhs); -}; -#endif - -/* ----------------------------------------------------------------------------- - * This section contains generic SWIG labels for method/variable - * declarations/attributes, and other compiler dependent labels. - * ----------------------------------------------------------------------------- */ - -/* template workaround for compilers that cannot correctly implement the C++ standard */ -#ifndef SWIGTEMPLATEDISAMBIGUATOR -# if defined(__SUNPRO_CC) -# if (__SUNPRO_CC <= 0x560) -# define SWIGTEMPLATEDISAMBIGUATOR template -# else -# define SWIGTEMPLATEDISAMBIGUATOR -# endif -# else -# define SWIGTEMPLATEDISAMBIGUATOR -# endif -#endif - -/* inline attribute */ -#ifndef SWIGINLINE -# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) -# define SWIGINLINE inline -# else -# define SWIGINLINE -# endif -#endif - -/* attribute recognised by some compilers to avoid 'unused' warnings */ -#ifndef SWIGUNUSED -# if defined(__GNUC__) -# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) -# define SWIGUNUSED __attribute__ ((__unused__)) -# else -# define SWIGUNUSED -# endif -# elif defined(__ICC) -# define SWIGUNUSED __attribute__ ((__unused__)) -# else -# define SWIGUNUSED -# endif -#endif - -#ifndef SWIGUNUSEDPARM -# ifdef __cplusplus -# define SWIGUNUSEDPARM(p) -# else -# define SWIGUNUSEDPARM(p) p SWIGUNUSED -# endif -#endif - -/* internal SWIG method */ -#ifndef SWIGINTERN -# define SWIGINTERN static SWIGUNUSED -#endif - -/* internal inline SWIG method */ -#ifndef SWIGINTERNINLINE -# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE -#endif - -/* exporting methods */ -#if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) -# ifndef GCC_HASCLASSVISIBILITY -# define GCC_HASCLASSVISIBILITY -# endif -#endif - -#ifndef SWIGEXPORT -# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) -# if defined(STATIC_LINKED) -# define SWIGEXPORT -# else -# define SWIGEXPORT __declspec(dllexport) -# endif -# else -# if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) -# define SWIGEXPORT __attribute__ ((visibility("default"))) -# else -# define SWIGEXPORT -# endif -# endif -#endif - -/* calling conventions for Windows */ -#ifndef SWIGSTDCALL -# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) -# define SWIGSTDCALL __stdcall -# else -# define SWIGSTDCALL -# endif -#endif - -/* Deal with Microsoft's attempt at deprecating C standard runtime functions */ -#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) -# define _CRT_SECURE_NO_DEPRECATE -#endif - - -/* Python.h has to appear first */ -#include <Python.h> - -/* ----------------------------------------------------------------------------- - * swigrun.swg - * - * This file contains generic CAPI SWIG runtime support for pointer - * type checking. - * ----------------------------------------------------------------------------- */ - -/* This should only be incremented when either the layout of swig_type_info changes, - or for whatever reason, the runtime changes incompatibly */ -#define SWIG_RUNTIME_VERSION "3" - -/* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */ -#ifdef SWIG_TYPE_TABLE -# define SWIG_QUOTE_STRING(x) #x -# define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x) -# define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE) -#else -# define SWIG_TYPE_TABLE_NAME -#endif - -/* - You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for - creating a static or dynamic library from the swig runtime code. - In 99.9% of the cases, swig just needs to declare them as 'static'. - - But only do this if is strictly necessary, ie, if you have problems - with your compiler or so. -*/ - -#ifndef SWIGRUNTIME -# define SWIGRUNTIME SWIGINTERN -#endif - -#ifndef SWIGRUNTIMEINLINE -# define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE -#endif - -/* Generic buffer size */ -#ifndef SWIG_BUFFER_SIZE -# define SWIG_BUFFER_SIZE 1024 -#endif - -/* Flags for pointer conversions */ -#define SWIG_POINTER_DISOWN 0x1 - -/* Flags for new pointer objects */ -#define SWIG_POINTER_OWN 0x1 - - -/* - Flags/methods for returning states. - - The swig conversion methods, as ConvertPtr, return and integer - that tells if the conversion was successful or not. And if not, - an error code can be returned (see swigerrors.swg for the codes). - - Use the following macros/flags to set or process the returning - states. - - In old swig versions, you usually write code as: - - if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) { - // success code - } else { - //fail code - } - - Now you can be more explicit as: - - int res = SWIG_ConvertPtr(obj,vptr,ty.flags); - if (SWIG_IsOK(res)) { - // success code - } else { - // fail code - } - - that seems to be the same, but now you can also do - - Type *ptr; - int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags); - if (SWIG_IsOK(res)) { - // success code - if (SWIG_IsNewObj(res) { - ... - delete *ptr; - } else { - ... - } - } else { - // fail code - } - - I.e., now SWIG_ConvertPtr can return new objects and you can - identify the case and take care of the deallocation. Of course that - requires also to SWIG_ConvertPtr to return new result values, as - - int SWIG_ConvertPtr(obj, ptr,...) { - if (<obj is ok>) { - if (<need new object>) { - *ptr = <ptr to new allocated object>; - return SWIG_NEWOBJ; - } else { - *ptr = <ptr to old object>; - return SWIG_OLDOBJ; - } - } else { - return SWIG_BADOBJ; - } - } - - Of course, returning the plain '0(success)/-1(fail)' still works, but you can be - more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the - swig errors code. - - Finally, if the SWIG_CASTRANK_MODE is enabled, the result code - allows to return the 'cast rank', for example, if you have this - - int food(double) - int fooi(int); - - and you call - - food(1) // cast rank '1' (1 -> 1.0) - fooi(1) // cast rank '0' - - just use the SWIG_AddCast()/SWIG_CheckState() - - - */ -#define SWIG_OK (0) -#define SWIG_ERROR (-1) -#define SWIG_IsOK(r) (r >= 0) -#define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) - -/* The CastRankLimit says how many bits are used for the cast rank */ -#define SWIG_CASTRANKLIMIT (1 << 8) -/* The NewMask denotes the object was created (using new/malloc) */ -#define SWIG_NEWOBJMASK (SWIG_CASTRANKLIMIT << 1) -/* The TmpMask is for in/out typemaps that use temporal objects */ -#define SWIG_TMPOBJMASK (SWIG_NEWOBJMASK << 1) -/* Simple returning values */ -#define SWIG_BADOBJ (SWIG_ERROR) -#define SWIG_OLDOBJ (SWIG_OK) -#define SWIG_NEWOBJ (SWIG_OK | SWIG_NEWOBJMASK) -#define SWIG_TMPOBJ (SWIG_OK | SWIG_TMPOBJMASK) -/* Check, add and del mask methods */ -#define SWIG_AddNewMask(r) (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r) -#define SWIG_DelNewMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r) -#define SWIG_IsNewObj(r) (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK)) -#define SWIG_AddTmpMask(r) (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r) -#define SWIG_DelTmpMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r) -#define SWIG_IsTmpObj(r) (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK)) - - -/* Cast-Rank Mode */ -#if defined(SWIG_CASTRANK_MODE) -# ifndef SWIG_TypeRank -# define SWIG_TypeRank unsigned long -# endif -# ifndef SWIG_MAXCASTRANK /* Default cast allowed */ -# define SWIG_MAXCASTRANK (2) -# endif -# define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) -# define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) -SWIGINTERNINLINE int SWIG_AddCast(int r) { - return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; -} -SWIGINTERNINLINE int SWIG_CheckState(int r) { - return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; -} -#else /* no cast-rank mode */ -# define SWIG_AddCast -# define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0) -#endif - - - - -#include <string.h> - -#ifdef __cplusplus -extern "C" { -#endif - -typedef void *(*swig_converter_func)(void *); -typedef struct swig_type_info *(*swig_dycast_func)(void **); - -/* Structure to store inforomation on one type */ -typedef struct swig_type_info { - const char *name; /* mangled name of this type */ - const char *str; /* human readable name of this type */ - swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ - struct swig_cast_info *cast; /* linked list of types that can cast into this type */ - void *clientdata; /* language specific type data */ - int owndata; /* flag if the structure owns the clientdata */ -} swig_type_info; - -/* Structure to store a type and conversion function used for casting */ -typedef struct swig_cast_info { - swig_type_info *type; /* pointer to type that is equivalent to this type */ - swig_converter_func converter; /* function to cast the void pointers */ - struct swig_cast_info *next; /* pointer to next cast in linked list */ - struct swig_cast_info *prev; /* pointer to the previous cast */ -} swig_cast_info; - -/* Structure used to store module information - * Each module generates one structure like this, and the runtime collects - * all of these structures and stores them in a circularly linked list.*/ -typedef struct swig_module_info { - swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ - size_t size; /* Number of types in this module */ - struct swig_module_info *next; /* Pointer to next element in circularly linked list */ - swig_type_info **type_initial; /* Array of initially generated type structures */ - swig_cast_info **cast_initial; /* Array of initially generated casting structures */ - void *clientdata; /* Language specific module data */ -} swig_module_info; - -/* - Compare two type names skipping the space characters, therefore - "char*" == "char *" and "Class<int>" == "Class<int >", etc. - - Return 0 when the two name types are equivalent, as in - strncmp, but skipping ' '. -*/ -SWIGRUNTIME int -SWIG_TypeNameComp(const char *f1, const char *l1, - const char *f2, const char *l2) { - for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { - while ((*f1 == ' ') && (f1 != l1)) ++f1; - while ((*f2 == ' ') && (f2 != l2)) ++f2; - if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; - } - return (l1 - f1) - (l2 - f2); -} - -/* - Check type equivalence in a name list like <name1>|<name2>|... - Return 0 if not equal, 1 if equal -*/ -SWIGRUNTIME int -SWIG_TypeEquiv(const char *nb, const char *tb) { - int equiv = 0; - const char* te = tb + strlen(tb); - const char* ne = nb; - while (!equiv && *ne) { - for (nb = ne; *ne; ++ne) { - if (*ne == '|') break; - } - equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; - if (*ne) ++ne; - } - return equiv; -} - -/* - Check type equivalence in a name list like <name1>|<name2>|... - Return 0 if equal, -1 if nb < tb, 1 if nb > tb -*/ -SWIGRUNTIME int -SWIG_TypeCompare(const char *nb, const char *tb) { - int equiv = 0; - const char* te = tb + strlen(tb); - const char* ne = nb; - while (!equiv && *ne) { - for (nb = ne; *ne; ++ne) { - if (*ne == '|') break; - } - equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; - if (*ne) ++ne; - } - return equiv; -} - - -/* think of this as a c++ template<> or a scheme macro */ -#define SWIG_TypeCheck_Template(comparison, ty) \ - if (ty) { \ - swig_cast_info *iter = ty->cast; \ - while (iter) { \ - if (comparison) { \ - if (iter == ty->cast) return iter; \ - /* Move iter to the top of the linked list */ \ - iter->prev->next = iter->next; \ - if (iter->next) \ - iter->next->prev = iter->prev; \ - iter->next = ty->cast; \ - iter->prev = 0; \ - if (ty->cast) ty->cast->prev = iter; \ - ty->cast = iter; \ - return iter; \ - } \ - iter = iter->next; \ - } \ - } \ - return 0 - -/* - Check the typename -*/ -SWIGRUNTIME swig_cast_info * -SWIG_TypeCheck(const char *c, swig_type_info *ty) { - SWIG_TypeCheck_Template(strcmp(iter->type->name, c) == 0, ty); -} - -/* Same as previous function, except strcmp is replaced with a pointer comparison */ -SWIGRUNTIME swig_cast_info * -SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *into) { - SWIG_TypeCheck_Template(iter->type == from, into); -} - -/* - Cast a pointer up an inheritance hierarchy -*/ -SWIGRUNTIMEINLINE void * -SWIG_TypeCast(swig_cast_info *ty, void *ptr) { - return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr); -} - -/* - Dynamic pointer casting. Down an inheritance hierarchy -*/ -SWIGRUNTIME swig_type_info * -SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { - swig_type_info *lastty = ty; - if (!ty || !ty->dcast) return ty; - while (ty && (ty->dcast)) { - ty = (*ty->dcast)(ptr); - if (ty) lastty = ty; - } - return lastty; -} - -/* - Return the name associated with this type -*/ -SWIGRUNTIMEINLINE const char * -SWIG_TypeName(const swig_type_info *ty) { - return ty->name; -} - -/* - Return the pretty name associated with this type, - that is an unmangled type name in a form presentable to the user. -*/ -SWIGRUNTIME const char * -SWIG_TypePrettyName(const swig_type_info *type) { - /* The "str" field contains the equivalent pretty names of the - type, separated by vertical-bar characters. We choose - to print the last name, as it is often (?) the most - specific. */ - if (!type) return NULL; - if (type->str != NULL) { - const char *last_name = type->str; - const char *s; - for (s = type->str; *s; s++) - if (*s == '|') last_name = s+1; - return last_name; - } - else - return type->name; -} - -/* - Set the clientdata field for a type -*/ -SWIGRUNTIME void -SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { - swig_cast_info *cast = ti->cast; - /* if (ti->clientdata == clientdata) return; */ - ti->clientdata = clientdata; - - while (cast) { - if (!cast->converter) { - swig_type_info *tc = cast->type; - if (!tc->clientdata) { - SWIG_TypeClientData(tc, clientdata); - } - } - cast = cast->next; - } -} -SWIGRUNTIME void -SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { - SWIG_TypeClientData(ti, clientdata); - ti->owndata = 1; -} - -/* - Search for a swig_type_info structure only by mangled name - Search is a O(log #types) - - We start searching at module start, and finish searching when start == end. - Note: if start == end at the beginning of the function, we go all the way around - the circular list. -*/ -SWIGRUNTIME swig_type_info * -SWIG_MangledTypeQueryModule(swig_module_info *start, - swig_module_info *end, - const char *name) { - swig_module_info *iter = start; - do { - if (iter->size) { - register size_t l = 0; - register size_t r = iter->size - 1; - do { - /* since l+r >= 0, we can (>> 1) instead (/ 2) */ - register size_t i = (l + r) >> 1; - const char *iname = iter->types[i]->name; - if (iname) { - register int compare = strcmp(name, iname); - if (compare == 0) { - return iter->types[i]; - } else if (compare < 0) { - if (i) { - r = i - 1; - } else { - break; - } - } else if (compare > 0) { - l = i + 1; - } - } else { - break; /* should never happen */ - } - } while (l <= r); - } - iter = iter->next; - } while (iter != end); - return 0; -} - -/* - Search for a swig_type_info structure for either a mangled name or a human readable name. - It first searches the mangled names of the types, which is a O(log #types) - If a type is not found it then searches the human readable names, which is O(#types). - - We start searching at module start, and finish searching when start == end. - Note: if start == end at the beginning of the function, we go all the way around - the circular list. -*/ -SWIGRUNTIME swig_type_info * -SWIG_TypeQueryModule(swig_module_info *start, - swig_module_info *end, - const char *name) { - /* STEP 1: Search the name field using binary search */ - swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); - if (ret) { - return ret; - } else { - /* STEP 2: If the type hasn't been found, do a complete search - of the str field (the human readable name) */ - swig_module_info *iter = start; - do { - register size_t i = 0; - for (; i < iter->size; ++i) { - if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) - return iter->types[i]; - } - iter = iter->next; - } while (iter != end); - } - - /* neither found a match */ - return 0; -} - -/* - Pack binary data into a string -*/ -SWIGRUNTIME char * -SWIG_PackData(char *c, void *ptr, size_t sz) { - static const char hex[17] = "0123456789abcdef"; - register const unsigned char *u = (unsigned char *) ptr; - register const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - register unsigned char uu = *u; - *(c++) = hex[(uu & 0xf0) >> 4]; - *(c++) = hex[uu & 0xf]; - } - return c; -} - -/* - Unpack binary data from a string -*/ -SWIGRUNTIME const char * -SWIG_UnpackData(const char *c, void *ptr, size_t sz) { - register unsigned char *u = (unsigned char *) ptr; - register const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - register char d = *(c++); - register unsigned char uu; - if ((d >= '0') && (d <= '9')) - uu = ((d - '0') << 4); - else if ((d >= 'a') && (d <= 'f')) - uu = ((d - ('a'-10)) << 4); - else - return (char *) 0; - d = *(c++); - if ((d >= '0') && (d <= '9')) - uu |= (d - '0'); - else if ((d >= 'a') && (d <= 'f')) - uu |= (d - ('a'-10)); - else - return (char *) 0; - *u = uu; - } - return c; -} - -/* - Pack 'void *' into a string buffer. -*/ -SWIGRUNTIME char * -SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { - char *r = buff; - if ((2*sizeof(void *) + 2) > bsz) return 0; - *(r++) = '_'; - r = SWIG_PackData(r,&ptr,sizeof(void *)); - if (strlen(name) + 1 > (bsz - (r - buff))) return 0; - strcpy(r,name); - return buff; -} - -SWIGRUNTIME const char * -SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { - if (*c != '_') { - if (strcmp(c,"NULL") == 0) { - *ptr = (void *) 0; - return name; - } else { - return 0; - } - } - return SWIG_UnpackData(++c,ptr,sizeof(void *)); -} - -SWIGRUNTIME char * -SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { - char *r = buff; - size_t lname = (name ? strlen(name) : 0); - if ((2*sz + 2 + lname) > bsz) return 0; - *(r++) = '_'; - r = SWIG_PackData(r,ptr,sz); - if (lname) { - strncpy(r,name,lname+1); - } else { - *r = 0; - } - return buff; -} - -SWIGRUNTIME const char * -SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { - if (*c != '_') { - if (strcmp(c,"NULL") == 0) { - memset(ptr,0,sz); - return name; - } else { - return 0; - } - } - return SWIG_UnpackData(++c,ptr,sz); -} - -#ifdef __cplusplus -} -#endif - -/* Errors in SWIG */ -#define SWIG_UnknownError -1 -#define SWIG_IOError -2 -#define SWIG_RuntimeError -3 -#define SWIG_IndexError -4 -#define SWIG_TypeError -5 -#define SWIG_DivisionByZero -6 -#define SWIG_OverflowError -7 -#define SWIG_SyntaxError -8 -#define SWIG_ValueError -9 -#define SWIG_SystemError -10 -#define SWIG_AttributeError -11 -#define SWIG_MemoryError -12 -#define SWIG_NullReferenceError -13 - - - - -/* Add PyOS_snprintf for old Pythons */ -#if PY_VERSION_HEX < 0x02020000 -# if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WATCOM) -# define PyOS_snprintf _snprintf -# else -# define PyOS_snprintf snprintf -# endif -#endif - -/* A crude PyString_FromFormat implementation for old Pythons */ -#if PY_VERSION_HEX < 0x02020000 - -#ifndef SWIG_PYBUFFER_SIZE -# define SWIG_PYBUFFER_SIZE 1024 -#endif - -static PyObject * -PyString_FromFormat(const char *fmt, ...) { - va_list ap; - char buf[SWIG_PYBUFFER_SIZE * 2]; - int res; - va_start(ap, fmt); - res = vsnprintf(buf, sizeof(buf), fmt, ap); - va_end(ap); - return (res < 0 || res >= (int)sizeof(buf)) ? 0 : PyString_FromString(buf); -} -#endif - -/* Add PyObject_Del for old Pythons */ -#if PY_VERSION_HEX < 0x01060000 -# define PyObject_Del(op) PyMem_DEL((op)) -#endif -#ifndef PyObject_DEL -# define PyObject_DEL PyObject_Del -#endif - -/* A crude PyExc_StopIteration exception for old Pythons */ -#if PY_VERSION_HEX < 0x02020000 -# ifndef PyExc_StopIteration -# define PyExc_StopIteration PyExc_RuntimeError -# endif -# ifndef PyObject_GenericGetAttr -# define PyObject_GenericGetAttr 0 -# endif -#endif -/* Py_NotImplemented is defined in 2.1 and up. */ -#if PY_VERSION_HEX < 0x02010000 -# ifndef Py_NotImplemented -# define Py_NotImplemented PyExc_RuntimeError -# endif -#endif - - -/* A crude PyString_AsStringAndSize implementation for old Pythons */ -#if PY_VERSION_HEX < 0x02010000 -# ifndef PyString_AsStringAndSize -# define PyString_AsStringAndSize(obj, s, len) {*s = PyString_AsString(obj); *len = *s ? strlen(*s) : 0;} -# endif -#endif - -/* PySequence_Size for old Pythons */ -#if PY_VERSION_HEX < 0x02000000 -# ifndef PySequence_Size -# define PySequence_Size PySequence_Length -# endif -#endif - - -/* PyBool_FromLong for old Pythons */ -#if PY_VERSION_HEX < 0x02030000 -static -PyObject *PyBool_FromLong(long ok) -{ - PyObject *result = ok ? Py_True : Py_False; - Py_INCREF(result); - return result; -} -#endif - -/* Py_ssize_t for old Pythons */ -/* This code is as recommended by: */ -/* http://www.python.org/dev/peps/pep-0353/#conversion-guidelines */ -#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) -typedef int Py_ssize_t; -# define PY_SSIZE_T_MAX INT_MAX -# define PY_SSIZE_T_MIN INT_MIN -#endif - -/* ----------------------------------------------------------------------------- - * error manipulation - * ----------------------------------------------------------------------------- */ - -SWIGRUNTIME PyObject* -SWIG_Python_ErrorType(int code) { - PyObject* type = 0; - switch(code) { - case SWIG_MemoryError: - type = PyExc_MemoryError; - break; - case SWIG_IOError: - type = PyExc_IOError; - break; - case SWIG_RuntimeError: - type = PyExc_RuntimeError; - break; - case SWIG_IndexError: - type = PyExc_IndexError; - break; - case SWIG_TypeError: - type = PyExc_TypeError; - break; - case SWIG_DivisionByZero: - type = PyExc_ZeroDivisionError; - break; - case SWIG_OverflowError: - type = PyExc_OverflowError; - break; - case SWIG_SyntaxError: - type = PyExc_SyntaxError; - break; - case SWIG_ValueError: - type = PyExc_ValueError; - break; - case SWIG_SystemError: - type = PyExc_SystemError; - break; - case SWIG_AttributeError: - type = PyExc_AttributeError; - break; - default: - type = PyExc_RuntimeError; - } - return type; -} - - -SWIGRUNTIME void -SWIG_Python_AddErrorMsg(const char* mesg) -{ - PyObject *type = 0; - PyObject *value = 0; - PyObject *traceback = 0; - - if (PyErr_Occurred()) PyErr_Fetch(&type, &value, &traceback); - if (value) { - PyObject *old_str = PyObject_Str(value); - PyErr_Clear(); - Py_XINCREF(type); - PyErr_Format(type, "%s %s", PyString_AsString(old_str), mesg); - Py_DECREF(old_str); - Py_DECREF(value); - } else { - PyErr_Format(PyExc_RuntimeError, mesg); - } -} - - - -#if defined(SWIG_PYTHON_NO_THREADS) -# if defined(SWIG_PYTHON_THREADS) -# undef SWIG_PYTHON_THREADS -# endif -#endif -#if defined(SWIG_PYTHON_THREADS) /* Threading support is enabled */ -# if !defined(SWIG_PYTHON_USE_GIL) && !defined(SWIG_PYTHON_NO_USE_GIL) -# if (PY_VERSION_HEX >= 0x02030000) /* For 2.3 or later, use the PyGILState calls */ -# define SWIG_PYTHON_USE_GIL -# endif -# endif -# if defined(SWIG_PYTHON_USE_GIL) /* Use PyGILState threads calls */ -# ifndef SWIG_PYTHON_INITIALIZE_THREADS -# define SWIG_PYTHON_INITIALIZE_THREADS PyEval_InitThreads() -# endif -# ifdef __cplusplus /* C++ code */ - class SWIG_Python_Thread_Block { - bool status; - PyGILState_STATE state; - public: - void end() { if (status) { PyGILState_Release(state); status = false;} } - SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {} - ~SWIG_Python_Thread_Block() { end(); } - }; - class SWIG_Python_Thread_Allow { - bool status; - PyThreadState *save; - public: - void end() { if (status) { PyEval_RestoreThread(save); status = false; }} - SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {} - ~SWIG_Python_Thread_Allow() { end(); } - }; -# define SWIG_PYTHON_THREAD_BEGIN_BLOCK SWIG_Python_Thread_Block _swig_thread_block -# define SWIG_PYTHON_THREAD_END_BLOCK _swig_thread_block.end() -# define SWIG_PYTHON_THREAD_BEGIN_ALLOW SWIG_Python_Thread_Allow _swig_thread_allow -# define SWIG_PYTHON_THREAD_END_ALLOW _swig_thread_allow.end() -# else /* C code */ -# define SWIG_PYTHON_THREAD_BEGIN_BLOCK PyGILState_STATE _swig_thread_block = PyGILState_Ensure() -# define SWIG_PYTHON_THREAD_END_BLOCK PyGILState_Release(_swig_thread_block) -# define SWIG_PYTHON_THREAD_BEGIN_ALLOW PyThreadState *_swig_thread_allow = PyEval_SaveThread() -# define SWIG_PYTHON_THREAD_END_ALLOW PyEval_RestoreThread(_swig_thread_allow) -# endif -# else /* Old thread way, not implemented, user must provide it */ -# if !defined(SWIG_PYTHON_INITIALIZE_THREADS) -# define SWIG_PYTHON_INITIALIZE_THREADS -# endif -# if !defined(SWIG_PYTHON_THREAD_BEGIN_BLOCK) -# define SWIG_PYTHON_THREAD_BEGIN_BLOCK -# endif -# if !defined(SWIG_PYTHON_THREAD_END_BLOCK) -# define SWIG_PYTHON_THREAD_END_BLOCK -# endif -# if !defined(SWIG_PYTHON_THREAD_BEGIN_ALLOW) -# define SWIG_PYTHON_THREAD_BEGIN_ALLOW -# endif -# if !defined(SWIG_PYTHON_THREAD_END_ALLOW) -# define SWIG_PYTHON_THREAD_END_ALLOW -# endif -# endif -#else /* No thread support */ -# define SWIG_PYTHON_INITIALIZE_THREADS -# define SWIG_PYTHON_THREAD_BEGIN_BLOCK -# define SWIG_PYTHON_THREAD_END_BLOCK -# define SWIG_PYTHON_THREAD_BEGIN_ALLOW -# define SWIG_PYTHON_THREAD_END_ALLOW -#endif - -/* ----------------------------------------------------------------------------- - * Python API portion that goes into the runtime - * ----------------------------------------------------------------------------- */ - -#ifdef __cplusplus -extern "C" { -#if 0 -} /* cc-mode */ -#endif -#endif - -/* ----------------------------------------------------------------------------- - * Constant declarations - * ----------------------------------------------------------------------------- */ - -/* Constant Types */ -#define SWIG_PY_POINTER 4 -#define SWIG_PY_BINARY 5 - -/* Constant information structure */ -typedef struct swig_const_info { - int type; - char *name; - long lvalue; - double dvalue; - void *pvalue; - swig_type_info **ptype; -} swig_const_info; - -#ifdef __cplusplus -#if 0 -{ /* cc-mode */ -#endif -} -#endif - - -/* ----------------------------------------------------------------------------- - * See the LICENSE file for information on copyright, usage and redistribution - * of SWIG, and the README file for authors - http://www.swig.org/release.html. - * - * pyrun.swg - * - * This file contains the runtime support for Python modules - * and includes code for managing global variables and pointer - * type checking. - * - * ----------------------------------------------------------------------------- */ - -/* Common SWIG API */ - -/* for raw pointers */ -#define SWIG_Python_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, 0) -#define SWIG_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtr(obj, pptr, type, flags) -#define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, own) -#define SWIG_NewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(ptr, type, flags) -#define SWIG_CheckImplicit(ty) SWIG_Python_CheckImplicit(ty) -#define SWIG_AcquirePtr(ptr, src) SWIG_Python_AcquirePtr(ptr, src) -#define swig_owntype int - -/* for raw packed data */ -#define SWIG_ConvertPacked(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) -#define SWIG_NewPackedObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) - -/* for class or struct pointers */ -#define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_ConvertPtr(obj, pptr, type, flags) -#define SWIG_NewInstanceObj(ptr, type, flags) SWIG_NewPointerObj(ptr, type, flags) - -/* for C or C++ function pointers */ -#define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_Python_ConvertFunctionPtr(obj, pptr, type) -#define SWIG_NewFunctionPtrObj(ptr, type) SWIG_Python_NewPointerObj(ptr, type, 0) - -/* for C++ member pointers, ie, member methods */ -#define SWIG_ConvertMember(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) -#define SWIG_NewMemberObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) - - -/* Runtime API */ - -#define SWIG_GetModule(clientdata) SWIG_Python_GetModule() -#define SWIG_SetModule(clientdata, pointer) SWIG_Python_SetModule(pointer) -#define SWIG_NewClientData(obj) PySwigClientData_New(obj) - -#define SWIG_SetErrorObj SWIG_Python_SetErrorObj -#define SWIG_SetErrorMsg SWIG_Python_SetErrorMsg -#define SWIG_ErrorType(code) SWIG_Python_ErrorType(code) -#define SWIG_Error(code, msg) SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) -#define SWIG_fail goto fail - - -/* Runtime API implementation */ - -/* Error manipulation */ - -SWIGINTERN void -SWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) { - SWIG_PYTHON_THREAD_BEGIN_BLOCK; - PyErr_SetObject(errtype, obj); - Py_DECREF(obj); - SWIG_PYTHON_THREAD_END_BLOCK; -} - -SWIGINTERN void -SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) { - SWIG_PYTHON_THREAD_BEGIN_BLOCK; - PyErr_SetString(errtype, (char *) msg); - SWIG_PYTHON_THREAD_END_BLOCK; -} - -#define SWIG_Python_Raise(obj, type, desc) SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj) - -/* Set a constant value */ - -SWIGINTERN void -SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) { - PyDict_SetItemString(d, (char*) name, obj); - Py_DECREF(obj); -} - -/* Append a value to the result obj */ - -SWIGINTERN PyObject* -SWIG_Python_AppendOutput(PyObject* result, PyObject* obj) { -#if !defined(SWIG_PYTHON_OUTPUT_TUPLE) - if (!result) { - result = obj; - } else if (result == Py_None) { - Py_DECREF(result); - result = obj; - } else { - if (!PyList_Check(result)) { - PyObject *o2 = result; - result = PyList_New(1); - PyList_SetItem(result, 0, o2); - } - PyList_Append(result,obj); - Py_DECREF(obj); - } - return result; -#else - PyObject* o2; - PyObject* o3; - if (!result) { - result = obj; - } else if (result == Py_None) { - Py_DECREF(result); - result = obj; - } else { - if (!PyTuple_Check(result)) { - o2 = result; - result = PyTuple_New(1); - PyTuple_SET_ITEM(result, 0, o2); - } - o3 = PyTuple_New(1); - PyTuple_SET_ITEM(o3, 0, obj); - o2 = result; - result = PySequence_Concat(o2, o3); - Py_DECREF(o2); - Py_DECREF(o3); - } - return result; -#endif -} - -/* Unpack the argument tuple */ - -SWIGINTERN int -SWIG_Python_UnpackTuple(PyObject *args, const char *name, int min, int max, PyObject **objs) -{ - if (!args) { - if (!min && !max) { - return 1; - } else { - PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", - name, (min == max ? "" : "at least "), min); - return 0; - } - } - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple"); - return 0; - } else { - register int l = PyTuple_GET_SIZE(args); - if (l < min) { - PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", - name, (min == max ? "" : "at least "), min, l); - return 0; - } else if (l > max) { - PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", - name, (min == max ? "" : "at most "), max, l); - return 0; - } else { - register int i; - for (i = 0; i < l; ++i) { - objs[i] = PyTuple_GET_ITEM(args, i); - } - for (; l < max; ++l) { - objs[l] = 0; - } - return i + 1; - } - } -} - -/* A functor is a function object with one single object argument */ -#if PY_VERSION_HEX >= 0x02020000 -#define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunctionObjArgs(functor, obj, NULL); -#else -#define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunction(functor, "O", obj); -#endif - -/* - Helper for static pointer initialization for both C and C++ code, for example - static PyObject *SWIG_STATIC_POINTER(MyVar) = NewSomething(...); -*/ -#ifdef __cplusplus -#define SWIG_STATIC_POINTER(var) var -#else -#define SWIG_STATIC_POINTER(var) var = 0; if (!var) var -#endif - -/* ----------------------------------------------------------------------------- - * Pointer declarations - * ----------------------------------------------------------------------------- */ - -/* Flags for new pointer objects */ -#define SWIG_POINTER_NOSHADOW (SWIG_POINTER_OWN << 1) -#define SWIG_POINTER_NEW (SWIG_POINTER_NOSHADOW | SWIG_POINTER_OWN) - -#define SWIG_POINTER_IMPLICIT_CONV (SWIG_POINTER_DISOWN << 1) - -#ifdef __cplusplus -extern "C" { -#if 0 -} /* cc-mode */ -#endif -#endif - -/* How to access Py_None */ -#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) -# ifndef SWIG_PYTHON_NO_BUILD_NONE -# ifndef SWIG_PYTHON_BUILD_NONE -# define SWIG_PYTHON_BUILD_NONE -# endif -# endif -#endif - -#ifdef SWIG_PYTHON_BUILD_NONE -# ifdef Py_None -# undef Py_None -# define Py_None SWIG_Py_None() -# endif -SWIGRUNTIMEINLINE PyObject * -_SWIG_Py_None(void) -{ - PyObject *none = Py_BuildValue((char*)""); - Py_DECREF(none); - return none; -} -SWIGRUNTIME PyObject * -SWIG_Py_None(void) -{ - static PyObject *SWIG_STATIC_POINTER(none) = _SWIG_Py_None(); - return none; -} -#endif - -/* The python void return value */ - -SWIGRUNTIMEINLINE PyObject * -SWIG_Py_Void(void) -{ - PyObject *none = Py_None; - Py_INCREF(none); - return none; -} - -/* PySwigClientData */ - -typedef struct { - PyObject *klass; - PyObject *newraw; - PyObject *newargs; - PyObject *destroy; - int delargs; - int implicitconv; -} PySwigClientData; - -SWIGRUNTIMEINLINE int -SWIG_Python_CheckImplicit(swig_type_info *ty) -{ - PySwigClientData *data = (PySwigClientData *)ty->clientdata; - return data ? data->implicitconv : 0; -} - -SWIGRUNTIMEINLINE PyObject * -SWIG_Python_ExceptionType(swig_type_info *desc) { - PySwigClientData *data = desc ? (PySwigClientData *) desc->clientdata : 0; - PyObject *klass = data ? data->klass : 0; - return (klass ? klass : PyExc_RuntimeError); -} - - -SWIGRUNTIME PySwigClientData * -PySwigClientData_New(PyObject* obj) -{ - if (!obj) { - return 0; - } else { - PySwigClientData *data = (PySwigClientData *)malloc(sizeof(PySwigClientData)); - /* the klass element */ - data->klass = obj; - Py_INCREF(data->klass); - /* the newraw method and newargs arguments used to create a new raw instance */ - if (PyClass_Check(obj)) { - data->newraw = 0; - data->newargs = obj; - Py_INCREF(obj); - } else { -#if (PY_VERSION_HEX < 0x02020000) - data->newraw = 0; -#else - data->newraw = PyObject_GetAttrString(data->klass, (char *)"__new__"); -#endif - if (data->newraw) { - Py_INCREF(data->newraw); - data->newargs = PyTuple_New(1); - PyTuple_SetItem(data->newargs, 0, obj); - } else { - data->newargs = obj; - } - Py_INCREF(data->newargs); - } - /* the destroy method, aka as the C++ delete method */ - data->destroy = PyObject_GetAttrString(data->klass, (char *)"__swig_destroy__"); - if (PyErr_Occurred()) { - PyErr_Clear(); - data->destroy = 0; - } - if (data->destroy) { - int flags; - Py_INCREF(data->destroy); - flags = PyCFunction_GET_FLAGS(data->destroy); -#ifdef METH_O - data->delargs = !(flags & (METH_O)); -#else - data->delargs = 0; -#endif - } else { - data->delargs = 0; - } - data->implicitconv = 0; - return data; - } -} - -SWIGRUNTIME void -PySwigClientData_Del(PySwigClientData* data) -{ - Py_XDECREF(data->newraw); - Py_XDECREF(data->newargs); - Py_XDECREF(data->destroy); -} - -/* =============== PySwigObject =====================*/ - -typedef struct { - PyObject_HEAD - void *ptr; - swig_type_info *ty; - int own; - PyObject *next; -} PySwigObject; - -SWIGRUNTIME PyObject * -PySwigObject_long(PySwigObject *v) -{ - return PyLong_FromVoidPtr(v->ptr); -} - -SWIGRUNTIME PyObject * -PySwigObject_format(const char* fmt, PySwigObject *v) -{ - PyObject *res = NULL; - PyObject *args = PyTuple_New(1); - if (args) { - if (PyTuple_SetItem(args, 0, PySwigObject_long(v)) == 0) { - PyObject *ofmt = PyString_FromString(fmt); - if (ofmt) { - res = PyString_Format(ofmt,args); - Py_DECREF(ofmt); - } - Py_DECREF(args); - } - } - return res; -} - -SWIGRUNTIME PyObject * -PySwigObject_oct(PySwigObject *v) -{ - return PySwigObject_format("%o",v); -} - -SWIGRUNTIME PyObject * -PySwigObject_hex(PySwigObject *v) -{ - return PySwigObject_format("%x",v); -} - -SWIGRUNTIME PyObject * -#ifdef METH_NOARGS -PySwigObject_repr(PySwigObject *v) -#else -PySwigObject_repr(PySwigObject *v, PyObject *args) -#endif -{ - const char *name = SWIG_TypePrettyName(v->ty); - PyObject *hex = PySwigObject_hex(v); - PyObject *repr = PyString_FromFormat("<Swig Object of type '%s' at 0x%s>", name, PyString_AsString(hex)); - Py_DECREF(hex); - if (v->next) { -#ifdef METH_NOARGS - PyObject *nrep = PySwigObject_repr((PySwigObject *)v->next); -#else - PyObject *nrep = PySwigObject_repr((PySwigObject *)v->next, args); -#endif - PyString_ConcatAndDel(&repr,nrep); - } - return repr; -} - -SWIGRUNTIME int -PySwigObject_print(PySwigObject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) -{ -#ifdef METH_NOARGS - PyObject *repr = PySwigObject_repr(v); -#else - PyObject *repr = PySwigObject_repr(v, NULL); -#endif - if (repr) { - fputs(PyString_AsString(repr), fp); - Py_DECREF(repr); - return 0; - } else { - return 1; - } -} - -SWIGRUNTIME PyObject * -PySwigObject_str(PySwigObject *v) -{ - char result[SWIG_BUFFER_SIZE]; - return SWIG_PackVoidPtr(result, v->ptr, v->ty->name, sizeof(result)) ? - PyString_FromString(result) : 0; -} - -SWIGRUNTIME int -PySwigObject_compare(PySwigObject *v, PySwigObject *w) -{ - void *i = v->ptr; - void *j = w->ptr; - return (i < j) ? -1 : ((i > j) ? 1 : 0); -} - -SWIGRUNTIME PyTypeObject* _PySwigObject_type(void); - -SWIGRUNTIME PyTypeObject* -PySwigObject_type(void) { - static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigObject_type(); - return type; -} - -SWIGRUNTIMEINLINE int -PySwigObject_Check(PyObject *op) { - return ((op)->ob_type == PySwigObject_type()) - || (strcmp((op)->ob_type->tp_name,"PySwigObject") == 0); -} - -SWIGRUNTIME PyObject * -PySwigObject_New(void *ptr, swig_type_info *ty, int own); - -SWIGRUNTIME void -PySwigObject_dealloc(PyObject *v) -{ - PySwigObject *sobj = (PySwigObject *) v; - PyObject *next = sobj->next; - if (sobj->own) { - swig_type_info *ty = sobj->ty; - PySwigClientData *data = ty ? (PySwigClientData *) ty->clientdata : 0; - PyObject *destroy = data ? data->destroy : 0; - if (destroy) { - /* destroy is always a VARARGS method */ - PyObject *res; - if (data->delargs) { - /* we need to create a temporal object to carry the destroy operation */ - PyObject *tmp = PySwigObject_New(sobj->ptr, ty, 0); - res = SWIG_Python_CallFunctor(destroy, tmp); - Py_DECREF(tmp); - } else { - PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); - PyObject *mself = PyCFunction_GET_SELF(destroy); - res = ((*meth)(mself, v)); - } - Py_XDECREF(res); - } else { - const char *name = SWIG_TypePrettyName(ty); -#if !defined(SWIG_PYTHON_SILENT_MEMLEAK) - printf("swig/python detected a memory leak of type '%s', no destructor found.\n", name); -#endif - } - } - Py_XDECREF(next); - PyObject_DEL(v); -} - -SWIGRUNTIME PyObject* -PySwigObject_append(PyObject* v, PyObject* next) -{ - PySwigObject *sobj = (PySwigObject *) v; -#ifndef METH_O - PyObject *tmp = 0; - if (!PyArg_ParseTuple(next,(char *)"O:append", &tmp)) return NULL; - next = tmp; -#endif - if (!PySwigObject_Check(next)) { - return NULL; - } - sobj->next = next; - Py_INCREF(next); - return SWIG_Py_Void(); -} - -SWIGRUNTIME PyObject* -#ifdef METH_NOARGS -PySwigObject_next(PyObject* v) -#else -PySwigObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) -#endif -{ - PySwigObject *sobj = (PySwigObject *) v; - if (sobj->next) { - Py_INCREF(sobj->next); - return sobj->next; - } else { - return SWIG_Py_Void(); - } -} - -SWIGINTERN PyObject* -#ifdef METH_NOARGS -PySwigObject_disown(PyObject *v) -#else -PySwigObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) -#endif -{ - PySwigObject *sobj = (PySwigObject *)v; - sobj->own = 0; - return SWIG_Py_Void(); -} - -SWIGINTERN PyObject* -#ifdef METH_NOARGS -PySwigObject_acquire(PyObject *v) -#else -PySwigObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) -#endif -{ - PySwigObject *sobj = (PySwigObject *)v; - sobj->own = SWIG_POINTER_OWN; - return SWIG_Py_Void(); -} - -SWIGINTERN PyObject* -PySwigObject_own(PyObject *v, PyObject *args) -{ - PyObject *val = 0; -#if (PY_VERSION_HEX < 0x02020000) - if (!PyArg_ParseTuple(args,(char *)"|O:own",&val)) -#else - if (!PyArg_UnpackTuple(args, (char *)"own", 0, 1, &val)) -#endif - { - return NULL; - } - else - { - PySwigObject *sobj = (PySwigObject *)v; - PyObject *obj = PyBool_FromLong(sobj->own); - if (val) { -#ifdef METH_NOARGS - if (PyObject_IsTrue(val)) { - PySwigObject_acquire(v); - } else { - PySwigObject_disown(v); - } -#else - if (PyObject_IsTrue(val)) { - PySwigObject_acquire(v,args); - } else { - PySwigObject_disown(v,args); - } -#endif - } - return obj; - } -} - -#ifdef METH_O -static PyMethodDef -swigobject_methods[] = { - {(char *)"disown", (PyCFunction)PySwigObject_disown, METH_NOARGS, (char *)"releases ownership of the pointer"}, - {(char *)"acquire", (PyCFunction)PySwigObject_acquire, METH_NOARGS, (char *)"aquires ownership of the pointer"}, - {(char *)"own", (PyCFunction)PySwigObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, - {(char *)"append", (PyCFunction)PySwigObject_append, METH_O, (char *)"appends another 'this' object"}, - {(char *)"next", (PyCFunction)PySwigObject_next, METH_NOARGS, (char *)"returns the next 'this' object"}, - {(char *)"__repr__",(PyCFunction)PySwigObject_repr, METH_NOARGS, (char *)"returns object representation"}, - {0, 0, 0, 0} -}; -#else -static PyMethodDef -swigobject_methods[] = { - {(char *)"disown", (PyCFunction)PySwigObject_disown, METH_VARARGS, (char *)"releases ownership of the pointer"}, - {(char *)"acquire", (PyCFunction)PySwigObject_acquire, METH_VARARGS, (char *)"aquires ownership of the pointer"}, - {(char *)"own", (PyCFunction)PySwigObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, - {(char *)"append", (PyCFunction)PySwigObject_append, METH_VARARGS, (char *)"appends another 'this' object"}, - {(char *)"next", (PyCFunction)PySwigObject_next, METH_VARARGS, (char *)"returns the next 'this' object"}, - {(char *)"__repr__",(PyCFunction)PySwigObject_repr, METH_VARARGS, (char *)"returns object representation"}, - {0, 0, 0, 0} -}; -#endif - -#if PY_VERSION_HEX < 0x02020000 -SWIGINTERN PyObject * -PySwigObject_getattr(PySwigObject *sobj,char *name) -{ - return Py_FindMethod(swigobject_methods, (PyObject *)sobj, name); -} -#endif - -SWIGRUNTIME PyTypeObject* -_PySwigObject_type(void) { - static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer"; - - static PyNumberMethods PySwigObject_as_number = { - (binaryfunc)0, /*nb_add*/ - (binaryfunc)0, /*nb_subtract*/ - (binaryfunc)0, /*nb_multiply*/ - (binaryfunc)0, /*nb_divide*/ - (binaryfunc)0, /*nb_remainder*/ - (binaryfunc)0, /*nb_divmod*/ - (ternaryfunc)0,/*nb_power*/ - (unaryfunc)0, /*nb_negative*/ - (unaryfunc)0, /*nb_positive*/ - (unaryfunc)0, /*nb_absolute*/ - (inquiry)0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - (coercion)0, /*nb_coerce*/ - (unaryfunc)PySwigObject_long, /*nb_int*/ - (unaryfunc)PySwigObject_long, /*nb_long*/ - (unaryfunc)0, /*nb_float*/ - (unaryfunc)PySwigObject_oct, /*nb_oct*/ - (unaryfunc)PySwigObject_hex, /*nb_hex*/ -#if PY_VERSION_HEX >= 0x02020000 - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_true_divide */ -#elif PY_VERSION_HEX >= 0x02000000 - 0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_or */ -#endif - }; - - static PyTypeObject pyswigobject_type; - static int type_init = 0; - if (!type_init) { - const PyTypeObject tmp - = { - PyObject_HEAD_INIT(NULL) - 0, /* ob_size */ - (char *)"PySwigObject", /* tp_name */ - sizeof(PySwigObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)PySwigObject_dealloc, /* tp_dealloc */ - (printfunc)PySwigObject_print, /* tp_print */ -#if PY_VERSION_HEX < 0x02020000 - (getattrfunc)PySwigObject_getattr, /* tp_getattr */ -#else - (getattrfunc)0, /* tp_getattr */ -#endif - (setattrfunc)0, /* tp_setattr */ - (cmpfunc)PySwigObject_compare, /* tp_compare */ - (reprfunc)PySwigObject_repr, /* tp_repr */ - &PySwigObject_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)0, /* tp_hash */ - (ternaryfunc)0, /* tp_call */ - (reprfunc)PySwigObject_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - swigobject_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ -#if PY_VERSION_HEX >= 0x02020000 - 0, /* tp_iter */ - 0, /* tp_iternext */ - swigobject_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ - 0, /* tp_is_gc */ - 0, /* tp_bases */ - 0, /* tp_mro */ - 0, /* tp_cache */ - 0, /* tp_subclasses */ - 0, /* tp_weaklist */ -#endif -#if PY_VERSION_HEX >= 0x02030000 - 0, /* tp_del */ -#endif -#ifdef COUNT_ALLOCS - 0,0,0,0 /* tp_alloc -> tp_next */ -#endif - }; - pyswigobject_type = tmp; - pyswigobject_type.ob_type = &PyType_Type; - type_init = 1; - } - return &pyswigobject_type; -} - -SWIGRUNTIME PyObject * -PySwigObject_New(void *ptr, swig_type_info *ty, int own) -{ - PySwigObject *sobj = PyObject_NEW(PySwigObject, PySwigObject_type()); - if (sobj) { - sobj->ptr = ptr; - sobj->ty = ty; - sobj->own = own; - sobj->next = 0; - } - return (PyObject *)sobj; -} - -/* ----------------------------------------------------------------------------- - * Implements a simple Swig Packed type, and use it instead of string - * ----------------------------------------------------------------------------- */ - -typedef struct { - PyObject_HEAD - void *pack; - swig_type_info *ty; - size_t size; -} PySwigPacked; - -SWIGRUNTIME int -PySwigPacked_print(PySwigPacked *v, FILE *fp, int SWIGUNUSEDPARM(flags)) -{ - char result[SWIG_BUFFER_SIZE]; - fputs("<Swig Packed ", fp); - if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { - fputs("at ", fp); - fputs(result, fp); - } - fputs(v->ty->name,fp); - fputs(">", fp); - return 0; -} - -SWIGRUNTIME PyObject * -PySwigPacked_repr(PySwigPacked *v) -{ - char result[SWIG_BUFFER_SIZE]; - if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { - return PyString_FromFormat("<Swig Packed at %s%s>", result, v->ty->name); - } else { - return PyString_FromFormat("<Swig Packed %s>", v->ty->name); - } -} - -SWIGRUNTIME PyObject * -PySwigPacked_str(PySwigPacked *v) -{ - char result[SWIG_BUFFER_SIZE]; - if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){ - return PyString_FromFormat("%s%s", result, v->ty->name); - } else { - return PyString_FromString(v->ty->name); - } -} - -SWIGRUNTIME int -PySwigPacked_compare(PySwigPacked *v, PySwigPacked *w) -{ - size_t i = v->size; - size_t j = w->size; - int s = (i < j) ? -1 : ((i > j) ? 1 : 0); - return s ? s : strncmp((char *)v->pack, (char *)w->pack, 2*v->size); -} - -SWIGRUNTIME PyTypeObject* _PySwigPacked_type(void); - -SWIGRUNTIME PyTypeObject* -PySwigPacked_type(void) { - static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigPacked_type(); - return type; -} - -SWIGRUNTIMEINLINE int -PySwigPacked_Check(PyObject *op) { - return ((op)->ob_type == _PySwigPacked_type()) - || (strcmp((op)->ob_type->tp_name,"PySwigPacked") == 0); -} - -SWIGRUNTIME void -PySwigPacked_dealloc(PyObject *v) -{ - if (PySwigPacked_Check(v)) { - PySwigPacked *sobj = (PySwigPacked *) v; - free(sobj->pack); - } - PyObject_DEL(v); -} - -SWIGRUNTIME PyTypeObject* -_PySwigPacked_type(void) { - static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer"; - static PyTypeObject pyswigpacked_type; - static int type_init = 0; - if (!type_init) { - const PyTypeObject tmp - = { - PyObject_HEAD_INIT(NULL) - 0, /* ob_size */ - (char *)"PySwigPacked", /* tp_name */ - sizeof(PySwigPacked), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)PySwigPacked_dealloc, /* tp_dealloc */ - (printfunc)PySwigPacked_print, /* tp_print */ - (getattrfunc)0, /* tp_getattr */ - (setattrfunc)0, /* tp_setattr */ - (cmpfunc)PySwigPacked_compare, /* tp_compare */ - (reprfunc)PySwigPacked_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)0, /* tp_hash */ - (ternaryfunc)0, /* tp_call */ - (reprfunc)PySwigPacked_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - swigpacked_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ -#if PY_VERSION_HEX >= 0x02020000 - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ - 0, /* tp_is_gc */ - 0, /* tp_bases */ - 0, /* tp_mro */ - 0, /* tp_cache */ - 0, /* tp_subclasses */ - 0, /* tp_weaklist */ -#endif -#if PY_VERSION_HEX >= 0x02030000 - 0, /* tp_del */ -#endif -#ifdef COUNT_ALLOCS - 0,0,0,0 /* tp_alloc -> tp_next */ -#endif - }; - pyswigpacked_type = tmp; - pyswigpacked_type.ob_type = &PyType_Type; - type_init = 1; - } - return &pyswigpacked_type; -} - -SWIGRUNTIME PyObject * -PySwigPacked_New(void *ptr, size_t size, swig_type_info *ty) -{ - PySwigPacked *sobj = PyObject_NEW(PySwigPacked, PySwigPacked_type()); - if (sobj) { - void *pack = malloc(size); - if (pack) { - memcpy(pack, ptr, size); - sobj->pack = pack; - sobj->ty = ty; - sobj->size = size; - } else { - PyObject_DEL((PyObject *) sobj); - sobj = 0; - } - } - return (PyObject *) sobj; -} - -SWIGRUNTIME swig_type_info * -PySwigPacked_UnpackData(PyObject *obj, void *ptr, size_t size) -{ - if (PySwigPacked_Check(obj)) { - PySwigPacked *sobj = (PySwigPacked *)obj; - if (sobj->size != size) return 0; - memcpy(ptr, sobj->pack, size); - return sobj->ty; - } else { - return 0; - } -} - -/* ----------------------------------------------------------------------------- - * pointers/data manipulation - * ----------------------------------------------------------------------------- */ - -SWIGRUNTIMEINLINE PyObject * -_SWIG_This(void) -{ - return PyString_FromString("this"); -} - -SWIGRUNTIME PyObject * -SWIG_This(void) -{ - static PyObject *SWIG_STATIC_POINTER(swig_this) = _SWIG_This(); - return swig_this; -} - -/* #define SWIG_PYTHON_SLOW_GETSET_THIS */ - -SWIGRUNTIME PySwigObject * -SWIG_Python_GetSwigThis(PyObject *pyobj) -{ - if (PySwigObject_Check(pyobj)) { - return (PySwigObject *) pyobj; - } else { - PyObject *obj = 0; -#if (!defined(SWIG_PYTHON_SLOW_GETSET_THIS) && (PY_VERSION_HEX >= 0x02030000)) - if (PyInstance_Check(pyobj)) { - obj = _PyInstance_Lookup(pyobj, SWIG_This()); - } else { - PyObject **dictptr = _PyObject_GetDictPtr(pyobj); - if (dictptr != NULL) { - PyObject *dict = *dictptr; - obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0; - } else { -#ifdef PyWeakref_CheckProxy - if (PyWeakref_CheckProxy(pyobj)) { - PyObject *wobj = PyWeakref_GET_OBJECT(pyobj); - return wobj ? SWIG_Python_GetSwigThis(wobj) : 0; - } -#endif - obj = PyObject_GetAttr(pyobj,SWIG_This()); - if (obj) { - Py_DECREF(obj); - } else { - if (PyErr_Occurred()) PyErr_Clear(); - return 0; - } - } - } -#else - obj = PyObject_GetAttr(pyobj,SWIG_This()); - if (obj) { - Py_DECREF(obj); - } else { - if (PyErr_Occurred()) PyErr_Clear(); - return 0; - } -#endif - if (obj && !PySwigObject_Check(obj)) { - /* a PyObject is called 'this', try to get the 'real this' - PySwigObject from it */ - return SWIG_Python_GetSwigThis(obj); - } - return (PySwigObject *)obj; - } ... [truncated message content] |
From: <jo...@us...> - 2009-07-18 08:36:04
|
Revision: 7270 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7270&view=rev Author: jouni Date: 2009-07-18 08:35:56 +0000 (Sat, 18 Jul 2009) Log Message: ----------- Fix support for hatches without color fills to pdf and svg backends. Add an example of that to hatch_demo.py. Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/examples/pylab_examples/hatch_demo.py trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py trunk/matplotlib/lib/matplotlib/backends/backend_svg.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-07-17 20:03:21 UTC (rev 7269) +++ trunk/matplotlib/CHANGELOG 2009-07-18 08:35:56 UTC (rev 7270) @@ -1,3 +1,6 @@ +2009-07-18 Fix support for hatches without color fills to pdf and svg + backends. Add an example of that to hatch_demo.py. - JKS + 2009-07-17 Removed fossils from swig version of agg backend. - EF 2009-07-14 initial submission of the annotation guide. -JJL Modified: trunk/matplotlib/examples/pylab_examples/hatch_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/hatch_demo.py 2009-07-17 20:03:21 UTC (rev 7269) +++ trunk/matplotlib/examples/pylab_examples/hatch_demo.py 2009-07-18 08:35:56 UTC (rev 7270) @@ -3,18 +3,29 @@ PDF, SVG and Agg backends only. """ import matplotlib.pyplot as plt +from matplotlib.patches import Ellipse, Polygon fig = plt.figure() -ax1 = fig.add_subplot(121) +ax1 = fig.add_subplot(131) ax1.bar(range(1,5), range(1,5), color='red', edgecolor='black', hatch="/") ax1.bar(range(1,5), [6] * 4, bottom=range(1,5), color='blue', edgecolor='black', hatch='//') +ax1.set_xticks([1.5,2.5,3.5,4.5]) -ax2 = fig.add_subplot(122) +ax2 = fig.add_subplot(132) bars = ax2.bar(range(1,5), range(1,5), color='yellow', ecolor='black') + \ ax2.bar(range(1, 5), [6] * 4, bottom=range(1,5), color='green', ecolor='black') +ax2.set_xticks([1.5,2.5,3.5,4.5]) patterns = ('-', '+', 'x', '\\', '*', 'o', 'O', '.') for bar, pattern in zip(bars, patterns): bar.set_hatch(pattern) +ax3 = fig.add_subplot(133) +ax3.fill([1,3,3,1],[1,1,2,2], fill=False, hatch='\\') +ax3.add_patch(Ellipse((4,1.5), 4, 0.5, fill=False, hatch='*')) +ax3.add_patch(Polygon([[0,0],[4,1.1],[6,2.5],[2,1.4]], closed=True, + fill=False, hatch='/')) +ax3.set_xlim((0,6)) +ax3.set_ylim((0,2.5)) + plt.show() Modified: trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py =================================================================== --- trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py 2009-07-17 20:03:21 UTC (rev 7269) +++ trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py 2009-07-18 08:35:56 UTC (rev 7270) @@ -1715,14 +1715,27 @@ return `d` def _strokep(self): + """ + Predicate: does the path need to be stroked (its outline drawn)? + This tests for the various conditions that disable stroking + the path, in which case it would presumably be filled. + """ return (self._linewidth > 0 and self._alpha > 0 and (len(self._rgb) <= 3 or self._rgb[3] != 0.0)) def _fillp(self): - return ((self._fillcolor is not None or self._hatch) and - (len(self._fillcolor) <= 3 or self._fillcolor[3] != 0.0)) + """ + Predicate: does the path need to be filled? + """ + return self._hatch or \ + (self._fillcolor is not None and + (len(self._fillcolor) <= 3 or self._fillcolor[3] != 0.0)) def close_and_paint(self): + """ + Return the appropriate pdf operator to close the path and + cause it to be stroked, filled, or both. + """ if self._strokep(): if self._fillp(): return Op.close_fill_stroke @@ -1735,6 +1748,10 @@ return Op.endpath def paint(self): + """ + Return the appropriate pdf operator to cause the path to be + stroked, filled, or both. + """ if self._strokep(): if self._fillp(): return Op.fill_stroke Modified: trunk/matplotlib/lib/matplotlib/backends/backend_svg.py =================================================================== --- trunk/matplotlib/lib/matplotlib/backends/backend_svg.py 2009-07-17 20:03:21 UTC (rev 7269) +++ trunk/matplotlib/lib/matplotlib/backends/backend_svg.py 2009-07-18 08:35:56 UTC (rev 7270) @@ -102,9 +102,13 @@ path_data = self._convert_path( gc.get_hatch_path(), Affine2D().scale(HATCH_SIZE).scale(1.0, -1.0).translate(0, HATCH_SIZE)) + if rgbFace is None: + fill = 'none' + else: + fill = rgb2hex(rgbFace) self._svgwriter.write( '<rect x="0" y="0" width="%d" height="%d" fill="%s"/>' % - (HATCH_SIZE+1, HATCH_SIZE+1, rgb2hex(rgbFace))) + (HATCH_SIZE+1, HATCH_SIZE+1, fill)) path = '<path d="%s" fill="%s" stroke="%s" stroke-width="1.0"/>' % ( path_data, rgb2hex(gc.get_rgb()[:3]), rgb2hex(gc.get_rgb()[:3])) self._svgwriter.write(path) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2009-07-19 13:35:17
|
Revision: 7272 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7272&view=rev Author: jdh2358 Date: 2009-07-19 13:35:15 +0000 (Sun, 19 Jul 2009) Log Message: ----------- fixed Axes.step docstring per sf bug 2823304 Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/axes.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-07-19 10:15:57 UTC (rev 7271) +++ trunk/matplotlib/CHANGELOG 2009-07-19 13:35:15 UTC (rev 7272) @@ -1,3 +1,8 @@ +2009-07-19 Fixed the docstring of Axes.step to reflect the correct + meaning of the kwargs "pre" and "post" - See SF bug + https://sourceforge.net/tracker/index.php?func=detail&aid=2823304&group_id=80706&atid=560720 + - JDH + 2009-07-18 Fix support for hatches without color fills to pdf and svg backends. Add an example of that to hatch_demo.py. - JKS Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2009-07-19 10:15:57 UTC (rev 7271) +++ trunk/matplotlib/lib/matplotlib/axes.py 2009-07-19 13:35:15 UTC (rev 7272) @@ -4109,9 +4109,9 @@ Keyword arguments: *where*: [ 'pre' | 'post' | 'mid' ] - If 'pre', the interval from x[i] to x[i+1] has level y[i] + If 'pre', the interval from x[i] to x[i+1] has level y[i+1] - If 'post', that interval has level y[i+1] + If 'post', that interval has level y[i] If 'mid', the jumps in *y* occur half-way between the *x*-values. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jo...@us...> - 2009-07-22 13:08:44
|
Revision: 7282 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7282&view=rev Author: jouni Date: 2009-07-22 13:08:41 +0000 (Wed, 22 Jul 2009) Log Message: ----------- Improved boilerplate.py so that it generates the correct signatures for pyplot functions. Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/boilerplate.py trunk/matplotlib/lib/matplotlib/pyplot.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-07-22 10:54:35 UTC (rev 7281) +++ trunk/matplotlib/CHANGELOG 2009-07-22 13:08:41 UTC (rev 7282) @@ -1,3 +1,6 @@ +2009-07-22 Improved boilerplate.py so that it generates the correct + signatures for pyplot functions. - JKS + 2009-07-19 Fixed the docstring of Axes.step to reflect the correct meaning of the kwargs "pre" and "post" - See SF bug https://sourceforge.net/tracker/index.php?func=detail&aid=2823304&group_id=80706&atid=560720 Modified: trunk/matplotlib/boilerplate.py =================================================================== --- trunk/matplotlib/boilerplate.py 2009-07-22 10:54:35 UTC (rev 7281) +++ trunk/matplotlib/boilerplate.py 2009-07-22 13:08:41 UTC (rev 7282) @@ -1,47 +1,50 @@ -# wrap the plot commands defined in axes. The code generated by this +# Wrap the plot commands defined in axes. The code generated by this # file is pasted into pylab.py. We did try to do this the smart way, # with callable functions and new.function, but could never get the # docstrings right for python2.2. See # http://groups.google.com/group/comp.lang.python/browse_frm/thread/dcd63ec13096a0f6/1b14640f3a4ad3dc?#1b14640f3a4ad3dc +# For some later history, see +# http://thread.gmane.org/gmane.comp.python.matplotlib.devel/7068 +import inspect +import random +import re +import sys +import types -# note we check for __doc__ is not None since py2exe optimize removes -# the docstrings +# import the local copy of matplotlib, not the installed one +sys.path.insert(0, './lib') +from matplotlib.axes import Axes +from matplotlib.cbook import dedent _fmtplot = """\ # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost -def %(func)s(*args, **kwargs): +def %(func)s(%(argspec)s): + %(docstring)s + %(ax)s = gca() # allow callers to override the hold state by passing hold=True|False - b = ishold() - h = kwargs.pop('hold', None) - if h is not None: - hold(h) + %(washold)s = %(ax)s.ishold() + %(sethold)s + if hold is not None: + %(ax)s.hold(hold) try: - ret = gca().%(func)s(*args, **kwargs) + %(ret)s = %(ax)s.%(func)s(%(call)s) draw_if_interactive() - except: - hold(b) - raise + finally: + %(ax)s.hold(%(washold)s) %(mappable)s - hold(b) - return ret -if Axes.%(func)s.__doc__ is not None: - %(func)s.__doc__ = dedent(Axes.%(func)s.__doc__) + \"\"\" - -Additional kwargs: hold = [True|False] overrides default hold state\"\"\" + return %(ret)s """ _fmtmisc = """\ # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost -def %(func)s(*args, **kwargs): - - ret = gca().%(func)s(*args, **kwargs) +def %(func)s(%(argspec)s): + %(docstring)s + %(ret)s = gca().%(func)s(%(call)s) draw_if_interactive() - return ret -if Axes.%(func)s.__doc__ is not None: - %(func)s.__doc__ = dedent(Axes.%(func)s.__doc__) + return %(ret)s """ # these methods are all simple wrappers of Axes methods by the same @@ -101,33 +104,113 @@ ) cmappable = { - 'contour' : 'if ret._A is not None: gci._current = ret', - 'contourf': 'if ret._A is not None: gci._current = ret', - 'hexbin' : 'gci._current = ret[0]', - 'scatter' : 'gci._current = ret', - 'pcolor' : 'gci._current = ret', - 'pcolormesh' : 'gci._current = ret', - 'imshow' : 'gci._current = ret', - 'spy' : 'gci._current = ret', - 'quiver' : 'gci._current = ret', - 'specgram' : 'gci._current = ret[-1]', + 'contour' : 'if %(ret)s._A is not None: gci._current = %(ret)s', + 'contourf': 'if %(ret)s._A is not None: gci._current = %(ret)s', + 'hexbin' : 'gci._current = %(ret)s', + 'scatter' : 'gci._current = %(ret)s', + 'pcolor' : 'gci._current = %(ret)s', + 'pcolormesh' : 'gci._current = %(ret)s', + 'imshow' : 'gci._current = %(ret)s', + 'spy' : 'gci._current = %(ret)s', + 'quiver' : 'gci._current = %(ret)s', + 'specgram' : 'gci._current = %(ret)s[-1]', } +def format_value(value): + """ + Format function default values as needed for inspect.formatargspec. + The interesting part is a hard-coded list of functions used + as defaults in pyplot methods. + """ + if isinstance(value, types.FunctionType): + if value.func_name in ('detrend_none', 'window_hanning'): + return '=mlab.' + value.func_name + if value.func_name == 'mean': + return '=np.' + value.func_name + raise ValueError, ('default value %s unknown to boilerplate.formatvalue' + % value) + return '='+repr(value) -for func in _plotcommands: - if func in cmappable: - mappable = cmappable[func] - else: - mappable = '' - print _fmtplot%locals() +def remove_final_whitespace(string): + """ + Return a copy of *string* with final whitespace removed from each line. + """ + return '\n'.join(x.rstrip() for x in string.split('\n')) +def make_docstring(cmd, mention_hold): + func = getattr(Axes, cmd) + docstring = inspect.getdoc(func) + if docstring is None: + return "" + escaped = re.sub(r'\\', r'\\\\', docstring) + if mention_hold: + escaped += ''' -for func in _misccommands: - print _fmtmisc%locals() +Additional kwargs: hold = [True|False] overrides default hold state +''' + return '"""'+escaped+'"""' +for fmt,cmdlist in (_fmtplot,_plotcommands),(_fmtmisc,_misccommands): + for func in cmdlist: + # For some commands, an additional line is needed to set the + # color map + if func in cmappable: + mappable = cmappable[func] % locals() + else: + mappable = '' + # Format docstring + docstring = make_docstring(func, fmt is _fmtplot) + # Get argspec of wrapped function + args, varargs, varkw, defaults = inspect.getargspec(getattr(Axes, func)) + args.pop(0) # remove 'self' argument + if defaults is None: + defaults = () + + # How to call the wrapped function + call = map(str, args) + if varargs is not None: + call.append('*'+varargs) + if varkw is not None: + call.append('**'+varkw) + call = ', '.join(call) + + # Add a hold keyword argument if needed (fmt is _fmtplot) and + # possible (if *args is used, we can't just add a hold + # argument in front of it since it would gobble one of the + # arguments the user means to pass via *args) + if varargs: + sethold = "hold = %(varkw)s.pop('hold', None)" % locals() + elif fmt is _fmtplot: + args.append('hold') + defaults = defaults + (None,) + sethold = '' + + # Now we can build the argspec for defining the wrapper + argspec = inspect.formatargspec(args, varargs, varkw, defaults, + formatvalue=format_value) + argspec = argspec[1:-1] # remove parens + + # A gensym-like facility in case some function takes an + # argument named washold, ax, or ret + washold,ret,ax = 'washold', 'ret', 'ax' + bad = set(args) | set((varargs, varkw)) + while washold in bad or ret in bad or ax in bad: + washold = 'washold' + str(random.randrange(10**12)) + ret = 'ret' + str(random.randrange(10**12)) + ax = 'ax' + str(random.randrange(10**12)) + + # Since we can't avoid using some function names, + # bail out if they are used as argument names + for reserved in ('gca', 'gci', 'draw_if_interactive'): + if reserved in bad: + raise ValueError, \ + 'Axes method %s has kwarg named %s' % (func, reserved) + + print remove_final_whitespace(fmt%locals()) + # define the colormap functions _fmtcmap = """\ # This function was autogenerated by boilerplate.py. Do not edit as Modified: trunk/matplotlib/lib/matplotlib/pyplot.py =================================================================== --- trunk/matplotlib/lib/matplotlib/pyplot.py 2009-07-22 10:54:35 UTC (rev 7281) +++ trunk/matplotlib/lib/matplotlib/pyplot.py 2009-07-22 13:08:41 UTC (rev 7282) @@ -13,12 +13,14 @@ from matplotlib.artist import setp as _setp from matplotlib.axes import Axes from matplotlib.projections import PolarAxes -from matplotlib import mlab # for csv2rec in plotfile +from matplotlib import mlab # for csv2rec, detrend_none, window_hanning from matplotlib.scale import get_scale_docs, get_scale_names from matplotlib import cm from matplotlib.cm import get_cmap +import numpy as np + # We may not need the following imports here: from matplotlib.colors import Normalize, normalize # latter for backwards compat. from matplotlib.lines import Line2D @@ -1593,987 +1595,5048 @@ # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost -def acorr(*args, **kwargs): +def acorr(x, hold=None, **kwargs): + """call signature:: + + acorr(x, normed=True, detrend=mlab.detrend_none, usevlines=True, + maxlags=10, **kwargs) + +Plot the autocorrelation of *x*. If *normed* = *True*, +normalize the data by the autocorrelation at 0-th lag. *x* is +detrended by the *detrend* callable (default no normalization). + +Data are plotted as ``plot(lags, c, **kwargs)`` + +Return value is a tuple (*lags*, *c*, *line*) where: + + - *lags* are a length 2*maxlags+1 lag vector + + - *c* is the 2*maxlags+1 auto correlation vector + + - *line* is a :class:`~matplotlib.lines.Line2D` instance + returned by :meth:`plot` + +The default *linestyle* is None and the default *marker* is +``'o'``, though these can be overridden with keyword args. +The cross correlation is performed with +:func:`numpy.correlate` with *mode* = 2. + +If *usevlines* is *True*, :meth:`~matplotlib.axes.Axes.vlines` +rather than :meth:`~matplotlib.axes.Axes.plot` is used to draw +vertical lines from the origin to the acorr. Otherwise, the +plot style is determined by the kwargs, which are +:class:`~matplotlib.lines.Line2D` properties. + +*maxlags* is a positive integer detailing the number of lags +to show. The default value of *None* will return all +:math:`2 \\mathrm{len}(x) - 1` lags. + +The return value is a tuple (*lags*, *c*, *linecol*, *b*) +where + +- *linecol* is the + :class:`~matplotlib.collections.LineCollection` + +- *b* is the *x*-axis. + +.. seealso:: + + :meth:`~matplotlib.axes.Axes.plot` or + :meth:`~matplotlib.axes.Axes.vlines` + For documentation on valid kwargs. + +**Example:** + +:func:`~matplotlib.pyplot.xcorr` above, and +:func:`~matplotlib.pyplot.acorr` below. + +**Example:** + +.. plot:: mpl_examples/pylab_examples/xcorr_demo.py + +Additional kwargs: hold = [True|False] overrides default hold state +""" + ax = gca() # allow callers to override the hold state by passing hold=True|False - b = ishold() - h = kwargs.pop('hold', None) - if h is not None: - hold(h) + washold = ax.ishold() + + if hold is not None: + ax.hold(hold) try: - ret = gca().acorr(*args, **kwargs) + ret = ax.acorr(x, **kwargs) draw_if_interactive() - except: - hold(b) - raise + finally: + ax.hold(washold) - hold(b) return ret -if Axes.acorr.__doc__ is not None: - acorr.__doc__ = dedent(Axes.acorr.__doc__) + """ -Additional kwargs: hold = [True|False] overrides default hold state""" - # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost -def arrow(*args, **kwargs): +def arrow(x, y, dx, dy, hold=None, **kwargs): + """call signature:: + + arrow(x, y, dx, dy, **kwargs) + +Draws arrow on specified axis from (*x*, *y*) to (*x* + *dx*, +*y* + *dy*). + +Optional kwargs control the arrow properties: + alpha: float (0.0 transparent through 1.0 opaque) + animated: [True | False] + antialiased or aa: [True | False] or None for default + axes: an :class:`~matplotlib.axes.Axes` instance + clip_box: a :class:`matplotlib.transforms.Bbox` instance + clip_on: [True | False] + clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] + color: matplotlib color arg or sequence of rgba tuples + contains: a callable function + edgecolor or ec: mpl color spec, or None for default, or 'none' for no color + facecolor or fc: mpl color spec, or None for default, or 'none' for no color + figure: a :class:`matplotlib.figure.Figure` instance + fill: [True | False] + gid: an id string + hatch: [ '/' | '\\\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*' ] + label: any string + linestyle or ls: ['solid' | 'dashed' | 'dashdot' | 'dotted'] + linewidth or lw: float or None for default + lod: [True | False] + picker: [None|float|boolean|callable] + rasterized: [True | False | None] + snap: unknown + transform: :class:`~matplotlib.transforms.Transform` instance + url: a url string + visible: [True | False] + zorder: any number + +**Example:** + +.. plot:: mpl_examples/pylab_examples/arrow_demo.py + +Additional kwargs: hold = [True|False] overrides default hold state +""" + ax = gca() # allow callers to override the hold state by passing hold=True|False - b = ishold() - h = kwargs.pop('hold', None) - if h is not None: - hold(h) + washold = ax.ishold() + + if hold is not None: + ax.hold(hold) try: - ret = gca().arrow(*args, **kwargs) + ret = ax.arrow(x, y, dx, dy, **kwargs) draw_if_interactive() - except: - hold(b) - raise + finally: + ax.hold(washold) - hold(b) return ret -if Axes.arrow.__doc__ is not None: - arrow.__doc__ = dedent(Axes.arrow.__doc__) + """ -Additional kwargs: hold = [True|False] overrides default hold state""" - # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost -def axhline(*args, **kwargs): +def axhline(y=0, xmin=0, xmax=1, hold=None, **kwargs): + """call signature:: + + axhline(y=0, xmin=0, xmax=1, **kwargs) + +Axis Horizontal Line + +Draw a horizontal line at *y* from *xmin* to *xmax*. With the +default values of *xmin* = 0 and *xmax* = 1, this line will +always span the horizontal extent of the axes, regardless of +the xlim settings, even if you change them, eg. with the +:meth:`set_xlim` command. That is, the horizontal extent is +in axes coords: 0=left, 0.5=middle, 1.0=right but the *y* +location is in data coordinates. + +Return value is the :class:`~matplotlib.lines.Line2D` +instance. kwargs are the same as kwargs to plot, and can be +used to control the line properties. Eg., + +* draw a thick red hline at *y* = 0 that spans the xrange + + >>> axhline(linewidth=4, color='r') + +* draw a default hline at *y* = 1 that spans the xrange + + >>> axhline(y=1) + +* draw a default hline at *y* = .5 that spans the the middle half of + the xrange + + >>> axhline(y=.5, xmin=0.25, xmax=0.75) + +Valid kwargs are :class:`~matplotlib.lines.Line2D` properties: + + alpha: float (0.0 transparent through 1.0 opaque) + animated: [True | False] + antialiased or aa: [True | False] + axes: an :class:`~matplotlib.axes.Axes` instance + clip_box: a :class:`matplotlib.transforms.Bbox` instance + clip_on: [True | False] + clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] + color or c: any matplotlib color + contains: a callable function + dash_capstyle: ['butt' | 'round' | 'projecting'] + dash_joinstyle: ['miter' | 'round' | 'bevel'] + dashes: sequence of on/off ink in points + data: 2D array + drawstyle: [ 'default' | 'steps' | 'steps-pre' | 'steps-mid' | 'steps-post' ] + figure: a :class:`matplotlib.figure.Figure` instance + fillstyle: ['full' | 'left' | 'right' | 'bottom' | 'top'] + gid: an id string + label: any string + linestyle or ls: [ '-' | '--' | '-.' | ':' | 'None' | ' ' | '' ] and any drawstyle in combination with a linestyle, e.g. 'steps--'. + linewidth or lw: float value in points + lod: [True | False] + marker: [ '+' | '*' | ',' | '.' | '1' | '2' | '3' | '4' | '<' | '>' | 'D' | 'H' | '^' | '_' | 'd' | 'h' | 'o' | 'p' | 's' | 'v' | 'x' | '|' | TICKUP | TICKDOWN | TICKLEFT | TICKRIGHT | 'None' | ' ' | '' ] + markeredgecolor or mec: any matplotlib color + markeredgewidth or mew: float value in points + markerfacecolor or mfc: any matplotlib color + markersize or ms: float + markevery: None | integer | (startind, stride) + picker: float distance in points or callable pick function ``fn(artist, event)`` + pickradius: float distance in points + rasterized: [True | False | None] + snap: unknown + solid_capstyle: ['butt' | 'round' | 'projecting'] + solid_joinstyle: ['miter' | 'round' | 'bevel'] + transform: a :class:`matplotlib.transforms.Transform` instance + url: a url string + visible: [True | False] + xdata: 1D array + ydata: 1D array + zorder: any number + +.. seealso:: + + :meth:`axhspan` + for example plot and source code + +Additional kwargs: hold = [True|False] overrides default hold state +""" + ax = gca() # allow callers to override the hold state by passing hold=True|False - b = ishold() - h = kwargs.pop('hold', None) - if h is not None: - hold(h) + washold = ax.ishold() + + if hold is not None: + ax.hold(hold) try: - ret = gca().axhline(*args, **kwargs) + ret = ax.axhline(y, xmin, xmax, **kwargs) draw_if_interactive() - except: - hold(b) - raise + finally: + ax.hold(washold) - hold(b) return ret -if Axes.axhline.__doc__ is not None: - axhline.__doc__ = dedent(Axes.axhline.__doc__) + """ -Additional kwargs: hold = [True|False] overrides default hold state""" - # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost -def axhspan(*args, **kwargs): +def axhspan(ymin, ymax, xmin=0, xmax=1, hold=None, **kwargs): + """call signature:: + + axhspan(ymin, ymax, xmin=0, xmax=1, **kwargs) + +Axis Horizontal Span. + +*y* coords are in data units and *x* coords are in axes (relative +0-1) units. + +Draw a horizontal span (rectangle) from *ymin* to *ymax*. +With the default values of *xmin* = 0 and *xmax* = 1, this +always spans the xrange, regardless of the xlim settings, even +if you change them, eg. with the :meth:`set_xlim` command. +That is, the horizontal extent is in axes coords: 0=left, +0.5=middle, 1.0=right but the *y* location is in data +coordinates. + +Return value is a :class:`matplotlib.patches.Polygon` +instance. + +Examples: + +* draw a gray rectangle from *y* = 0.25-0.75 that spans the + horizontal extent of the axes + + >>> axhspan(0.25, 0.75, facecolor='0.5', alpha=0.5) + +Valid kwargs are :class:`~matplotlib.patches.Polygon` properties: + + alpha: float (0.0 transparent through 1.0 opaque) + animated: [True | False] + antialiased or aa: [True | False] or None for default + axes: an :class:`~matplotlib.axes.Axes` instance + clip_box: a :class:`matplotlib.transforms.Bbox` instance + clip_on: [True | False] + clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] + color: matplotlib color arg or sequence of rgba tuples + contains: a callable function + edgecolor or ec: mpl color spec, or None for default, or 'none' for no color + facecolor or fc: mpl color spec, or None for default, or 'none' for no color + figure: a :class:`matplotlib.figure.Figure` instance + fill: [True | False] + gid: an id string + hatch: [ '/' | '\\\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*' ] + label: any string + linestyle or ls: ['solid' | 'dashed' | 'dashdot' | 'dotted'] + linewidth or lw: float or None for default + lod: [True | False] + picker: [None|float|boolean|callable] + rasterized: [True | False | None] + snap: unknown + transform: :class:`~matplotlib.transforms.Transform` instance + url: a url string + visible: [True | False] + zorder: any number + +**Example:** + +.. plot:: mpl_examples/pylab_examples/axhspan_demo.py + +Additional kwargs: hold = [True|False] overrides default hold state +""" + ax = gca() # allow callers to override the hold state by passing hold=True|False - b = ishold() - h = kwargs.pop('hold', None) - if h is not None: - hold(h) + washold = ax.ishold() + + if hold is not None: + ax.hold(hold) try: - ret = gca().axhspan(*args, **kwargs) + ret = ax.axhspan(ymin, ymax, xmin, xmax, **kwargs) draw_if_interactive() - except: - hold(b) - raise + finally: + ax.hold(washold) - hold(b) return ret -if Axes.axhspan.__doc__ is not None: - axhspan.__doc__ = dedent(Axes.axhspan.__doc__) + """ -Additional kwargs: hold = [True|False] overrides default hold state""" - # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost -def axvline(*args, **kwargs): +def axvline(x=0, ymin=0, ymax=1, hold=None, **kwargs): + """call signature:: + + axvline(x=0, ymin=0, ymax=1, **kwargs) + +Axis Vertical Line + +Draw a vertical line at *x* from *ymin* to *ymax*. With the +default values of *ymin* = 0 and *ymax* = 1, this line will +always span the vertical extent of the axes, regardless of the +ylim settings, even if you change them, eg. with the +:meth:`set_ylim` command. That is, the vertical extent is in +axes coords: 0=bottom, 0.5=middle, 1.0=top but the *x* location +is in data coordinates. + +Return value is the :class:`~matplotlib.lines.Line2D` +instance. kwargs are the same as kwargs to plot, and can be +used to control the line properties. Eg., + +* draw a thick red vline at *x* = 0 that spans the yrange + + >>> axvline(linewidth=4, color='r') + +* draw a default vline at *x* = 1 that spans the yrange + + >>> axvline(x=1) + +* draw a default vline at *x* = .5 that spans the the middle half of + the yrange + + >>> axvline(x=.5, ymin=0.25, ymax=0.75) + +Valid kwargs are :class:`~matplotlib.lines.Line2D` properties: + + alpha: float (0.0 transparent through 1.0 opaque) + animated: [True | False] + antialiased or aa: [True | False] + axes: an :class:`~matplotlib.axes.Axes` instance + clip_box: a :class:`matplotlib.transforms.Bbox` instance + clip_on: [True | False] + clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] + color or c: any matplotlib color + contains: a callable function + dash_capstyle: ['butt' | 'round' | 'projecting'] + dash_joinstyle: ['miter' | 'round' | 'bevel'] + dashes: sequence of on/off ink in points + data: 2D array + drawstyle: [ 'default' | 'steps' | 'steps-pre' | 'steps-mid' | 'steps-post' ] + figure: a :class:`matplotlib.figure.Figure` instance + fillstyle: ['full' | 'left' | 'right' | 'bottom' | 'top'] + gid: an id string + label: any string + linestyle or ls: [ '-' | '--' | '-.' | ':' | 'None' | ' ' | '' ] and any drawstyle in combination with a linestyle, e.g. 'steps--'. + linewidth or lw: float value in points + lod: [True | False] + marker: [ '+' | '*' | ',' | '.' | '1' | '2' | '3' | '4' | '<' | '>' | 'D' | 'H' | '^' | '_' | 'd' | 'h' | 'o' | 'p' | 's' | 'v' | 'x' | '|' | TICKUP | TICKDOWN | TICKLEFT | TICKRIGHT | 'None' | ' ' | '' ] + markeredgecolor or mec: any matplotlib color + markeredgewidth or mew: float value in points + markerfacecolor or mfc: any matplotlib color + markersize or ms: float + markevery: None | integer | (startind, stride) + picker: float distance in points or callable pick function ``fn(artist, event)`` + pickradius: float distance in points + rasterized: [True | False | None] + snap: unknown + solid_capstyle: ['butt' | 'round' | 'projecting'] + solid_joinstyle: ['miter' | 'round' | 'bevel'] + transform: a :class:`matplotlib.transforms.Transform` instance + url: a url string + visible: [True | False] + xdata: 1D array + ydata: 1D array + zorder: any number + +.. seealso:: + + :meth:`axhspan` + for example plot and source code + +Additional kwargs: hold = [True|False] overrides default hold state +""" + ax = gca() # allow callers to override the hold state by passing hold=True|False - b = ishold() - h = kwargs.pop('hold', None) - if h is not None: - hold(h) + washold = ax.ishold() + + if hold is not None: + ax.hold(hold) try: - ret = gca().axvline(*args, **kwargs) + ret = ax.axvline(x, ymin, ymax, **kwargs) draw_if_interactive() - except: - hold(b) - raise + finally: + ax.hold(washold) - hold(b) return ret -if Axes.axvline.__doc__ is not None: - axvline.__doc__ = dedent(Axes.axvline.__doc__) + """ -Additional kwargs: hold = [True|False] overrides default hold state""" - # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost -def axvspan(*args, **kwargs): +def axvspan(xmin, xmax, ymin=0, ymax=1, hold=None, **kwargs): + """call signature:: + + axvspan(xmin, xmax, ymin=0, ymax=1, **kwargs) + +Axis Vertical Span. + +*x* coords are in data units and *y* coords are in axes (relative +0-1) units. + +Draw a vertical span (rectangle) from *xmin* to *xmax*. With +the default values of *ymin* = 0 and *ymax* = 1, this always +spans the yrange, regardless of the ylim settings, even if you +change them, eg. with the :meth:`set_ylim` command. That is, +the vertical extent is in axes coords: 0=bottom, 0.5=middle, +1.0=top but the *y* location is in data coordinates. + +Return value is the :class:`matplotlib.patches.Polygon` +instance. + +Examples: + +* draw a vertical green translucent rectangle from x=1.25 to 1.55 that + spans the yrange of the axes + + >>> axvspan(1.25, 1.55, facecolor='g', alpha=0.5) + +Valid kwargs are :class:`~matplotlib.patches.Polygon` +properties: + + alpha: float (0.0 transparent through 1.0 opaque) + animated: [True | False] + antialiased or aa: [True | False] or None for default + axes: an :class:`~matplotlib.axes.Axes` instance + clip_box: a :class:`matplotlib.transforms.Bbox` instance + clip_on: [True | False] + clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] + color: matplotlib color arg or sequence of rgba tuples + contains: a callable function + edgecolor or ec: mpl color spec, or None for default, or 'none' for no color + facecolor or fc: mpl color spec, or None for default, or 'none' for no color + figure: a :class:`matplotlib.figure.Figure` instance + fill: [True | False] + gid: an id string + hatch: [ '/' | '\\\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*' ] + label: any string + linestyle or ls: ['solid' | 'dashed' | 'dashdot' | 'dotted'] + linewidth or lw: float or None for default + lod: [True | False] + picker: [None|float|boolean|callable] + rasterized: [True | False | None] + snap: unknown + transform: :class:`~matplotlib.transforms.Transform` instance + url: a url string + visible: [True | False] + zorder: any number + +.. seealso:: + + :meth:`axhspan` + for example plot and source code + +Additional kwargs: hold = [True|False] overrides default hold state +""" + ax = gca() # allow callers to override the hold state by passing hold=True|False - b = ishold() - h = kwargs.pop('hold', None) - if h is not None: - hold(h) + washold = ax.ishold() + + if hold is not None: + ax.hold(hold) try: - ret = gca().axvspan(*args, **kwargs) + ret = ax.axvspan(xmin, xmax, ymin, ymax, **kwargs) draw_if_interactive() - except: - hold(b) - raise + finally: + ax.hold(washold) - hold(b) return ret -if Axes.axvspan.__doc__ is not None: - axvspan.__doc__ = dedent(Axes.axvspan.__doc__) + """ -Additional kwargs: hold = [True|False] overrides default hold state""" - # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost -def bar(*args, **kwargs): +def bar(left, height, width=0.80000000000000004, bottom=None, color=None, edgecolor=None, linewidth=None, yerr=None, xerr=None, ecolor=None, capsize=3, align='edge', orientation='vertical', log=False, hold=None, **kwargs): + """call signature:: + + bar(left, height, width=0.8, bottom=0, + color=None, edgecolor=None, linewidth=None, + yerr=None, xerr=None, ecolor=None, capsize=3, + align='edge', orientation='vertical', log=False) + +Make a bar plot with rectangles bounded by: + + *left*, *left* + *width*, *bottom*, *bottom* + *height* + (left, right, bottom and top edges) + +*left*, *height*, *width*, and *bottom* can be either scalars +or sequences + +Return value is a list of +:class:`matplotlib.patches.Rectangle` instances. + +Required arguments: + + ======== =============================================== + Argument Description + ======== =============================================== + *left* the x coordinates of the left sides of the bars + *height* the heights of the bars + ======== =============================================== + +Optional keyword arguments: + + =============== ========================================== + Keyword Description + =============== ========================================== + *width* the widths of the bars + *bottom* the y coordinates of the bottom edges of + the bars + *color* the colors of the bars + *edgecolor* the colors of the bar edges + *linewidth* width of bar edges; None means use default + linewidth; 0 means don't draw edges. + *xerr* if not None, will be used to generate + errorbars on the bar chart + *yerr* if not None, will be used to generate + errorbars on the bar chart + *ecolor* specifies the color of any errorbar + *capsize* (default 3) determines the length in + points of the error bar caps + *align* 'edge' (default) | 'center' + *orientation* 'vertical' | 'horizontal' + *log* [False|True] False (default) leaves the + orientation axis as-is; True sets it to + log scale + =============== ========================================== + +For vertical bars, *align* = 'edge' aligns bars by their left +edges in left, while *align* = 'center' interprets these +values as the *x* coordinates of the bar centers. For +horizontal bars, *align* = 'edge' aligns bars by their bottom +edges in bottom, while *align* = 'center' interprets these +values as the *y* coordinates of the bar centers. + +The optional arguments *color*, *edgecolor*, *linewidth*, +*xerr*, and *yerr* can be either scalars or sequences of +length equal to the number of bars. This enables you to use +bar as the basis for stacked bar charts, or candlestick plots. + +Other optional kwargs: + + alpha: float (0.0 transparent through 1.0 opaque) + animated: [True | False] + antialiased or aa: [True | False] or None for default + axes: an :class:`~matplotlib.axes.Axes` instance + clip_box: a :class:`matplotlib.transforms.Bbox` instance + clip_on: [True | False] + clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] + color: matplotlib color arg or sequence of rgba tuples + contains: a callable function + edgecolor or ec: mpl color spec, or None for default, or 'none' for no color + facecolor or fc: mpl color spec, or None for default, or 'none' for no color + figure: a :class:`matplotlib.figure.Figure` instance + fill: [True | False] + gid: an id string + hatch: [ '/' | '\\\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*' ] + label: any string + linestyle or ls: ['solid' | 'dashed' | 'dashdot' | 'dotted'] + linewidth or lw: float or None for default + lod: [True | False] + picker: [None|float|boolean|callable] + rasterized: [True | False | None] + snap: unknown + transform: :class:`~matplotlib.transforms.Transform` instance + url: a url string + visible: [True | False] + zorder: any number + +**Example:** A stacked bar chart. + +.. plot:: mpl_examples/pylab_examples/bar_stacked.py + +Additional kwargs: hold = [True|False] overrides default hold state +""" + ax = gca() # allow callers to override the hold state by passing hold=True|False - b = ishold() - h = kwargs.pop('hold', None) - if h is not None: - hold(h) + washold = ax.ishold() + + if hold is not None: + ax.hold(hold) try: - ret = gca().bar(*args, **kwargs) + ret = ax.bar(left, height, width, bottom, color, edgecolor, linewidth, yerr, xerr, ecolor, capsize, align, orientation, log, **kwargs) draw_if_interactive() - except: - hold(b) - raise + finally: + ax.hold(washold) - hold(b) return ret -if Axes.bar.__doc__ is not None: - bar.__doc__ = dedent(Axes.bar.__doc__) + """ -Additional kwargs: hold = [True|False] overrides default hold state""" - # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost -def barh(*args, **kwargs): +def barh(bottom, width, height=0.80000000000000004, left=None, hold=None, **kwargs): + """call signature:: + + barh(bottom, width, height=0.8, left=0, **kwargs) + +Make a horizontal bar plot with rectangles bounded by: + + *left*, *left* + *width*, *bottom*, *bottom* + *height* + (left, right, bottom and top edges) + +*bottom*, *width*, *height*, and *left* can be either scalars +or sequences + +Return value is a list of +:class:`matplotlib.patches.Rectangle` instances. + +Required arguments: + + ======== ====================================================== + Argument Description + ======== ====================================================== + *bottom* the vertical positions of the bottom edges of the bars + *width* the lengths of the bars + ======== ====================================================== + +Optional keyword arguments: + + =============== ========================================== + Keyword Description + =============== ========================================== + *height* the heights (thicknesses) of the bars + *left* the x coordinates of the left edges of the + bars + *color* the colors of the bars + *edgecolor* the colors of the bar edges + *linewidth* width of bar edges; None means use default + linewidth; 0 means don't draw edges. + *xerr* if not None, will be used to generate + errorbars on the bar chart + *yerr* if not None, will be used to generate + errorbars on the bar chart + *ecolor* specifies the color of any errorbar + *capsize* (default 3) determines the length in + points of the error bar caps + *align* 'edge' (default) | 'center' + *log* [False|True] False (default) leaves the + horizontal axis as-is; True sets it to log + scale + =============== ========================================== + +Setting *align* = 'edge' aligns bars by their bottom edges in +bottom, while *align* = 'center' interprets these values as +the *y* coordinates of the bar centers. + +The optional arguments *color*, *edgecolor*, *linewidth*, +*xerr*, and *yerr* can be either scalars or sequences of +length equal to the number of bars. This enables you to use +barh as the basis for stacked bar charts, or candlestick +plots. + +other optional kwargs: + + alpha: float (0.0 transparent through 1.0 opaque) + animated: [True | False] + antialiased or aa: [True | False] or None for default + axes: an :class:`~matplotlib.axes.Axes` instance + clip_box: a :class:`matplotlib.transforms.Bbox` instance + clip_on: [True | False] + clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] + color: matplotlib color arg or sequence of rgba tuples + contains: a callable function + edgecolor or ec: mpl color spec, or None for default, or 'none' for no color + facecolor or fc: mpl color spec, or None for default, or 'none' for no color + figure: a :class:`matplotlib.figure.Figure` instance + fill: [True | False] + gid: an id string + hatch: [ '/' | '\\\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*' ] + label: any string + linestyle or ls: ['solid' | 'dashed' | 'dashdot' | 'dotted'] + linewidth or lw: float or None for default + lod: [True | False] + picker: [None|float|boolean|callable] + rasterized: [True | False | None] + snap: unknown + transform: :class:`~matplotlib.transforms.Transform` instance + url: a url string + visible: [True | False] + zorder: any number + +Additional kwargs: hold = [True|False] overrides default hold state +""" + ax = gca() # allow callers to override the hold state by passing hold=True|False - b = ishold() - h = kwargs.pop('hold', None) - if h is not None: - hold(h) + washold = ax.ishold() + + if hold is not None: + ax.hold(hold) try: - ret = gca().barh(*args, **kwargs) + ret = ax.barh(bottom, width, height, left, **kwargs) draw_if_interactive() - except: - hold(b) - raise + finally: + ax.hold(washold) - hold(b) return ret -if Axes.barh.__doc__ is not None: - barh.__doc__ = dedent(Axes.barh.__doc__) + """ -Additional kwargs: hold = [True|False] overrides default hold state""" - # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost -def broken_barh(*args, **kwargs): +def broken_barh(xranges, yrange, hold=None, **kwargs): + """call signature:: + + broken_barh(self, xranges, yrange, **kwargs) + +A collection of horizontal bars spanning *yrange* with a sequence of +*xranges*. + +Required arguments: + + ========= ============================== + Argument Description + ========= ============================== + *xranges* sequence of (*xmin*, *xwidth*) + *yrange* sequence of (*ymin*, *ywidth*) + ========= ============================== + +kwargs are +:class:`matplotlib.collections.BrokenBarHCollection` +properties: + + alpha: float + animated: [True | False] + antialiased or antialiaseds: Boolean or sequence of booleans + array: unknown + axes: an :class:`~matplotlib.axes.Axes` instance + clim: a length 2 sequence of floats + clip_box: a :class:`matplotlib.transforms.Bbox` instance + clip_on: [True | False] + clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] + cmap: a colormap + color: matplotlib color arg or sequence of rgba tuples + colorbar: unknown + contains: a callable function + edgecolor or edgecolors: matplotlib color arg or sequence of rgba tuples + facecolor or facecolors: matplotlib color arg or sequence of rgba tuples + figure: a :class:`matplotlib.figure.Figure` instance + gid: an id string + label: any string + linestyle or linestyles or dashes: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq) ] + linewidth or lw or linewidths: float or sequence of floats + lod: [True | False] + norm: unknown + offsets: float or sequence of floats + picker: [None|float|boolean|callable] + pickradius: unknown + rasterized: [True | False | None] + snap: unknown + transform: :class:`~matplotlib.transforms.Transform` instance + url: a url string + urls: unknown + visible: [True | False] + zorder: any number + +these can either be a single argument, ie:: + + facecolors = 'black' + +or a sequence of arguments for the various bars, ie:: + + facecolors = ('black', 'red', 'green') + +**Example:** + +.. plot:: mpl_examples/pylab_examples/broken_barh.py + +Additional kwargs: hold = [True|False] overrides default hold state +""" + ax = gca() # allow callers to override the hold state by passing hold=True|False - b = ishold() - h = kwargs.pop('hold', None) - if h is not None: - hold(h) + washold = ax.ishold() + + if hold is not None: + ax.hold(hold) try: - ret = gca().broken_barh(*args, **kwargs) + ret = ax.broken_barh(xranges, yrange, **kwargs) draw_if_interactive() - except: - hold(b) - raise + finally: + ax.hold(washold) - hold(b) return ret -if Axes.broken_barh.__doc__ is not None: - broken_barh.__doc__ = dedent(Axes.broken_barh.__doc__) + """ -Additional kwargs: hold = [True|False] overrides default hold state""" - # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost -def boxplot(*args, **kwargs): +def boxplot(x, notch=0, sym='b+', vert=1, whis=1.5, positions=None, widths=None, hold=None): + """call signature:: + + boxplot(x, notch=0, sym='+', vert=1, whis=1.5, + positions=None, widths=None) + +Make a box and whisker plot for each column of *x* or each +vector in sequence *x*. The box extends from the lower to +upper quartile values of the data, with a line at the median. +The whiskers extend from the box to show the range of the +data. Flier points are those past the end of the whiskers. + +- *notch* = 0 (default) produces a rectangular box plot. +- *notch* = 1 will produce a notched box plot + +*sym* (default 'b+') is the default symbol for flier points. +Enter an empty string ('') if you don't want to show fliers. + +- *vert* = 1 (default) makes the boxes vertical. +- *vert* = 0 makes horizontal boxes. This seems goofy, but + that's how Matlab did it. + +*whis* (default 1.5) defines the length of the whiskers as +a function of the inner quartile range. They extend to the +most extreme data point within ( ``whis*(75%-25%)`` ) data range. + +*positions* (default 1,2,...,n) sets the horizontal positions of +the boxes. The ticks and limits are automatically set to match +the positions. + +*widths* is either a scalar or a vector and sets the width of +each box. The default is 0.5, or ``0.15*(distance between extreme +positions)`` if that is smaller. + +*x* is an array or a sequence of vectors. + +Returns a dictionary mapping each component of the boxplot +to a list of the :class:`matplotlib.lines.Line2D` +instances created. + +**Example:** + +.. plot:: pyplots/boxplot_demo.py + +Additional kwargs: hold = [True|False] overrides default hold state +""" + ax = gca() # allow callers to override the hold state by passing hold=True|False - b = ishold() - h = kwargs.pop('hold', None) - if h is not None: - hold(h) + washold = ax.ishold() + + if hold is not None: + ax.hold(hold) try: - ret = gca().boxplot(*args, **kwargs) + ret = ax.boxplot(x, notch, sym, vert, whis, positions, widths) draw_if_interactive() - except: - hold(b) - raise + finally: + ax.hold(washold) - hold(b) return ret -if Axes.boxplot.__doc__ is not None: - boxplot.__doc__ = dedent(Axes.boxplot.__doc__) + """ -Additional kwargs: hold = [True|False] overrides default hold state""" - # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost -def cohere(*args, **kwargs): +def cohere(x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, window=mlab.window_hanning, noverlap=0, pad_to=None, sides='default', scale_by_freq=None, hold=None, **kwargs): + """call signature:: + + cohere(x, y, NFFT=256, Fs=2, Fc=0, detrend = mlab.detrend_none, + window = mlab.window_hanning, noverlap=0, pad_to=None, + sides='default', scale_by_freq=None, **kwargs) + +cohere the coherence between *x* and *y*. Coherence is the normalized +cross spectral density: + +.. math:: + + C_{xy} = \\frac{|P_{xy}|^2}{P_{xx}P_{yy}} + +Keyword arguments: + + *NFFT*: integer + The number of data points used in each block for the FFT. + Must be even; a power 2 is most efficient. The default value is 256. + + *Fs*: scalar + The sampling frequency (samples per time unit). It is used + to calculate the Fourier frequencies, freqs, in cycles per time + unit. The default value is 2. + + *detrend*: callable + The function applied to each segment before fft-ing, + designed to remove the mean or linear trend. Unlike in + matlab, where the *detrend* parameter is a vector, in + matplotlib is it a function. The :mod:`~matplotlib.pylab` + module defines :func:`~matplotlib.pylab.detrend_none`, + :func:`~matplotlib.pylab.detrend_mean`, and + :func:`~matplotlib.pylab.detrend_linear`, but you can use + a custom function as well. + + *window*: callable or ndarray + A function or a vector of length *NFFT*. To create window + vectors see :func:`window_hanning`, :func:`window_none`, + :func:`numpy.blackman`, :func:`numpy.hamming`, + :func:`numpy.bartlett`, :func:`scipy.signal`, + :func:`scipy.signal.get_window`, etc. The default is + :func:`window_hanning`. If a function is passed as the + argument, it must take a data segment as an argument and + return the windowed version of the segment. + + *noverlap*: integer + The number of points of overlap between blocks. The default value + is 0 (no overlap). + + *pad_to*: integer + The number of points to which the data segment is padded when + performing the FFT. This can be different from *NFFT*, which + specifies the number of data points used. While not increasing + the actual resolution of the psd (the minimum distance between + resolvable peaks), this can give more points in the plot, + allowing for more detail. This corresponds to the *n* parameter + in the call to fft(). The default is None, which sets *pad_to* + equal to *NFFT* + + *sides*: [ 'default' | 'onesided' | 'twosided' ] + Specifies which sides of the PSD to return. Default gives the + default behavior, which returns one-sided for real data and both + for complex data. 'onesided' forces the return of a one-sided PSD, + while 'twosided' forces two-sided. + + *scale_by_freq*: boolean + Specifies whether the resulting density values should be scaled + by the scaling frequency, which gives density in units of Hz^-1. + This allows for integration over the returned frequency values. + The default is True for MatLab compatibility. + + *Fc*: integer + The center frequency of *x* (defaults to 0), which offsets + the x extents of the plot to reflect the frequency range used + when a signal is acquired and then filtered and downsampled to + baseband. + +The return value is a tuple (*Cxy*, *f*), where *f* are the +frequencies of the coherence vector. + +kwargs are applied to the lines. + +References: + + * Bendat & Piersol -- Random Data: Analysis and Measurement + Procedures, John Wiley & Sons (1986) + +kwargs control the :class:`~matplotlib.lines.Line2D` +properties of the coherence plot: + + alpha: float (0.0 transparent through 1.0 opaque) + animated: [True | False] + antialiased or aa: [True | False] + axes: an :class:`~matplotlib.axes.Axes` instance + clip_box: a :class:`matplotlib.transforms.Bbox` instance + clip_on: [True | False] + clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] + color or c: any matplotlib color + contains: a callable function + dash_capstyle: ['butt' | 'round' | 'projecting'] + dash_joinstyle: ['miter' | 'round' | 'bevel'] + dashes: sequence of on/off ink in points + data: 2D array + drawstyle: [ 'default' | 'steps' | 'steps-pre' | 'steps-mid' | 'steps-post' ] + figure: a :class:`matplotlib.figure.Figure` instance + fillstyle: ['full' | 'left' | 'right' | 'bottom' | 'top'] + gid: an id string + label: any string + linestyle or ls: [ '-' | '--' | '-.' | ':' | 'None' | ' ' | '' ] and any drawstyle in combination with a linestyle, e.g. 'steps--'. + linewidth or lw: float value in points + lod: [True | False] + marker: [ '+' | '*' | ',' | '.' | '1' | '2' | '3' | '4' | '<' | '>' | 'D' | 'H' | '^' | '_' | 'd' | 'h' | 'o' | 'p' | 's' | 'v' | 'x' | '|' | TICKUP | TICKDOWN | TICKLEFT | TICKRIGHT | 'None' | ' ' | '' ] + markeredgecolor or mec: any matplotlib color + markeredgewidth or mew: float value in points + markerfacecolor or mfc: any matplotlib color + markersize or ms: float + markevery: None | integer | (startind, stride) + picker: float distance in points or callable pick function ``fn(artist, event)`` + pickradius: float distance in points + rasterized: [True | False | None] + snap: unknown + solid_capstyle: ['butt' | 'round' | 'projecting'] + solid_joinstyle: ['miter' | 'round' | 'bevel'] + transform: a :class:`matplotlib.transforms.Transform` instance + url: a url string + visible: [True | False] + xdata: 1D array + ydata: 1D array + zorder: any number + +**Example:** + +.. plot:: mpl_examples/pylab_examples/cohere_demo.py + +Additional kwargs: hold = [True|False] overrides default hold state +""" + ax = gca() # allow callers to override the hold state by passing hold=True|False - b = ishold() - h = kwargs.pop('hold', None) - if h is not None: - hold(h) + washold = ax.ishold() + + if hold is not None: + ax.hold(hold) try: - ret = gca().cohere(*args, **kwargs) + ret = ax.cohere(x, y, NFFT, Fs, Fc, detrend, window, noverlap, pad_to, sides, scale_by_freq, **kwargs) draw_if_interactive() - except: - hold(b) - raise + finally: + ax.hold(washold) - hold(b) return ret -if Axes.cohere.__doc__ is not None: - cohere.__doc__ = dedent(Axes.cohere.__doc__) + """ -Additional kwargs: hold = [True|False] overrides default hold state""" - # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost -def clabel(*args, **kwargs): +def clabel(CS, *args, **kwargs): + """call signature:: + + clabel(cs, **kwargs) + +adds labels to line contours in *cs*, where *cs* is a +:class:`~matplotlib.contour.ContourSet` object returned by +contour. + +:: + + clabel(cs, v, **kwargs) + +only labels contours listed in *v*. + +Optional keyword arguments: + + *fontsize*: + See http://matplotlib.sf.net/fonts.html + + *colors*: + - if *None*, the color of each label matches the color of + the corresponding contour + + - if one string color, e.g. *colors* = 'r' or *colors* = + 'red', all labels will be plotted in this color + + - if a tuple of matplotlib color args (string, float, rgb, etc), + different labels will be plotted in different colors in the order + specified + + *inline*: + controls whether the underlying contour is removed or + not. Default is *True*. + + *inline_spacing*: + space in pixels to leave on each side of label when + placing inline. Defaults to 5. This spacing will be + exact for labels at locations where the contour is + straight, less so for labels on curved contours. + + *fmt*: + a format string for the label. Default is '%1.3f' + Alternatively, this can be a dictionary matching contour + levels with arbitrary strings to use for each contour level + (i.e., fmt[level]=string) + + *manual*: + if *True*, contour labels will be placed manually using + mouse clicks. Click the first button near a contour to + add a label, click the second button (or potentially both + mouse buttons at once) to finish adding labels. The third + button can be used to remove the last label added, but + only if labels are not inline. Alternatively, the keyboard + can be used to select label locations (enter to end label + placement, delete or backspace act like the third mouse button, + and any other key will select a label location). + + *rightside_up*: + if *True* (default), label rotations will always be plus + or minus 90 degrees from level. + +.. plot:: mpl_examples/pylab_examples/contour_demo.py + +Additional kwargs: hold = [True|False] overrides default hold state +""" + ax = gca() # allow callers to override the hold state by passing hold=True|False - b = ishold() - h = kwargs.pop('hold', None) - if h is not None: - hold(h) + washold = ax.ishold() + hold = kwargs.pop('hold', None) + if hold is not None: + ax.hold(hold) try: - ret = gca().clabel(*args, **kwargs) + ret = ax.clabel(CS, *args, **kwargs) draw_if_interactive() - except: - hold(b) - raise + finally: + ax.hold(washold) - hold(b) return ret -if Axes.clabel.__doc__ is not None: - clabel.__doc__ = dedent(Axes.clabel.__doc__) + """ -Additional kwargs: hold = [True|False] overrides default hold state""" - # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def contour(*args, **kwargs): + """:func:`~matplotlib.pyplot.contour` and +:func:`~matplotlib.pyplot.contourf` draw contour lines and +filled contours, respectively. Except as noted, function +signatures and return values are the same for both versions. + +:func:`~matplotlib.pyplot.contourf` differs from the Matlab +(TM) version in that it does not draw the polygon edges, +because the contouring engine yields simply connected regions +with branch cuts. To draw the edges, add line contours with +calls to :func:`~matplotlib.pyplot.contour`. + + +call signatures:: + + contour(Z) + +make a contour plot of an array *Z*. The level values are chosen +automatically. + +:: + + contour(X,Y,Z) + +*X*, *Y* specify the (*x*, *y*) coordinates of the surface + +:: + + contour(Z,N) + contour(X,Y,Z,N) + +contour *N* automatically-chosen levels. + +:: + + contour(Z,V) + contour(X,Y,Z,V) + +draw contour lines at the values specified in sequence *V* + +:: + + contourf(..., V) + +fill the (len(*V*)-1) regions between the values in *V* + +:: + + contour(Z, **kwargs) + +Use keyword args to control colors, linewidth, origin, cmap ... see +below for more details. + +*X*, *Y*, and *Z* must be arrays with the same dimensions. + +*Z* may be a masked array, but filled contouring may not +handle internal masked regions correctly. + +``C = contour(...)`` returns a +:class:`~matplotlib.contour.ContourSet` object. + +Optional keyword arguments: + + *colors*: [ None | string | (mpl_colors) ] + If *None*, the colormap specified by cmap will be used. + + If a string, like 'r' or 'red', all levels will be plotted in this + color. + + If a tuple of matplotlib color args (string, float, rgb, etc), + different levels will be plotted in different colors in the order + specified. + + *alpha*: float + The alpha blending value + + *cmap*: [ None | Colormap ] + A cm :class:`~matplotlib.cm.Colormap` instance or + *None*. If *cmap* is *None* and *colors* is *None*, a + default Colormap is used. + + *norm*: [ None | Normalize ] + A :class:`matplotlib.colors.Normalize` instance for + scaling data values to colors. If *norm* is *None* and + *colors* is *None*, the default linear scaling is used. + + *origin*: [ None | 'upper' | 'lower' | 'image' ] + If *None*, the first value of *Z* will correspond to the + lower left corner, location (0,0). If 'image', the rc + value for ``image.origin`` will be used. + + This keyword is not active if *X* and *Y* are specified in + the call to contour. + + *extent*: [ None | (x0,x1,y0,y1) ] + + If *origin* is not *None*, then *extent* is interpreted as + in :func:`matplotlib.pyplot.imshow`: it gives the outer + pixel boundaries. In this case, the position of Z[0,0] + is the center of the pixel, not a corner. If *origin* is + *None*, then (*x0*, *y0*) is the position of Z[0,0], and + (*x1*, *y1*) is the position of Z[-1,-1]. + + This keyword is not active if *X* and *Y* are specified in + the call to contour. + + *locator*: [ None | ticker.Locator subclass ] + If *locator* is None, the default + :class:`~matplotlib.ticker.MaxNLocator` is used. The + locator is used to determine the contour levels if they + are not given explicitly via the *V* argument. + + *extend*: [ 'neither' | 'both' | 'min' | 'max' ] + Unless this is 'neither', contour levels are automatically + added to one or both ends of the range so that all data + are included. These added ranges are then mapped to the + special colormap values which default to the ends of the + colormap range, but can be set via + :meth:`matplotlib.cm.Colormap.set_under` and + :meth:`matplotlib.cm.Colormap.set_over` methods. + +contour-only keyword arguments: + + *linewidths*: [ None | number | tuple of numbers ] + If *linewidths* is *None*, the default width in + ``lines.linewidth`` in ``matplotlibrc`` is used. + + If a number, all levels will be plotted with this linewidth. + + If a tuple, different levels will be plotted with different + linewidths in the order specified + + *linestyles*: [None | 'solid' | 'dashed' | 'dashdot' | 'dotted' ] + If *linestyles* is *None*, the 'solid' is used. + + *linestyles* can also be an iterable of the above strings + specifying a set of linestyles to be used. If this + iterable is shorter than the number of contour levels + it will be repeated as necessary. + + If contour is using a monochrome colormap and the contour + level is less than 0, then the linestyle specified + in ``contour.negative_linestyle`` in ``matplotlibrc`` + will be used. + +contourf-only keyword arguments: + + *antialiased*: [ True | False ] + enable antialiasing + + *nchunk*: [ 0 | integer ] + If 0, no subdivision of the domain. Specify a positive integer to + divide the domain into subdomains of roughly *nchunk* by *nchunk* + points. This may never actually be advantageous, so this option may + be removed. Chunking introduces artifacts at the chunk boundaries + unless *antialiased* is *False*. + +**Example:** + +.. plot:: mpl_examples/pylab_examples/contour_demo.py + +Additional kwargs: hold = [True|False] overrides default hold state +""" + ax = gca() # allow callers to override the hold state by passing hold=True|False - b = ishold() - h = kwargs.pop('hold', None) - if h is not None: - hold(h) + washold = ax.ishold() + hold = kwargs.pop('hold', None) + if hold is not None: + ax.hold(hold) try: - ret = gca().contour(*args, **kwargs) + ret = ax.contour(*args, **kwargs) draw_if_interactive() - except: - hold(b) - raise + finally: + ax.hold(washold) if ret._A is not None: gci._current = ret - hold(b) return ret -if Axes.contour.__doc__ is not None: - contour.__doc__ = dedent(Axes.contour.__doc__) + """ -Additional kwargs: hold = [True|False] overrides default hold state""" - # This function was autogenerated by boilerplate.py. Do not edit as # changes will b... [truncated message content] |
From: <js...@us...> - 2009-07-23 12:10:28
|
Revision: 7287 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7287&view=rev Author: jswhit Date: 2009-07-23 12:10:18 +0000 (Thu, 23 Jul 2009) Log Message: ----------- add 'interp' keyword to griddata. Can be set to 'linear' to get faster linear interpolation using Delaunay package. Default is 'nn' (natural neighbor). Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/mlab.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-07-22 13:58:18 UTC (rev 7286) +++ trunk/matplotlib/CHANGELOG 2009-07-23 12:10:18 UTC (rev 7287) @@ -1,3 +1,7 @@ +2009-07-22 Added an 'interp' keyword to griddata so the faster linear + interpolation method can be chosen. Default is 'nn', so + default behavior (using natural neighbor method) is unchanged (JSW) + 2009-07-22 Improved boilerplate.py so that it generates the correct signatures for pyplot functions. - JKS Modified: trunk/matplotlib/lib/matplotlib/mlab.py =================================================================== --- trunk/matplotlib/lib/matplotlib/mlab.py 2009-07-22 13:58:18 UTC (rev 7286) +++ trunk/matplotlib/lib/matplotlib/mlab.py 2009-07-23 12:10:18 UTC (rev 7287) @@ -2621,7 +2621,7 @@ if opened: fh.close() -def griddata(x,y,z,xi,yi): +def griddata(x,y,z,xi,yi,interp='nn'): """ ``zi = griddata(x,y,z,xi,yi)`` fits a surface of the form *z* = *f*(*x*, *y*) to the data in the (usually) nonuniformly spaced @@ -2633,7 +2633,8 @@ A masked array is returned if any grid points are outside convex hull defined by input data (no extrapolation is done). - Uses natural neighbor interpolation based on Delaunay + If interp keyword is set to '`nn`' (default), + uses natural neighbor interpolation based on Delaunay triangulation. By default, this algorithm is provided by the :mod:`matplotlib.delaunay` package, written by Robert Kern. The triangulation algorithm in this package is known to fail on some @@ -2646,6 +2647,14 @@ algorithm, otherwise it will use the built-in :mod:`matplotlib.delaunay` package. + If the interp keyword is set to '`linear`', then linear interpolation + is used instead of natural neighbor. In this case, the output grid + is assumed to be regular with a constant grid spacing in both the x and + y directions. For regular grids with nonconstant grid spacing, you + must use natural neighbor interpolation. Linear interpolation is only valid if + :mod:`matplotlib.delaunay` package is used - :mod:`mpl_tookits.natgrid` + only provides natural neighbor interpolation. + The natgrid matplotlib toolkit can be downloaded from http://sourceforge.net/project/showfiles.php?group_id=80706&package_id=142792 """ @@ -2674,6 +2683,9 @@ y = y.compress(z.mask == False) z = z.compressed() if _use_natgrid: # use natgrid toolkit if available. + if interp != 'nn': + raise ValueError("only natural neighor interpolation" + " allowed when using natgrid toolkit in griddata.") if xi.ndim == 2: xi = xi[0,:] yi = yi[:,0] @@ -2701,8 +2713,17 @@ # triangulate data tri = delaunay.Triangulation(x,y) # interpolate data - interp = tri.nn_interpolator(z) - zo = interp(xi,yi) + if interp == 'nn': + interp = tri.nn_interpolator(z) + zo = interp(xi,yi) + elif interp == 'linear': + interp = tri.linear_interpolator(z) + zo = interp[yi.min():yi.max():complex(0,yi.shape[0]), + xi.min():xi.max():complex(0,xi.shape[1])] + else: + raise ValueError("interp keyword must be one of" + " 'linear' (for linear interpolation) or 'nn'" + " (for natural neighbor interpolation). Default is 'nn'.") # mask points on grid outside convex hull of input data. if np.any(np.isnan(zo)): zo = np.ma.masked_where(np.isnan(zo),zo) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <js...@us...> - 2009-07-23 18:25:41
|
Revision: 7288 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7288&view=rev Author: jswhit Date: 2009-07-23 18:25:39 +0000 (Thu, 23 Jul 2009) Log Message: ----------- check for nonuniform grid spacing when using inter='linear' in griddata. update griddata_demo.py (negative seeds not allowed in numpy svn mtrand) Modified Paths: -------------- trunk/matplotlib/examples/pylab_examples/griddata_demo.py trunk/matplotlib/lib/matplotlib/mlab.py Modified: trunk/matplotlib/examples/pylab_examples/griddata_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/griddata_demo.py 2009-07-23 12:10:18 UTC (rev 7287) +++ trunk/matplotlib/examples/pylab_examples/griddata_demo.py 2009-07-23 18:25:39 UTC (rev 7288) @@ -4,7 +4,7 @@ import numpy as np # make up data. #npts = int(raw_input('enter # of random points to plot:')) -seed(-1) +seed(0) npts = 200 x = uniform(-2,2,npts) y = uniform(-2,2,npts) Modified: trunk/matplotlib/lib/matplotlib/mlab.py =================================================================== --- trunk/matplotlib/lib/matplotlib/mlab.py 2009-07-23 12:10:18 UTC (rev 7287) +++ trunk/matplotlib/lib/matplotlib/mlab.py 2009-07-23 18:25:39 UTC (rev 7288) @@ -2717,6 +2717,14 @@ interp = tri.nn_interpolator(z) zo = interp(xi,yi) elif interp == 'linear': + # make sure grid has constant dx, dy + dx = xi[0,1:]-xi[0,0:-1] + dy = yi[1:,0]-yi[0:-1,0] + epsx = np.finfo(xi.dtype).resolution + epsy = np.finfo(yi.dtype).resolution + if dx.max()-dx.min() > epsx or dy.max()-dy.min() > epsy: + raise ValueError("output grid must have constant spacing" + " when using interp='linear'") interp = tri.linear_interpolator(z) zo = interp[yi.min():yi.max():complex(0,yi.shape[0]), xi.min():xi.max():complex(0,xi.shape[1])] This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ef...@us...> - 2009-07-26 00:06:45
|
Revision: 7294 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7294&view=rev Author: efiring Date: 2009-07-26 00:06:34 +0000 (Sun, 26 Jul 2009) Log Message: ----------- Plot accepts scalar coordinates, e.g. plot(1, 2, 'r*') Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/axes.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-07-24 02:09:20 UTC (rev 7293) +++ trunk/matplotlib/CHANGELOG 2009-07-26 00:06:34 UTC (rev 7294) @@ -1,3 +1,5 @@ +2009-07-25 Allow "plot(1, 2, 'r*')" to work. - EF + 2009-07-22 Added an 'interp' keyword to griddata so the faster linear interpolation method can be chosen. Default is 'nn', so default behavior (using natural neighbor method) is unchanged (JSW) Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2009-07-24 02:09:20 UTC (rev 7293) +++ trunk/matplotlib/lib/matplotlib/axes.py 2009-07-26 00:06:34 UTC (rev 7294) @@ -223,11 +223,11 @@ if by: y = self.axes.convert_yunits(y) - x = ma.asarray(x) - y = ma.asarray(y) - if len(x.shape) == 1: + x = ma.asarray(np.atleast_1d(x)) + y = ma.asarray(np.atleast_1d(y)) + if x.ndim == 1: x = x[:,np.newaxis] - if len(y.shape) == 1: + if y.ndim == 1: y = y[:,np.newaxis] nrx, ncx = x.shape nry, ncy = y.shape This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ef...@us...> - 2009-07-27 19:35:55
|
Revision: 7298 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7298&view=rev Author: efiring Date: 2009-07-27 19:35:47 +0000 (Mon, 27 Jul 2009) Log Message: ----------- Simplify plot argument handling code. The only side effect of the change should be that previously, plotting multiple columns required that x and y have the same number of columns, or that one of them have only one column. Now the plotting simply cycles through the columns of both, wrapping back to the first column as needed. Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/axes.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-07-27 19:23:55 UTC (rev 7297) +++ trunk/matplotlib/CHANGELOG 2009-07-27 19:35:47 UTC (rev 7298) @@ -1,3 +1,5 @@ +2009-07-27 Simplify argument handling code for plot method. -EF + 2009-07-25 Allow "plot(1, 2, 'r*')" to work. - EF 2009-07-22 Added an 'interp' keyword to griddata so the faster linear Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2009-07-27 19:23:55 UTC (rev 7297) +++ trunk/matplotlib/lib/matplotlib/axes.py 2009-07-27 19:35:47 UTC (rev 7298) @@ -199,21 +199,6 @@ func = getattr(fill_poly,funcName) func(val) - def _xy_from_y(self, y): - if self.axes.yaxis is not None: - b = self.axes.yaxis.update_units(y) - if b: return np.arange(len(y)), y, False - - if not ma.isMaskedArray(y): - y = np.asarray(y) - if len(y.shape) == 1: - y = y[:,np.newaxis] - nr, nc = y.shape - x = np.arange(nr) - if len(x.shape) == 1: - x = x[:,np.newaxis] - return x,y, True - def _xy_from_xy(self, x, y): if self.axes.xaxis is not None and self.axes.yaxis is not None: bx = self.axes.xaxis.update_units(x) @@ -223,197 +208,107 @@ if by: y = self.axes.convert_yunits(y) - x = ma.asarray(np.atleast_1d(x)) - y = ma.asarray(np.atleast_1d(y)) + x = np.atleast_1d(x) #like asanyarray, but converts scalar to array + y = np.atleast_1d(y) + if x.shape[0] != y.shape[0]: + raise ValueError("x and y must have same first dimension") + if x.ndim > 2 or y.ndim > 2: + raise ValueError("x and y can be no greater than 2-D") + if x.ndim == 1: x = x[:,np.newaxis] if y.ndim == 1: y = y[:,np.newaxis] - nrx, ncx = x.shape - nry, ncy = y.shape - assert nrx == nry, 'Dimensions of x and y are incompatible' - if ncx == ncy: - return x, y, True - if ncx == 1: - x = np.repeat(x, ncy, axis=1) - if ncy == 1: - y = np.repeat(y, ncx, axis=1) - assert x.shape == y.shape, 'Dimensions of x and y are incompatible' - return x, y, True + return x, y + def _makeline(self, x, y, kw, kwargs): + kw = kw.copy() # Don't modify the original kw. + if not 'color' in kw: + kw['color'] = self._get_next_cycle_color() + # (can't use setdefault because it always evaluates + # its second argument) + seg = mlines.Line2D(x, y, + axes=self.axes, + **kw + ) + self.set_lineprops(seg, **kwargs) + return seg - def _plot_1_arg(self, y, **kwargs): - assert self.command == 'plot', 'fill needs at least 2 arguments' - ret = [] + def _makefill(self, x, y, kw, kwargs): + try: + facecolor = kw['color'] + except KeyError: + facecolor = self._get_next_cycle_color() + seg = mpatches.Polygon(np.hstack( + (x[:,np.newaxis],y[:,np.newaxis])), + facecolor = facecolor, + fill=True, + closed=kw['closed'] + ) + self.set_patchprops(seg, **kwargs) + return seg - x, y, multicol = self._xy_from_y(y) - if multicol: - for j in xrange(y.shape[1]): - color = self._get_next_cycle_color() - seg = mlines.Line2D(x, y[:,j], - color = color, - axes=self.axes, - ) - self.set_lineprops(seg, **kwargs) - ret.append(seg) + def _plot_args(self, tup, kwargs): + ret = [] + if len(tup) > 1 and is_string_like(tup[-1]): + linestyle, marker, color = _process_plot_format(tup[-1]) + tup = tup[:-1] + elif len(tup) == 3: + raise ValueError, 'third arg must be a format string' else: - color = self._get_next_cycle_color() - seg = mlines.Line2D(x, y, - color = color, - axes=self.axes, - ) - self.set_lineprops(seg, **kwargs) - ret.append(seg) + linestyle, marker, color = None, None, None + kw = {} + for k, v in zip(('linestyle', 'marker', 'color'), + (linestyle, marker, color)): + if v is not None: + kw[k] = v - return ret + y = np.atleast_1d(tup[-1]) - def _plot_2_args(self, tup2, **kwargs): - ret = [] - if is_string_like(tup2[1]): - - assert self.command == 'plot', ('fill needs at least 2 non-string ' - 'arguments') - y, fmt = tup2 - x, y, multicol = self._xy_from_y(y) - - linestyle, marker, color = _process_plot_format(fmt) - - def makeline(x, y): - _color = color - if _color is None: - _color = self._get_next_cycle_color() - seg = mlines.Line2D(x, y, - color=_color, - linestyle=linestyle, marker=marker, - axes=self.axes, - ) - self.set_lineprops(seg, **kwargs) - ret.append(seg) - - if multicol: - for j in xrange(y.shape[1]): - makeline(x[:,j], y[:,j]) - else: - makeline(x, y) - - return ret + if len(tup) == 2: + x = np.atleast_1d(tup[0]) else: + x = np.arange(y.shape[0], dtype=float) - x, y = tup2 - x, y, multicol = self._xy_from_xy(x, y) + x, y = self._xy_from_xy(x, y) - def makeline(x, y): - color = self._get_next_cycle_color() - seg = mlines.Line2D(x, y, - color=color, - axes=self.axes, - ) - self.set_lineprops(seg, **kwargs) - ret.append(seg) - - def makefill(x, y): - facecolor = self._get_next_cycle_color() - seg = mpatches.Polygon(np.hstack( - (x[:,np.newaxis],y[:,np.newaxis])), - facecolor = facecolor, - fill=True, - closed=closed - ) - self.set_patchprops(seg, **kwargs) - ret.append(seg) - - if self.command == 'plot': - func = makeline - else: - closed = kwargs.get('closed', True) - func = makefill - if multicol: - for j in xrange(y.shape[1]): - func(x[:,j], y[:,j]) - else: - func(x, y) - - - return ret - - def _plot_3_args(self, tup3, **kwargs): - ret = [] - - x, y, fmt = tup3 - x, y, multicol = self._xy_from_xy(x, y) - - linestyle, marker, color = _process_plot_format(fmt) - - def makeline(x, y): - _color = color - if _color is None: - _color = self._get_next_cycle_color() - seg = mlines.Line2D(x, y, - color=_color, - linestyle=linestyle, marker=marker, - axes=self.axes, - ) - self.set_lineprops(seg, **kwargs) - ret.append(seg) - - def makefill(x, y): - facecolor = color - seg = mpatches.Polygon(np.hstack( - (x[:,np.newaxis],y[:,np.newaxis])), - facecolor = facecolor, - fill=True, - closed=closed - ) - self.set_patchprops(seg, **kwargs) - ret.append(seg) - if self.command == 'plot': - func = makeline + func = self._makeline else: - closed = kwargs.get('closed', True) - func = makefill + kw['closed'] = kwargs.get('closed', True) + func = self._makefill - if multicol: - for j in xrange(y.shape[1]): - func(x[:,j], y[:,j]) - else: - func(x, y) + ncx, ncy = x.shape[1], y.shape[1] + for j in xrange(max(ncx, ncy)): + seg = func(x[:,j%ncx], y[:,j%ncy], kw, kwargs) + ret.append(seg) return ret + def _grab_next_args(self, *args, **kwargs): remaining = args while 1: - if len(remaining)==0: return - if len(remaining)==1: - for seg in self._plot_1_arg(remaining[0], **kwargs): + if len(remaining)==0: + return + if len(remaining) <= 3: + for seg in self._plot_args(remaining, kwargs): yield seg - remaining = [] - continue - if len(remaining)==2: - for seg in self._plot_2_args(remaining, **kwargs): - yield seg - remaining = [] - continue - if len(remaining)==3: - if not is_string_like(remaining[2]): - raise ValueError, 'third arg must be a format string' - for seg in self._plot_3_args(remaining, **kwargs): - yield seg - remaining=[] - continue + return + if is_string_like(remaining[2]): - for seg in self._plot_3_args(remaining[:3], **kwargs): - yield seg - remaining=remaining[3:] + isplit = 3 else: - for seg in self._plot_2_args(remaining[:2], **kwargs): - yield seg - remaining=remaining[2:] + isplit = 2 + for seg in self._plot_args(remaining[:isplit], kwargs): + yield seg + remaining=remaining[isplit:] + + class Axes(martist.Artist): """ The :class:`Axes` contains most of the figure elements: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ef...@us...> - 2009-07-28 22:43:25
|
Revision: 7303 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7303&view=rev Author: efiring Date: 2009-07-28 22:43:15 +0000 (Tue, 28 Jul 2009) Log Message: ----------- Speed up quiver for large numbers of arrows; key tip given by Ray Speth. Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/collections.py trunk/matplotlib/lib/matplotlib/quiver.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-07-28 20:56:07 UTC (rev 7302) +++ trunk/matplotlib/CHANGELOG 2009-07-28 22:43:15 UTC (rev 7303) @@ -1,3 +1,5 @@ +2009-07-28 Quiver speed improved, thanks to tip by Ray Speth. -EF + 2009-07-27 Simplify argument handling code for plot method. -EF 2009-07-25 Allow "plot(1, 2, 'r*')" to work. - EF Modified: trunk/matplotlib/lib/matplotlib/collections.py =================================================================== --- trunk/matplotlib/lib/matplotlib/collections.py 2009-07-28 20:56:07 UTC (rev 7302) +++ trunk/matplotlib/lib/matplotlib/collections.py 2009-07-28 22:43:15 UTC (rev 7303) @@ -670,6 +670,9 @@ def set_verts(self, verts, closed=True): '''This allows one to delay initialization of the vertices.''' + if np.ma.isMaskedArray(verts): + verts = verts.astype(np.float_).filled(np.nan) + # This is much faster than having Path do it one at a time. if closed: self._paths = [] for xy in verts: Modified: trunk/matplotlib/lib/matplotlib/quiver.py =================================================================== --- trunk/matplotlib/lib/matplotlib/quiver.py 2009-07-28 20:56:07 UTC (rev 7302) +++ trunk/matplotlib/lib/matplotlib/quiver.py 2009-07-28 22:43:15 UTC (rev 7303) @@ -253,8 +253,12 @@ self._set_transform() _pivot = self.Q.pivot self.Q.pivot = self.pivot[self.labelpos] + # Hack: save and restore the Umask + _mask = self.Q.Umask + self.Q.Umask = ma.nomask self.verts = self.Q._make_verts(np.array([self.U]), np.zeros((1,))) + self.Q.Umask = _mask self.Q.pivot = _pivot kw = self.Q.polykw kw.update(self.kw) @@ -388,9 +392,9 @@ X, Y, U, V, C = [None]*5 args = list(args) if len(args) == 3 or len(args) == 5: - C = ma.masked_invalid(args.pop(-1), copy=False) - V = ma.masked_invalid(args.pop(-1), copy=False) - U = ma.masked_invalid(args.pop(-1), copy=False) + C = np.asanyarray(args.pop(-1)) + V = np.asanyarray(args.pop(-1)) + U = np.asanyarray(args.pop(-1)) if U.ndim == 1: nr, nc = 1, U.shape[0] else: @@ -430,10 +434,21 @@ collections.PolyCollection.draw(self, renderer) def set_UVC(self, U, V, C=None): - self.U = U.ravel() - self.V = V.ravel() + U = ma.masked_invalid(U, copy=False).ravel() + V = ma.masked_invalid(V, copy=False).ravel() + mask = ma.mask_or(U.mask, V.mask, copy=False, shrink=True) if C is not None: - self.set_array(C.ravel()) + C = ma.masked_invalid(C, copy=False).ravel() + mask = ma.mask_or(mask, C.mask, copy=False, shrink=True) + if mask is ma.nomask: + C = C.filled() + else: + C = ma.array(C, mask=mask, copy=False) + self.U = U.filled(1) + self.V = V.filled(1) + self.Umask = mask + if C is not None: + self.set_array(C) self._new_UV = True def _set_transform(self): @@ -463,32 +478,33 @@ def _angles(self, U, V, eps=0.001): xy = self.ax.transData.transform(self.XY) - uv = ma.hstack((U[:,np.newaxis], V[:,np.newaxis])).filled(0) + uv = np.hstack((U[:,np.newaxis], V[:,np.newaxis])) xyp = self.ax.transData.transform(self.XY + eps * uv) dxy = xyp - xy - ang = ma.arctan2(dxy[:,1], dxy[:,0]) + ang = np.arctan2(dxy[:,1], dxy[:,0]) return ang def _make_verts(self, U, V): - uv = ma.asarray(U+V*1j) - a = ma.absolute(uv) + uv = (U+V*1j) + a = np.absolute(uv) if self.scale is None: sn = max(10, math.sqrt(self.N)) - scale = 1.8 * a.mean() * sn / self.span # crude auto-scaling + scale = 1.8 * a[~self.Umask].mean() * sn / self.span # crude auto-scaling self.scale = scale length = a/(self.scale*self.width) X, Y = self._h_arrows(length) if self.angles == 'xy': - theta = self._angles(U, V).filled(0) + theta = self._angles(U, V) elif self.angles == 'uv': - theta = np.angle(uv.filled(0)) + theta = np.angle(uv) else: theta = ma.masked_invalid(self.angles, copy=False).filled(0) theta *= (np.pi/180.0) theta.shape = (theta.shape[0], 1) # for broadcasting xy = (X+Y*1j) * np.exp(1j*theta)*self.width xy = xy[:,:,np.newaxis] - XY = ma.concatenate((xy.real, xy.imag), axis=2) + XY = np.concatenate((xy.real, xy.imag), axis=2) + return XY @@ -502,8 +518,8 @@ length = length.reshape(N, 1) # This number is chosen based on when pixel values overflow in Agg # causing rendering errors - length = np.minimum(length, 2 ** 16) - + #length = np.minimum(length, 2 ** 16) + np.clip(length, 0, 2**16, out=length) # x, y: normal horizontal arrow x = np.array([0, -self.headaxislength, -self.headlength, 0], np.float64) @@ -514,21 +530,20 @@ x0 = np.array([0, minsh-self.headaxislength, minsh-self.headlength, minsh], np.float64) y0 = 0.5 * np.array([1, 1, self.headwidth, 0], np.float64) - ii = [0,1,2,3,2,1,0] + ii = [0,1,2,3,2,1,0,0] X = x.take(ii, 1) Y = y.take(ii, 1) - Y[:, 3:] *= -1 + Y[:, 3:-1] *= -1 X0 = x0.take(ii) Y0 = y0.take(ii) - Y0[3:] *= -1 + Y0[3:-1] *= -1 shrink = length/minsh X0 = shrink * X0[np.newaxis,:] Y0 = shrink * Y0[np.newaxis,:] - short = np.repeat(length < minsh, 7, axis=1) - #print 'short', length < minsh + short = np.repeat(length < minsh, 8, axis=1) # Now select X0, Y0 if short, otherwise X, Y - X = ma.where(short, X0, X) - Y = ma.where(short, Y0, Y) + np.putmask(X, short, X0) + np.putmask(Y, short, Y0) if self.pivot[:3] == 'mid': X -= 0.5 * X[:,3, np.newaxis] elif self.pivot[:3] == 'tip': @@ -538,14 +553,18 @@ tooshort = length < self.minlength if tooshort.any(): # Use a heptagonal dot: - th = np.arange(0,7,1, np.float64) * (np.pi/3.0) + th = np.arange(0,8,1, np.float64) * (np.pi/3.0) x1 = np.cos(th) * self.minlength * 0.5 y1 = np.sin(th) * self.minlength * 0.5 X1 = np.repeat(x1[np.newaxis, :], N, axis=0) Y1 = np.repeat(y1[np.newaxis, :], N, axis=0) - tooshort = ma.repeat(tooshort, 7, 1) - X = ma.where(tooshort, X1, X) - Y = ma.where(tooshort, Y1, Y) + tooshort = np.repeat(tooshort, 8, 1) + np.putmask(X, tooshort, X1) + np.putmask(Y, tooshort, Y1) + if self.Umask is not ma.nomask: + mask = np.repeat(self.Umask[:,np.newaxis], 8, 1) + X = ma.array(X, mask=mask, copy=False) + Y = ma.array(Y, mask=mask, copy=False) return X, Y quiver_doc = _quiver_doc This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ef...@us...> - 2009-07-30 19:32:25
|
Revision: 7309 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7309&view=rev Author: efiring Date: 2009-07-30 19:32:15 +0000 (Thu, 30 Jul 2009) Log Message: ----------- User-generated colormaps are handled more easily. Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/doc/api/api_changes.rst trunk/matplotlib/examples/pylab_examples/custom_cmap.py trunk/matplotlib/lib/matplotlib/cm.py trunk/matplotlib/lib/matplotlib/image.py trunk/matplotlib/lib/matplotlib/pyplot.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-07-30 17:08:23 UTC (rev 7308) +++ trunk/matplotlib/CHANGELOG 2009-07-30 19:32:15 UTC (rev 7309) @@ -1,3 +1,7 @@ +2009-07-30 Add set_cmap and register_cmap, and improve get_cmap, + to provide convenient handling of user-generated + colormaps. - EF + 2009-07-28 Quiver speed improved, thanks to tip by Ray Speth. -EF 2009-07-27 Simplify argument handling code for plot method. -EF Modified: trunk/matplotlib/doc/api/api_changes.rst =================================================================== --- trunk/matplotlib/doc/api/api_changes.rst 2009-07-30 17:08:23 UTC (rev 7308) +++ trunk/matplotlib/doc/api/api_changes.rst 2009-07-30 19:32:15 UTC (rev 7309) @@ -21,6 +21,11 @@ Changes beyond 0.98.x ===================== +* User-generated colormaps can now be added to the set recognized + by :func:`matplotlib.cm.get_cmap`. Colormaps can be made the + default and applied to the current image using + :func:`matplotlib.pyplot.set_cmap`. + * changed use_mrecords default to False in mlab.csv2rec since this is partially broken Modified: trunk/matplotlib/examples/pylab_examples/custom_cmap.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/custom_cmap.py 2009-07-30 17:08:23 UTC (rev 7308) +++ trunk/matplotlib/examples/pylab_examples/custom_cmap.py 2009-07-30 19:32:15 UTC (rev 7309) @@ -103,11 +103,25 @@ (1.0, 0.0, 0.0)) } +# Now we will use this example to illustrate 3 ways of +# handling custom colormaps. +# First, the most direct and explicit: blue_red1 = LinearSegmentedColormap('BlueRed1', cdict1) + +# Second, create the map explicitly and register it. +# Like the first method, this method works with any kind +# of Colormap, not just +# a LinearSegmentedColormap: + blue_red2 = LinearSegmentedColormap('BlueRed2', cdict2) -blue_red3 = LinearSegmentedColormap('BlueRed3', cdict3) +plt.register_cmap(cmap=blue_red2) +# Third, for LinearSegmentedColormap only, +# leave everything to register_cmap: + +plt.register_cmap(name='BlueRed3', data=cdict3) # optional lut kwarg + x = np.arange(0, np.pi, 0.1) y = np.arange(0, 2*np.pi, 0.1) X, Y = np.meshgrid(x,y) @@ -121,13 +135,33 @@ plt.colorbar() plt.subplot(1,3,2) -plt.imshow(Z, interpolation='nearest', cmap=blue_red2) +cmap = plt.get_cmap('BlueRed2') +plt.imshow(Z, interpolation='nearest', cmap=cmap) plt.colorbar() +# Now we will set the third cmap as the default. One would +# not normally do this in the middle of a script like this; +# it is done here just to illustrate the method. + +plt.rcParams['image.cmap'] = 'BlueRed3' + +# Also see below for an alternative, particularly for +# interactive use. + plt.subplot(1,3,3) -plt.imshow(Z, interpolation='nearest', cmap=blue_red3) +plt.imshow(Z, interpolation='nearest') plt.colorbar() +# Or as yet another variation, we could replace the rcParams +# specification *before* the imshow with the following *after* +# imshow: +# +# plt.set_cmap('BlueRed3') +# +# This sets the new default *and* sets the colormap of the last +# image-like item plotted via pyplot, if any. + + plt.suptitle('Custom Blue-Red colormaps') plt.show() Modified: trunk/matplotlib/lib/matplotlib/cm.py =================================================================== --- trunk/matplotlib/lib/matplotlib/cm.py 2009-07-30 17:08:23 UTC (rev 7308) +++ trunk/matplotlib/lib/matplotlib/cm.py 2009-07-30 19:32:15 UTC (rev 7309) @@ -9,16 +9,79 @@ import matplotlib.cbook as cbook from matplotlib._cm import * +# Dictionary for user-registered colormaps: +cmap_d = dict() +# Using this second dictionary allows us to handle any +# Colormap instance; the built-in datad is only for +# LinearSegmentedColormaps. The advantage of keeping +# datad is that it delays the generation of the Colormap +# instance until it is actually needed. Generating the +# instance is fast enough, and typically done few enough +# times, that there is no need to cache the result. +def register_cmap(name=None, cmap=None, data=None, lut=None): + """ + Add a colormap to the set recognized by :func:`get_cmap`. + + It can be used in two ways:: + + register_cmap(name='swirly', cmap=swirly_cmap) + + register_cmap(name='choppy', data=choppydata, lut=128) + + In the first case, *cmap* must be a :class:`colors.Colormap` + instance. The *name* is optional; if absent, the name will + be the :attr:`name` attribute of the *cmap*. + + In the second case, the three arguments are passed to + the :class:`colors.LinearSegmentedColormap` initializer, + and the resulting colormap is registered. + + """ + if name is None: + try: + name = cmap.name + except AttributeError: + raise ValueError("Arguments must include a name or a Colormap") + + if not cbook.is_string_like(name): + raise ValueError("Colormap name must be a string") + + if isinstance(cmap, colors.Colormap): + cmap_d[name] = cmap + return + + # For the remainder, let exceptions propagate. + if lut is None: + lut = mpl.rcParams['image.lut'] + cmap = colors.LinearSegmentedColormap(name, data, lut) + cmap_d[name] = cmap + def get_cmap(name=None, lut=None): """ - Get a colormap instance, defaulting to rc values if *name* is None + Get a colormap instance, defaulting to rc values if *name* is None. + + Colormaps added with :func:`register_cmap` take precedence over + builtin colormaps. + + If *name* is a :class:`colors.Colormap` instance, it will be + returned. """ - if name is None: name = mpl.rcParams['image.cmap'] - if lut is None: lut = mpl.rcParams['image.lut'] + if name is None: + name = mpl.rcParams['image.cmap'] - assert(name in datad.keys()) + if isinstance(name, colors.Colormap): + return name + + if name in cmap_d: + return cmap_d[name] + + if name not in datad: + raise ValueError("%s is not a known colormap name" % name) + + if lut is None: + lut = mpl.rcParams['image.lut'] return colors.LinearSegmentedColormap(name, datad[name], lut) class ScalarMappable: @@ -116,9 +179,9 @@ """ set the colormap for luminance data - ACCEPTS: a colormap + ACCEPTS: a colormap or registered colormap name """ - if cmap is None: cmap = get_cmap() + cmap = get_cmap(cmap) self.cmap = cmap self.changed() Modified: trunk/matplotlib/lib/matplotlib/image.py =================================================================== --- trunk/matplotlib/lib/matplotlib/image.py 2009-07-30 17:08:23 UTC (rev 7308) +++ trunk/matplotlib/lib/matplotlib/image.py 2009-07-30 19:32:15 UTC (rev 7309) @@ -512,7 +512,7 @@ def set_cmap(self, cmap): if self._A is not None: raise RuntimeError('Cannot change colors after loading data') - cm.ScalarMappable.set_cmap(self, norm) + cm.ScalarMappable.set_cmap(self, cmap) class PcolorImage(martist.Artist, cm.ScalarMappable): ''' Modified: trunk/matplotlib/lib/matplotlib/pyplot.py =================================================================== --- trunk/matplotlib/lib/matplotlib/pyplot.py 2009-07-30 17:08:23 UTC (rev 7308) +++ trunk/matplotlib/lib/matplotlib/pyplot.py 2009-07-30 19:32:15 UTC (rev 7309) @@ -17,7 +17,7 @@ from matplotlib.scale import get_scale_docs, get_scale_names from matplotlib import cm -from matplotlib.cm import get_cmap +from matplotlib.cm import get_cmap, register_cmap import numpy as np @@ -1396,8 +1396,26 @@ im.set_clim(vmin, vmax) draw_if_interactive() +def set_cmap(cmap): + ''' + set the default colormap to *cmap* and apply to current image if any. + See help(colormaps) for more information. + *cmap* must be a :class:`colors.Colormap` instance, or + the name of a registered colormap. + See :func:`register_cmap` and :func:`get_cmap`. + ''' + cmap = cm.get_cmap(cmap) + + rc('image', cmap=cmap.name) + im = gci() + + if im is not None: + im.set_cmap(cmap) + draw_if_interactive() + + def imread(*args, **kwargs): return _imread(*args, **kwargs) if _imread.__doc__ is not None: @@ -6327,12 +6345,12 @@ *bbox_to_anchor* keyword argument. bbox_to_anchor can be an instance of BboxBase(or its derivatives) or a tuple of 2 or 4 floats. For example, :: - + loc = 'upper right', bbox_to_anchor = (0.5, 0.5) will place the legend so that the upper right corner of the legend at the center of the axes. - + The legend location can be specified in other coordinate, by using the *bbox_transform* keyword. @@ -6365,7 +6383,7 @@ *fancybox*: [ None | False | True ] if True, draw a frame with a round fancybox. If None, use rc - + *shadow*: [ None | False | True ] If *True*, draw a shadow behind legend. If *None*, use rc settings. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ef...@us...> - 2009-07-31 02:48:25
|
Revision: 7311 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7311&view=rev Author: efiring Date: 2009-07-31 02:48:18 +0000 (Fri, 31 Jul 2009) Log Message: ----------- Cache the color data to reduce startup time. Also, cmap kwargs now accept colormap names as strings. Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/_cm.py trunk/matplotlib/lib/matplotlib/axes.py trunk/matplotlib/lib/matplotlib/cm.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-07-30 21:50:10 UTC (rev 7310) +++ trunk/matplotlib/CHANGELOG 2009-07-31 02:48:18 UTC (rev 7311) @@ -1,6 +1,7 @@ 2009-07-30 Add set_cmap and register_cmap, and improve get_cmap, to provide convenient handling of user-generated - colormaps. - EF + colormaps. Reorganized _cm and cm modules, and added + caching of the color data to reduce startup time. - EF 2009-07-28 Quiver speed improved, thanks to tip by Ray Speth. -EF Modified: trunk/matplotlib/lib/matplotlib/_cm.py =================================================================== --- trunk/matplotlib/lib/matplotlib/_cm.py 2009-07-30 21:50:10 UTC (rev 7310) +++ trunk/matplotlib/lib/matplotlib/_cm.py 2009-07-31 02:48:18 UTC (rev 7311) @@ -1,25 +1,15 @@ """ -Color data and pre-defined cmap objects. +Nothing here but dictionaries for generating LinearSegmentedColormaps, +and a dictionary of these dictionaries. -This is a helper for cm.py, originally part of that file. -Separating the data (this file) from cm.py makes both easier -to deal with. - -Objects visible in cm.py are the individual cmap objects ('autumn', -etc.) and a dictionary, 'datad', including all of these objects. """ -import matplotlib as mpl -import matplotlib.colors as colors -LUTSIZE = mpl.rcParams['image.lut'] - _binary_data = { 'red' : ((0., 1., 1.), (1., 0., 0.)), 'green': ((0., 1., 1.), (1., 0., 0.)), 'blue' : ((0., 1., 1.), (1., 0., 0.)) } - _bone_data = {'red': ((0., 0., 0.),(1.0, 1.0, 1.0)), 'green': ((0., 0., 0.),(1.0, 1.0, 1.0)), 'blue': ((0., 0., 0.),(1.0, 1.0, 1.0))} @@ -379,44 +369,6 @@ (1.0, 0.80, 0.80)]} -autumn = colors.LinearSegmentedColormap('autumn', _autumn_data, LUTSIZE) -bone = colors.LinearSegmentedColormap('bone ', _bone_data, LUTSIZE) -binary = colors.LinearSegmentedColormap('binary ', _binary_data, LUTSIZE) -cool = colors.LinearSegmentedColormap('cool', _cool_data, LUTSIZE) -copper = colors.LinearSegmentedColormap('copper', _copper_data, LUTSIZE) -flag = colors.LinearSegmentedColormap('flag', _flag_data, LUTSIZE) -gray = colors.LinearSegmentedColormap('gray', _gray_data, LUTSIZE) -hot = colors.LinearSegmentedColormap('hot', _hot_data, LUTSIZE) -hsv = colors.LinearSegmentedColormap('hsv', _hsv_data, LUTSIZE) -jet = colors.LinearSegmentedColormap('jet', _jet_data, LUTSIZE) -pink = colors.LinearSegmentedColormap('pink', _pink_data, LUTSIZE) -prism = colors.LinearSegmentedColormap('prism', _prism_data, LUTSIZE) -spring = colors.LinearSegmentedColormap('spring', _spring_data, LUTSIZE) -summer = colors.LinearSegmentedColormap('summer', _summer_data, LUTSIZE) -winter = colors.LinearSegmentedColormap('winter', _winter_data, LUTSIZE) -spectral = colors.LinearSegmentedColormap('spectral', _spectral_data, LUTSIZE) - - - -datad = { - 'autumn': _autumn_data, - 'bone': _bone_data, - 'binary': _binary_data, - 'cool': _cool_data, - 'copper': _copper_data, - 'flag': _flag_data, - 'gray' : _gray_data, - 'hot': _hot_data, - 'hsv': _hsv_data, - 'jet' : _jet_data, - 'pink': _pink_data, - 'prism': _prism_data, - 'spring': _spring_data, - 'summer': _summer_data, - 'winter': _winter_data, - 'spectral': _spectral_data - } - # 34 colormaps based on color specifications and designs # developed by Cynthia Brewer (http://colorbrewer.org). # The ColorBrewer palettes have been included under the terms @@ -5859,48 +5811,26 @@ 0.0078431377187371254, 0.0078431377187371254), (1.0, 0.0039215688593685627, 0.0039215688593685627)]} -Accent = colors.LinearSegmentedColormap('Accent', _Accent_data, LUTSIZE) -Blues = colors.LinearSegmentedColormap('Blues', _Blues_data, LUTSIZE) -BrBG = colors.LinearSegmentedColormap('BrBG', _BrBG_data, LUTSIZE) -BuGn = colors.LinearSegmentedColormap('BuGn', _BuGn_data, LUTSIZE) -BuPu = colors.LinearSegmentedColormap('BuPu', _BuPu_data, LUTSIZE) -Dark2 = colors.LinearSegmentedColormap('Dark2', _Dark2_data, LUTSIZE) -GnBu = colors.LinearSegmentedColormap('GnBu', _GnBu_data, LUTSIZE) -Greens = colors.LinearSegmentedColormap('Greens', _Greens_data, LUTSIZE) -Greys = colors.LinearSegmentedColormap('Greys', _Greys_data, LUTSIZE) -Oranges = colors.LinearSegmentedColormap('Oranges', _Oranges_data, LUTSIZE) -OrRd = colors.LinearSegmentedColormap('OrRd', _OrRd_data, LUTSIZE) -Paired = colors.LinearSegmentedColormap('Paired', _Paired_data, LUTSIZE) -Pastel1 = colors.LinearSegmentedColormap('Pastel1', _Pastel1_data, LUTSIZE) -Pastel2 = colors.LinearSegmentedColormap('Pastel2', _Pastel2_data, LUTSIZE) -PiYG = colors.LinearSegmentedColormap('PiYG', _PiYG_data, LUTSIZE) -PRGn = colors.LinearSegmentedColormap('PRGn', _PRGn_data, LUTSIZE) -PuBu = colors.LinearSegmentedColormap('PuBu', _PuBu_data, LUTSIZE) -PuBuGn = colors.LinearSegmentedColormap('PuBuGn', _PuBuGn_data, LUTSIZE) -PuOr = colors.LinearSegmentedColormap('PuOr', _PuOr_data, LUTSIZE) -PuRd = colors.LinearSegmentedColormap('PuRd', _PuRd_data, LUTSIZE) -Purples = colors.LinearSegmentedColormap('Purples', _Purples_data, LUTSIZE) -RdBu = colors.LinearSegmentedColormap('RdBu', _RdBu_data, LUTSIZE) -RdGy = colors.LinearSegmentedColormap('RdGy', _RdGy_data, LUTSIZE) -RdPu = colors.LinearSegmentedColormap('RdPu', _RdPu_data, LUTSIZE) -RdYlBu = colors.LinearSegmentedColormap('RdYlBu', _RdYlBu_data, LUTSIZE) -RdYlGn = colors.LinearSegmentedColormap('RdYlGn', _RdYlGn_data, LUTSIZE) -Reds = colors.LinearSegmentedColormap('Reds', _Reds_data, LUTSIZE) -Set1 = colors.LinearSegmentedColormap('Set1', _Set1_data, LUTSIZE) -Set2 = colors.LinearSegmentedColormap('Set2', _Set2_data, LUTSIZE) -Set3 = colors.LinearSegmentedColormap('Set3', _Set3_data, LUTSIZE) -Spectral = colors.LinearSegmentedColormap('Spectral', _Spectral_data, LUTSIZE) -YlGn = colors.LinearSegmentedColormap('YlGn', _YlGn_data, LUTSIZE) -YlGnBu = colors.LinearSegmentedColormap('YlGnBu', _YlGnBu_data, LUTSIZE) -YlOrBr = colors.LinearSegmentedColormap('YlOrBr', _YlOrBr_data, LUTSIZE) -YlOrRd = colors.LinearSegmentedColormap('YlOrRd', _YlOrRd_data, LUTSIZE) -gist_earth = colors.LinearSegmentedColormap('gist_earth', _gist_earth_data, LUTSIZE) -gist_gray = colors.LinearSegmentedColormap('gist_gray', _gist_gray_data, LUTSIZE) -gist_heat = colors.LinearSegmentedColormap('gist_heat', _gist_heat_data, LUTSIZE) -gist_ncar = colors.LinearSegmentedColormap('gist_ncar', _gist_ncar_data, LUTSIZE) -gist_rainbow = colors.LinearSegmentedColormap('gist_rainbow', _gist_rainbow_data, LUTSIZE) -gist_stern = colors.LinearSegmentedColormap('gist_stern', _gist_stern_data, LUTSIZE) -gist_yarg = colors.LinearSegmentedColormap('gist_yarg', _gist_yarg_data, LUTSIZE) +datad = { + 'autumn': _autumn_data, + 'bone': _bone_data, + 'binary': _binary_data, + 'cool': _cool_data, + 'copper': _copper_data, + 'flag': _flag_data, + 'gray' : _gray_data, + 'hot': _hot_data, + 'hsv': _hsv_data, + 'jet' : _jet_data, + 'pink': _pink_data, + 'prism': _prism_data, + 'spring': _spring_data, + 'summer': _summer_data, + 'winter': _winter_data, + 'spectral': _spectral_data + } + + datad['Accent']=_Accent_data datad['Blues']=_Blues_data datad['BrBG']=_BrBG_data @@ -5944,19 +5874,7 @@ datad['gist_stern']=_gist_stern_data datad['gist_yarg']=_gist_yarg_data -# reverse all the colormaps. -# reversed colormaps have '_r' appended to the name. -def revcmap(data): - data_r = {} - for key, val in data.iteritems(): - valnew = [(1.-a, b, c) for a, b, c in reversed(val)] - data_r[key] = valnew - return data_r -cmapnames = datad.keys() -for cmapname in cmapnames: - cmapname_r = cmapname+'_r' - cmapdat_r = revcmap(datad[cmapname]) - datad[cmapname_r] = cmapdat_r - locals()[cmapname_r] = colors.LinearSegmentedColormap(cmapname_r, cmapdat_r, LUTSIZE) + + Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2009-07-30 21:50:10 UTC (rev 7310) +++ trunk/matplotlib/lib/matplotlib/axes.py 2009-07-31 02:48:18 UTC (rev 7311) @@ -3911,12 +3911,12 @@ *bbox_to_anchor* keyword argument. bbox_to_anchor can be an instance of BboxBase(or its derivatives) or a tuple of 2 or 4 floats. For example, - + loc = 'upper right', bbox_to_anchor = (0.5, 0.5) will place the legend so that the upper right corner of the legend at the center of the axes. - + The legend location can be specified in other coordinate, by using the *bbox_transform* keyword. @@ -3946,7 +3946,7 @@ *fancybox*: [ None | False | True ] if True, draw a frame with a round fancybox. If None, use rc - + *shadow*: [ None | False | True ] If *True*, draw a shadow behind legend. If *None*, use rc settings. @@ -5172,9 +5172,9 @@ arguments will be used only if *c* is an array of floats. *cmap*: [ None | Colormap ] - A :class:`matplotlib.colors.Colormap` instance. If *None*, - defaults to rc ``image.cmap``. *cmap* is only used if *c* - is an array of floats. + A :class:`matplotlib.colors.Colormap` instance or registered + name. If *None*, defaults to rc ``image.cmap``. *cmap* is + only used if *c* is an array of floats. *norm*: [ None | Normalize ] A :class:`matplotlib.colors.Normalize` instance is used to @@ -5370,7 +5370,6 @@ if colors is None: if norm is not None: assert(isinstance(norm, mcolors.Normalize)) - if cmap is not None: assert(isinstance(cmap, mcolors.Colormap)) collection.set_array(np.asarray(c)) collection.set_cmap(cmap) collection.set_norm(norm) @@ -5712,7 +5711,6 @@ accum = bins.searchsorted(accum) if norm is not None: assert(isinstance(norm, mcolors.Normalize)) - if cmap is not None: assert(isinstance(cmap, mcolors.Colormap)) collection.set_array(accum) collection.set_cmap(cmap) collection.set_norm(norm) @@ -6245,7 +6243,6 @@ if not self._hold: self.cla() if norm is not None: assert(isinstance(norm, mcolors.Normalize)) - if cmap is not None: assert(isinstance(cmap, mcolors.Colormap)) if aspect is None: aspect = rcParams['image.aspect'] self.set_aspect(aspect) im = mimage.AxesImage(self, cmap, norm, interpolation, origin, extent, @@ -6490,7 +6487,6 @@ collection.set_alpha(alpha) collection.set_array(C) if norm is not None: assert(isinstance(norm, mcolors.Normalize)) - if cmap is not None: assert(isinstance(cmap, mcolors.Colormap)) collection.set_cmap(cmap) collection.set_norm(norm) if vmin is not None or vmax is not None: @@ -6612,7 +6608,6 @@ collection.set_alpha(alpha) collection.set_array(C) if norm is not None: assert(isinstance(norm, mcolors.Normalize)) - if cmap is not None: assert(isinstance(cmap, mcolors.Colormap)) collection.set_cmap(cmap) collection.set_norm(norm) if vmin is not None or vmax is not None: @@ -6719,7 +6714,6 @@ vmin = kwargs.pop('vmin', None) vmax = kwargs.pop('vmax', None) if norm is not None: assert(isinstance(norm, mcolors.Normalize)) - if cmap is not None: assert(isinstance(cmap, mcolors.Colormap)) C = args[-1] nr, nc = C.shape Modified: trunk/matplotlib/lib/matplotlib/cm.py =================================================================== --- trunk/matplotlib/lib/matplotlib/cm.py 2009-07-30 21:50:10 UTC (rev 7310) +++ trunk/matplotlib/lib/matplotlib/cm.py 2009-07-31 02:48:18 UTC (rev 7311) @@ -1,25 +1,68 @@ """ This module contains the instantiations of color mapping classes """ +import os +try: + import cPickle as pickle +except ImportError: + import pickle + import numpy as np from numpy import ma import matplotlib as mpl import matplotlib.colors as colors import matplotlib.cbook as cbook -from matplotlib._cm import * -# Dictionary for user-registered colormaps: +LUTSIZE = mpl.rcParams['image.lut'] + +_cmcache = os.path.join(mpl.get_configdir(), 'colormaps.cache') + +loaded = False +try: + c = open(_cmcache) + datad = pickle.load(c) + c.close() + mpl.verbose.report("Using colormaps from %s" % _cmcache) + loaded = True +except: + mpl.verbose.report("Could not load colormaps from %s" % _cmcache) + +if not loaded: + from matplotlib._cm import datad + + try: + c = open(_cmcache, 'w') + pickle.dump(datad, c, 2) + c.close() + mpl.verbose.report("New colormap cache in %s" % _cmcache) + except: + mpl.verbose.report("Failed to generate colormap cache") + cmap_d = dict() -# Using this second dictionary allows us to handle any -# Colormap instance; the built-in datad is only for -# LinearSegmentedColormaps. The advantage of keeping -# datad is that it delays the generation of the Colormap -# instance until it is actually needed. Generating the -# instance is fast enough, and typically done few enough -# times, that there is no need to cache the result. +# reverse all the colormaps. +# reversed colormaps have '_r' appended to the name. +def revcmap(data): + data_r = {} + for key, val in data.iteritems(): + valnew = [(1.0-a, b, c) for a, b, c in reversed(val)] + data_r[key] = valnew + return data_r + +_cmapnames = datad.keys() # need this list because datad is changed in loop +for cmapname in _cmapnames: + cmapname_r = cmapname+'_r' + cmapdat_r = revcmap(datad[cmapname]) + datad[cmapname_r] = cmapdat_r + cmap_d[cmapname] = colors.LinearSegmentedColormap( + cmapname, datad[cmapname], LUTSIZE) + cmap_d[cmapname_r] = colors.LinearSegmentedColormap( + cmapname_r, cmapdat_r, LUTSIZE) + +locals().update(cmap_d) + def register_cmap(name=None, cmap=None, data=None, lut=None): """ Add a colormap to the set recognized by :func:`get_cmap`. @@ -67,6 +110,11 @@ If *name* is a :class:`colors.Colormap` instance, it will be returned. + + If *lut* is not None it must be an integer giving the number of + entries desired in the lookup table, and *name* must be a + standard mpl colormap name with a corresponding data dictionary + in *datad*. """ if name is None: name = mpl.rcParams['image.cmap'] @@ -75,15 +123,13 @@ return name if name in cmap_d: - return cmap_d[name] + if lut is None: + return cmap_d[name] + elif name in datad: + return colors.LinearSegmentedColormap(name, datad[name], lut) + else: + raise ValueError("Colormap %s is not recognized" % name) - if name not in datad: - raise ValueError("%s is not a known colormap name" % name) - - if lut is None: - lut = mpl.rcParams['image.lut'] - return colors.LinearSegmentedColormap(name, datad[name], lut) - class ScalarMappable: """ This is a mixin class to support scalar -> RGBA mapping. Handles @@ -105,7 +151,7 @@ self._A = None self.norm = norm - self.cmap = cmap + self.cmap = get_cmap(cmap) self.colorbar = None self.update_dict = {'array':False} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ef...@us...> - 2009-07-31 05:22:49
|
Revision: 7312 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7312&view=rev Author: efiring Date: 2009-07-31 05:22:37 +0000 (Fri, 31 Jul 2009) Log Message: ----------- Removed the colormap data caching--it was trying to solve a non-problem. Upon installation, the colormap data in _cm.py is compiled into _cm.pyc, and importing that takes negligible time. Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/cm.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-07-31 02:48:18 UTC (rev 7311) +++ trunk/matplotlib/CHANGELOG 2009-07-31 05:22:37 UTC (rev 7312) @@ -1,7 +1,6 @@ 2009-07-30 Add set_cmap and register_cmap, and improve get_cmap, to provide convenient handling of user-generated - colormaps. Reorganized _cm and cm modules, and added - caching of the color data to reduce startup time. - EF + colormaps. Reorganized _cm and cm modules. - EF 2009-07-28 Quiver speed improved, thanks to tip by Ray Speth. -EF Modified: trunk/matplotlib/lib/matplotlib/cm.py =================================================================== --- trunk/matplotlib/lib/matplotlib/cm.py 2009-07-31 02:48:18 UTC (rev 7311) +++ trunk/matplotlib/lib/matplotlib/cm.py 2009-07-31 05:22:37 UTC (rev 7312) @@ -1,44 +1,20 @@ """ -This module contains the instantiations of color mapping classes +This module provides a large set of colormaps, functions for +registering new colormaps and for getting a colormap by name, +and a mixin class for adding color mapping functionality. + """ + import os -try: - import cPickle as pickle -except ImportError: - import pickle - import numpy as np from numpy import ma import matplotlib as mpl import matplotlib.colors as colors import matplotlib.cbook as cbook +from matplotlib._cm import datad -LUTSIZE = mpl.rcParams['image.lut'] -_cmcache = os.path.join(mpl.get_configdir(), 'colormaps.cache') - -loaded = False -try: - c = open(_cmcache) - datad = pickle.load(c) - c.close() - mpl.verbose.report("Using colormaps from %s" % _cmcache) - loaded = True -except: - mpl.verbose.report("Could not load colormaps from %s" % _cmcache) - -if not loaded: - from matplotlib._cm import datad - - try: - c = open(_cmcache, 'w') - pickle.dump(datad, c, 2) - c.close() - mpl.verbose.report("New colormap cache in %s" % _cmcache) - except: - mpl.verbose.report("Failed to generate colormap cache") - cmap_d = dict() # reverse all the colormaps. @@ -51,7 +27,10 @@ data_r[key] = valnew return data_r +LUTSIZE = mpl.rcParams['image.lut'] + _cmapnames = datad.keys() # need this list because datad is changed in loop + for cmapname in _cmapnames: cmapname_r = cmapname+'_r' cmapdat_r = revcmap(datad[cmapname]) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2009-07-31 13:15:29
|
Revision: 7313 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7313&view=rev Author: jdh2358 Date: 2009-07-31 13:15:16 +0000 (Fri, 31 Jul 2009) Log Message: ----------- make rgrids return grid, not tick, lines Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/projections/polar.py trunk/matplotlib/lib/matplotlib/pyplot.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-07-31 05:22:37 UTC (rev 7312) +++ trunk/matplotlib/CHANGELOG 2009-07-31 13:15:16 UTC (rev 7313) @@ -4421,4 +4421,3 @@ 2003-11-21 - make a dash-dot dict for the GC 2003-12-15 - fix install path bug -t Modified: trunk/matplotlib/lib/matplotlib/projections/polar.py =================================================================== --- trunk/matplotlib/lib/matplotlib/projections/polar.py 2009-07-31 05:22:37 UTC (rev 7312) +++ trunk/matplotlib/lib/matplotlib/projections/polar.py 2009-07-31 13:15:16 UTC (rev 7313) @@ -397,7 +397,7 @@ self._r_label2_position.clear().translate(angle, -self._rpad * rmax) for t in self.yaxis.get_ticklabels(): t.update(kwargs) - return self.yaxis.get_ticklines(), self.yaxis.get_ticklabels() + return self.yaxis.get_gridlines(), self.yaxis.get_ticklabels() set_rgrids.__doc__ = cbook.dedent(set_rgrids.__doc__) % kwdocd Modified: trunk/matplotlib/lib/matplotlib/pyplot.py =================================================================== --- trunk/matplotlib/lib/matplotlib/pyplot.py 2009-07-31 05:22:37 UTC (rev 7312) +++ trunk/matplotlib/lib/matplotlib/pyplot.py 2009-07-31 13:15:16 UTC (rev 7313) @@ -1102,7 +1102,7 @@ if not isinstance(ax, PolarAxes): raise RuntimeError('rgrids only defined for polar axes') if len(args)==0: - lines = ax.yaxis.get_ticklines() + lines = ax.yaxis.gridlines() labels = ax.yaxis.get_ticklabels() else: lines, labels = ax.set_rgrids(*args, **kwargs) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2009-07-31 13:33:15
|
Revision: 7315 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7315&view=rev Author: mdboom Date: 2009-07-31 13:33:06 +0000 (Fri, 31 Jul 2009) Log Message: ----------- Tagging 0.99.0.rc1 release Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/examples/pylab_examples/log_demo.py trunk/matplotlib/lib/matplotlib/__init__.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-07-31 13:28:27 UTC (rev 7314) +++ trunk/matplotlib/CHANGELOG 2009-07-31 13:33:06 UTC (rev 7315) @@ -1,3 +1,7 @@ +====================================================================== + +2009-07-31 Tagging 0.99.0.rc1 at 7314 - MGD + 2009-07-30 Add set_cmap and register_cmap, and improve get_cmap, to provide convenient handling of user-generated colormaps. Reorganized _cm and cm modules. - EF Modified: trunk/matplotlib/examples/pylab_examples/log_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/log_demo.py 2009-07-31 13:28:27 UTC (rev 7314) +++ trunk/matplotlib/examples/pylab_examples/log_demo.py 2009-07-31 13:33:06 UTC (rev 7315) @@ -19,7 +19,7 @@ # log x and y axis plt.subplot(223) -plt.loglog(t, 20*np.exp(-t/10.0), basex=4) +plt.loglog(t, 20*np.exp(-t/10.0), basex=2) plt.grid(True) plt.title('loglog base 4 on x') Modified: trunk/matplotlib/lib/matplotlib/__init__.py =================================================================== --- trunk/matplotlib/lib/matplotlib/__init__.py 2009-07-31 13:28:27 UTC (rev 7314) +++ trunk/matplotlib/lib/matplotlib/__init__.py 2009-07-31 13:33:06 UTC (rev 7315) @@ -89,7 +89,7 @@ """ from __future__ import generators -__version__ = '0.98.6svn' +__version__ = '0.99.0.rc1' __revision__ = '$Revision$' __date__ = '$Date$' This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2009-07-31 13:39:09
|
Revision: 7317 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7317&view=rev Author: jdh2358 Date: 2009-07-31 13:38:56 +0000 (Fri, 31 Jul 2009) Log Message: ----------- remove community choice vote from website Modified Paths: -------------- trunk/matplotlib/doc/_templates/indexsidebar.html trunk/matplotlib/doc/mpl_toolkits/mplot3d/api.rst trunk/matplotlib/doc/users/toolkits.rst trunk/matplotlib/examples/tests/backend_driver.py Modified: trunk/matplotlib/doc/_templates/indexsidebar.html =================================================================== --- trunk/matplotlib/doc/_templates/indexsidebar.html 2009-07-31 13:36:38 UTC (rev 7316) +++ trunk/matplotlib/doc/_templates/indexsidebar.html 2009-07-31 13:38:56 UTC (rev 7317) @@ -1,19 +1,13 @@ <h3>News</h3> + <p>Please <a href="http://sourceforge.net/project/project_donations.php?group_id=80706">donate</a> to support matplotlib development.</p> + <p>Watch a <a href="http://videolectures.net/mloss08_hunter_mat">video lecture</a> about matplotlib presented at <a href="http://videolectures.net/mloss08_whistler">NIPS 08 Workshop</a> <i>Machine Learning Open Source Software</i></a>. </p> -<p>Nominate matplotlib for a community choice award by clicking the -image below -- suggested category "Best Project for Academia" for -software which "helps you hit the books, analyze global trends, or -just understand the world a little bit better than you did before": -<a href="http://sourceforge.net/community/cca09/nominate/?project_name=matplotlib&project_url=http://sourceforge.net/projects/matplotlib/"><img src="http://sourceforge.net/images/cca/cca_nominate.png" border="0"/></a> -</p> - - <h3>Download</h3> <p>Current version: <b>{{ version }}</b></p> Modified: trunk/matplotlib/doc/mpl_toolkits/mplot3d/api.rst =================================================================== --- trunk/matplotlib/doc/mpl_toolkits/mplot3d/api.rst 2009-07-31 13:36:38 UTC (rev 7316) +++ trunk/matplotlib/doc/mpl_toolkits/mplot3d/api.rst 2009-07-31 13:38:56 UTC (rev 7317) @@ -7,7 +7,6 @@ .. automodule:: mpl_toolkits.mplot3d.axes3d :members: - :exclude-members: contour3D, contourf3D, plot3D, scatter3D :show-inheritance: :mod:`mpl_toolkits.mplot3d.art3d` Modified: trunk/matplotlib/doc/users/toolkits.rst =================================================================== --- trunk/matplotlib/doc/users/toolkits.rst 2009-07-31 13:36:38 UTC (rev 7316) +++ trunk/matplotlib/doc/users/toolkits.rst 2009-07-31 13:38:56 UTC (rev 7317) @@ -66,5 +66,5 @@ distributed with matplotlib source. .. image:: ../_static/demo_axes_grid.png - + See :ref:`toolkit_axesgrid-index` for documentations. Modified: trunk/matplotlib/examples/tests/backend_driver.py =================================================================== --- trunk/matplotlib/examples/tests/backend_driver.py 2009-07-31 13:36:38 UTC (rev 7316) +++ trunk/matplotlib/examples/tests/backend_driver.py 2009-07-31 13:38:56 UTC (rev 7317) @@ -336,7 +336,6 @@ for fullpath in testcases: print ('\tdriving %-40s' % (fullpath)), sys.stdout.flush() - fpath, fname = os.path.split(fullpath) if fname in exclude: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2009-07-31 13:42:33
|
Revision: 7314 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7314&view=rev Author: jdh2358 Date: 2009-07-31 13:28:27 +0000 (Fri, 31 Jul 2009) Log Message: ----------- fixed pyplot typo in gridlines Modified Paths: -------------- trunk/matplotlib/examples/tests/backend_driver.py trunk/matplotlib/lib/matplotlib/pyplot.py Modified: trunk/matplotlib/examples/tests/backend_driver.py =================================================================== --- trunk/matplotlib/examples/tests/backend_driver.py 2009-07-31 13:15:16 UTC (rev 7313) +++ trunk/matplotlib/examples/tests/backend_driver.py 2009-07-31 13:28:27 UTC (rev 7314) @@ -392,7 +392,8 @@ doc = __doc__.split('\n\n') op = OptionParser(description=doc[0].strip(), usage='%prog [options] [--] [backends and switches]', - epilog='\n'.join(doc[1:])) + #epilog='\n'.join(doc[1:]) # epilog not supported on my python2.4 machine: JDH + ) op.disable_interspersed_args() op.set_defaults(dirs='pylab,api,units,mplot3d', clean=False, coverage=False, valgrind=False) Modified: trunk/matplotlib/lib/matplotlib/pyplot.py =================================================================== --- trunk/matplotlib/lib/matplotlib/pyplot.py 2009-07-31 13:15:16 UTC (rev 7313) +++ trunk/matplotlib/lib/matplotlib/pyplot.py 2009-07-31 13:28:27 UTC (rev 7314) @@ -1102,7 +1102,7 @@ if not isinstance(ax, PolarAxes): raise RuntimeError('rgrids only defined for polar axes') if len(args)==0: - lines = ax.yaxis.gridlines() + lines = ax.yaxis.get_gridlines() labels = ax.yaxis.get_ticklabels() else: lines, labels = ax.set_rgrids(*args, **kwargs) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jo...@us...> - 2009-08-03 20:06:11
|
Revision: 7339 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7339&view=rev Author: jouni Date: 2009-08-03 20:06:02 +0000 (Mon, 03 Aug 2009) Log Message: ----------- Merged revisions 7338 via svnmerge from https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/v0_99_maint ........ r7338 | jouni | 2009-08-03 22:41:32 +0300 (Mon, 03 Aug 2009) | 2 lines Fixed boilerplate.py so it doesn't break the ReST docs. ........ Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/boilerplate.py trunk/matplotlib/lib/matplotlib/pyplot.py Property Changed: ---------------- trunk/matplotlib/ trunk/matplotlib/doc/pyplots/README trunk/matplotlib/doc/sphinxext/gen_gallery.py trunk/matplotlib/doc/sphinxext/gen_rst.py trunk/matplotlib/examples/misc/multiprocess.py trunk/matplotlib/examples/mplot3d/contour3d_demo.py trunk/matplotlib/examples/mplot3d/contourf3d_demo.py trunk/matplotlib/examples/mplot3d/polys3d_demo.py trunk/matplotlib/examples/mplot3d/scatter3d_demo.py trunk/matplotlib/examples/mplot3d/surface3d_demo.py trunk/matplotlib/examples/mplot3d/wire3d_demo.py trunk/matplotlib/lib/matplotlib/sphinxext/mathmpl.py trunk/matplotlib/lib/matplotlib/sphinxext/only_directives.py trunk/matplotlib/lib/matplotlib/sphinxext/plot_directive.py Property changes on: trunk/matplotlib ___________________________________________________________________ Modified: svnmerge-integrated - /branches/mathtex:1-7263 /branches/v0_98_5_maint:1-7253 /branches/v0_99_maint:1-7318 + /branches/mathtex:1-7263 /branches/v0_98_5_maint:1-7253 /branches/v0_99_maint:1-7318,7338 Modified: svn:mergeinfo - /branches/v0_91_maint:5753-5771 /branches/v0_98_5_maint:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080,7176,7209-7211,7227,7245 + /branches/v0_91_maint:5753-5771 /branches/v0_98_5_maint:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080,7176,7209-7211,7227,7245 /branches/v0_99_maint:7338 Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-08-03 19:41:32 UTC (rev 7338) +++ trunk/matplotlib/CHANGELOG 2009-08-03 20:06:02 UTC (rev 7339) @@ -1,3 +1,5 @@ +2009-08-03 Fixed boilerplate.py so it doesn't break the ReST docs. - JKS + ====================================================================== 2009-07-31 Tagging 0.99.0.rc1 at 7314 - MGD Modified: trunk/matplotlib/boilerplate.py =================================================================== --- trunk/matplotlib/boilerplate.py 2009-08-03 19:41:32 UTC (rev 7338) +++ trunk/matplotlib/boilerplate.py 2009-08-03 20:06:02 UTC (rev 7339) @@ -21,7 +21,6 @@ # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def %(func)s(%(argspec)s): - %(docstring)s %(ax)s = gca() # allow callers to override the hold state by passing hold=True|False %(washold)s = %(ax)s.ishold() @@ -35,16 +34,19 @@ %(ax)s.hold(%(washold)s) %(mappable)s return %(ret)s +if Axes.%(func)s.__doc__ is not None: + %(func)s.__doc__ = dedent(Axes.%(func)s.__doc__) + __docstring_addendum """ _fmtmisc = """\ # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def %(func)s(%(argspec)s): - %(docstring)s %(ret)s = gca().%(func)s(%(call)s) draw_if_interactive() return %(ret)s +if Axes.%(func)s.__doc__ is not None: + %(func)s.__doc__ = dedent(Axes.%(func)s.__doc__) """ # these methods are all simple wrappers of Axes methods by the same @@ -138,19 +140,6 @@ """ return '\n'.join(x.rstrip() for x in string.split('\n')) -def make_docstring(cmd, mention_hold): - func = getattr(Axes, cmd) - docstring = inspect.getdoc(func) - if docstring is None: - return "" - escaped = re.sub(r'\\', r'\\\\', docstring) - if mention_hold: - escaped += ''' - -Additional kwargs: hold = [True|False] overrides default hold state -''' - return '"""'+escaped+'"""' - for fmt,cmdlist in (_fmtplot,_plotcommands),(_fmtmisc,_misccommands): for func in cmdlist: # For some commands, an additional line is needed to set the @@ -160,9 +149,6 @@ else: mappable = '' - # Format docstring - docstring = make_docstring(func, fmt is _fmtplot) - # Get argspec of wrapped function args, varargs, varkw, defaults = inspect.getargspec(getattr(Axes, func)) args.pop(0) # remove 'self' argument Property changes on: trunk/matplotlib/doc/pyplots/README ___________________________________________________________________ Modified: svn:mergeinfo - /branches/v0_98_5_maint/doc/pyplots/README:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080,7176,7209-7211,7227,7245 + /branches/v0_98_5_maint/doc/pyplots/README:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080,7176,7209-7211,7227,7245 /branches/v0_99_maint/doc/pyplots/README:7338 Property changes on: trunk/matplotlib/doc/sphinxext/gen_gallery.py ___________________________________________________________________ Modified: svn:mergeinfo - /branches/v0_91_maint/doc/_templates/gen_gallery.py:5753-5771 /branches/v0_98_5_maint/doc/sphinxext/gen_gallery.py:6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080,7176,7209-7211,7227,7245 + /branches/v0_91_maint/doc/_templates/gen_gallery.py:5753-5771 /branches/v0_98_5_maint/doc/sphinxext/gen_gallery.py:6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080,7176,7209-7211,7227,7245 /branches/v0_99_maint/doc/sphinxext/gen_gallery.py:7338 Property changes on: trunk/matplotlib/doc/sphinxext/gen_rst.py ___________________________________________________________________ Modified: svn:mergeinfo - /branches/v0_91_maint/doc/examples/gen_rst.py:5753-5771 /branches/v0_98_5_maint/doc/sphinxext/gen_rst.py:6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080,7176,7209-7211,7227,7245 + /branches/v0_91_maint/doc/examples/gen_rst.py:5753-5771 /branches/v0_98_5_maint/doc/sphinxext/gen_rst.py:6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080,7176,7209-7211,7227,7245 /branches/v0_99_maint/doc/sphinxext/gen_rst.py:7338 Property changes on: trunk/matplotlib/examples/misc/multiprocess.py ___________________________________________________________________ Modified: svn:mergeinfo - /branches/v0_91_maint/examples/misc/log.py:5753-5771 /branches/v0_98_5_maint/examples/misc/log.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080 + /branches/v0_91_maint/examples/misc/log.py:5753-5771 /branches/v0_98_5_maint/examples/misc/log.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080 /branches/v0_99_maint/examples/misc/multiprocess.py:7338 Property changes on: trunk/matplotlib/examples/mplot3d/contour3d_demo.py ___________________________________________________________________ Modified: svn:mergeinfo - /branches/v0_91_maint/examples/mplot3d/contour.py:5753-5771 /branches/v0_98_5_maint/examples/mplot3d/contour.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080 + /branches/v0_91_maint/examples/mplot3d/contour.py:5753-5771 /branches/v0_98_5_maint/examples/mplot3d/contour.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080 /branches/v0_99_maint/examples/mplot3d/contour3d_demo.py:7338 Property changes on: trunk/matplotlib/examples/mplot3d/contourf3d_demo.py ___________________________________________________________________ Modified: svn:mergeinfo - /branches/v0_91_maint/examples/mplot3d/contourf.py:5753-5771 /branches/v0_98_5_maint/examples/mplot3d/contourf.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080 + /branches/v0_91_maint/examples/mplot3d/contourf.py:5753-5771 /branches/v0_98_5_maint/examples/mplot3d/contourf.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080 /branches/v0_99_maint/examples/mplot3d/contourf3d_demo.py:7338 Property changes on: trunk/matplotlib/examples/mplot3d/polys3d_demo.py ___________________________________________________________________ Modified: svn:mergeinfo - /branches/v0_91_maint/examples/mplot3d/polys.py:5753-5771 /branches/v0_98_5_maint/examples/mplot3d/polys.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080 + /branches/v0_91_maint/examples/mplot3d/polys.py:5753-5771 /branches/v0_98_5_maint/examples/mplot3d/polys.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080 /branches/v0_99_maint/examples/mplot3d/polys3d_demo.py:7338 Property changes on: trunk/matplotlib/examples/mplot3d/scatter3d_demo.py ___________________________________________________________________ Modified: svn:mergeinfo - /branches/v0_91_maint/examples/mplot3d/scatter.py:5753-5771 /branches/v0_98_5_maint/examples/mplot3d/scatter.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080 + /branches/v0_91_maint/examples/mplot3d/scatter.py:5753-5771 /branches/v0_98_5_maint/examples/mplot3d/scatter.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080 /branches/v0_99_maint/examples/mplot3d/scatter3d_demo.py:7338 Property changes on: trunk/matplotlib/examples/mplot3d/surface3d_demo.py ___________________________________________________________________ Modified: svn:mergeinfo - /branches/v0_91_maint/examples/mplot3d/surface.py:5753-5771 /branches/v0_98_5_maint/examples/mplot3d/surface.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080 + /branches/v0_91_maint/examples/mplot3d/surface.py:5753-5771 /branches/v0_98_5_maint/examples/mplot3d/surface.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080 /branches/v0_99_maint/examples/mplot3d/surface3d_demo.py:7338 Property changes on: trunk/matplotlib/examples/mplot3d/wire3d_demo.py ___________________________________________________________________ Modified: svn:mergeinfo - /branches/v0_91_maint/examples/mplot3d/wire.py:5753-5771 /branches/v0_98_5_maint/examples/mplot3d/wire.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080 + /branches/v0_91_maint/examples/mplot3d/wire.py:5753-5771 /branches/v0_98_5_maint/examples/mplot3d/wire.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080 /branches/v0_99_maint/examples/mplot3d/wire3d_demo.py:7338 Modified: trunk/matplotlib/lib/matplotlib/pyplot.py =================================================================== --- trunk/matplotlib/lib/matplotlib/pyplot.py 2009-08-03 19:41:32 UTC (rev 7338) +++ trunk/matplotlib/lib/matplotlib/pyplot.py 2009-08-03 20:06:02 UTC (rev 7339) @@ -1608,72 +1608,17 @@ draw_if_interactive() +# This is added to docstrings of autogenerated plotting functions +__docstring_addendum = """ + +Additional kwargs: hold = [True|False] overrides default hold state""" + ## Plotting part 2: autogenerated wrappers for axes methods ## # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def acorr(x, hold=None, **kwargs): - """call signature:: - - acorr(x, normed=True, detrend=mlab.detrend_none, usevlines=True, - maxlags=10, **kwargs) - -Plot the autocorrelation of *x*. If *normed* = *True*, -normalize the data by the autocorrelation at 0-th lag. *x* is -detrended by the *detrend* callable (default no normalization). - -Data are plotted as ``plot(lags, c, **kwargs)`` - -Return value is a tuple (*lags*, *c*, *line*) where: - - - *lags* are a length 2*maxlags+1 lag vector - - - *c* is the 2*maxlags+1 auto correlation vector - - - *line* is a :class:`~matplotlib.lines.Line2D` instance - returned by :meth:`plot` - -The default *linestyle* is None and the default *marker* is -``'o'``, though these can be overridden with keyword args. -The cross correlation is performed with -:func:`numpy.correlate` with *mode* = 2. - -If *usevlines* is *True*, :meth:`~matplotlib.axes.Axes.vlines` -rather than :meth:`~matplotlib.axes.Axes.plot` is used to draw -vertical lines from the origin to the acorr. Otherwise, the -plot style is determined by the kwargs, which are -:class:`~matplotlib.lines.Line2D` properties. - -*maxlags* is a positive integer detailing the number of lags -to show. The default value of *None* will return all -:math:`2 \\mathrm{len}(x) - 1` lags. - -The return value is a tuple (*lags*, *c*, *linecol*, *b*) -where - -- *linecol* is the - :class:`~matplotlib.collections.LineCollection` - -- *b* is the *x*-axis. - -.. seealso:: - - :meth:`~matplotlib.axes.Axes.plot` or - :meth:`~matplotlib.axes.Axes.vlines` - For documentation on valid kwargs. - -**Example:** - -:func:`~matplotlib.pyplot.xcorr` above, and -:func:`~matplotlib.pyplot.acorr` below. - -**Example:** - -.. plot:: mpl_examples/pylab_examples/xcorr_demo.py - -Additional kwargs: hold = [True|False] overrides default hold state -""" ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() @@ -1687,51 +1632,12 @@ ax.hold(washold) return ret +if Axes.acorr.__doc__ is not None: + acorr.__doc__ = dedent(Axes.acorr.__doc__) + __docstring_addendum # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def arrow(x, y, dx, dy, hold=None, **kwargs): - """call signature:: - - arrow(x, y, dx, dy, **kwargs) - -Draws arrow on specified axis from (*x*, *y*) to (*x* + *dx*, -*y* + *dy*). - -Optional kwargs control the arrow properties: - alpha: float (0.0 transparent through 1.0 opaque) - animated: [True | False] - antialiased or aa: [True | False] or None for default - axes: an :class:`~matplotlib.axes.Axes` instance - clip_box: a :class:`matplotlib.transforms.Bbox` instance - clip_on: [True | False] - clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] - color: matplotlib color arg or sequence of rgba tuples - contains: a callable function - edgecolor or ec: mpl color spec, or None for default, or 'none' for no color - facecolor or fc: mpl color spec, or None for default, or 'none' for no color - figure: a :class:`matplotlib.figure.Figure` instance - fill: [True | False] - gid: an id string - hatch: [ '/' | '\\\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*' ] - label: any string - linestyle or ls: ['solid' | 'dashed' | 'dashdot' | 'dotted'] - linewidth or lw: float or None for default - lod: [True | False] - picker: [None|float|boolean|callable] - rasterized: [True | False | None] - snap: unknown - transform: :class:`~matplotlib.transforms.Transform` instance - url: a url string - visible: [True | False] - zorder: any number - -**Example:** - -.. plot:: mpl_examples/pylab_examples/arrow_demo.py - -Additional kwargs: hold = [True|False] overrides default hold state -""" ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() @@ -1745,90 +1651,12 @@ ax.hold(washold) return ret +if Axes.arrow.__doc__ is not None: + arrow.__doc__ = dedent(Axes.arrow.__doc__) + __docstring_addendum # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def axhline(y=0, xmin=0, xmax=1, hold=None, **kwargs): - """call signature:: - - axhline(y=0, xmin=0, xmax=1, **kwargs) - -Axis Horizontal Line - -Draw a horizontal line at *y* from *xmin* to *xmax*. With the -default values of *xmin* = 0 and *xmax* = 1, this line will -always span the horizontal extent of the axes, regardless of -the xlim settings, even if you change them, eg. with the -:meth:`set_xlim` command. That is, the horizontal extent is -in axes coords: 0=left, 0.5=middle, 1.0=right but the *y* -location is in data coordinates. - -Return value is the :class:`~matplotlib.lines.Line2D` -instance. kwargs are the same as kwargs to plot, and can be -used to control the line properties. Eg., - -* draw a thick red hline at *y* = 0 that spans the xrange - - >>> axhline(linewidth=4, color='r') - -* draw a default hline at *y* = 1 that spans the xrange - - >>> axhline(y=1) - -* draw a default hline at *y* = .5 that spans the the middle half of - the xrange - - >>> axhline(y=.5, xmin=0.25, xmax=0.75) - -Valid kwargs are :class:`~matplotlib.lines.Line2D` properties: - - alpha: float (0.0 transparent through 1.0 opaque) - animated: [True | False] - antialiased or aa: [True | False] - axes: an :class:`~matplotlib.axes.Axes` instance - clip_box: a :class:`matplotlib.transforms.Bbox` instance - clip_on: [True | False] - clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] - color or c: any matplotlib color - contains: a callable function - dash_capstyle: ['butt' | 'round' | 'projecting'] - dash_joinstyle: ['miter' | 'round' | 'bevel'] - dashes: sequence of on/off ink in points - data: 2D array - drawstyle: [ 'default' | 'steps' | 'steps-pre' | 'steps-mid' | 'steps-post' ] - figure: a :class:`matplotlib.figure.Figure` instance - fillstyle: ['full' | 'left' | 'right' | 'bottom' | 'top'] - gid: an id string - label: any string - linestyle or ls: [ '-' | '--' | '-.' | ':' | 'None' | ' ' | '' ] and any drawstyle in combination with a linestyle, e.g. 'steps--'. - linewidth or lw: float value in points - lod: [True | False] - marker: [ '+' | '*' | ',' | '.' | '1' | '2' | '3' | '4' | '<' | '>' | 'D' | 'H' | '^' | '_' | 'd' | 'h' | 'o' | 'p' | 's' | 'v' | 'x' | '|' | TICKUP | TICKDOWN | TICKLEFT | TICKRIGHT | 'None' | ' ' | '' ] - markeredgecolor or mec: any matplotlib color - markeredgewidth or mew: float value in points - markerfacecolor or mfc: any matplotlib color - markersize or ms: float - markevery: None | integer | (startind, stride) - picker: float distance in points or callable pick function ``fn(artist, event)`` - pickradius: float distance in points - rasterized: [True | False | None] - snap: unknown - solid_capstyle: ['butt' | 'round' | 'projecting'] - solid_joinstyle: ['miter' | 'round' | 'bevel'] - transform: a :class:`matplotlib.transforms.Transform` instance - url: a url string - visible: [True | False] - xdata: 1D array - ydata: 1D array - zorder: any number - -.. seealso:: - - :meth:`axhspan` - for example plot and source code - -Additional kwargs: hold = [True|False] overrides default hold state -""" ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() @@ -1842,72 +1670,12 @@ ax.hold(washold) return ret +if Axes.axhline.__doc__ is not None: + axhline.__doc__ = dedent(Axes.axhline.__doc__) + __docstring_addendum # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def axhspan(ymin, ymax, xmin=0, xmax=1, hold=None, **kwargs): - """call signature:: - - axhspan(ymin, ymax, xmin=0, xmax=1, **kwargs) - -Axis Horizontal Span. - -*y* coords are in data units and *x* coords are in axes (relative -0-1) units. - -Draw a horizontal span (rectangle) from *ymin* to *ymax*. -With the default values of *xmin* = 0 and *xmax* = 1, this -always spans the xrange, regardless of the xlim settings, even -if you change them, eg. with the :meth:`set_xlim` command. -That is, the horizontal extent is in axes coords: 0=left, -0.5=middle, 1.0=right but the *y* location is in data -coordinates. - -Return value is a :class:`matplotlib.patches.Polygon` -instance. - -Examples: - -* draw a gray rectangle from *y* = 0.25-0.75 that spans the - horizontal extent of the axes - - >>> axhspan(0.25, 0.75, facecolor='0.5', alpha=0.5) - -Valid kwargs are :class:`~matplotlib.patches.Polygon` properties: - - alpha: float (0.0 transparent through 1.0 opaque) - animated: [True | False] - antialiased or aa: [True | False] or None for default - axes: an :class:`~matplotlib.axes.Axes` instance - clip_box: a :class:`matplotlib.transforms.Bbox` instance - clip_on: [True | False] - clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] - color: matplotlib color arg or sequence of rgba tuples - contains: a callable function - edgecolor or ec: mpl color spec, or None for default, or 'none' for no color - facecolor or fc: mpl color spec, or None for default, or 'none' for no color - figure: a :class:`matplotlib.figure.Figure` instance - fill: [True | False] - gid: an id string - hatch: [ '/' | '\\\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*' ] - label: any string - linestyle or ls: ['solid' | 'dashed' | 'dashdot' | 'dotted'] - linewidth or lw: float or None for default - lod: [True | False] - picker: [None|float|boolean|callable] - rasterized: [True | False | None] - snap: unknown - transform: :class:`~matplotlib.transforms.Transform` instance - url: a url string - visible: [True | False] - zorder: any number - -**Example:** - -.. plot:: mpl_examples/pylab_examples/axhspan_demo.py - -Additional kwargs: hold = [True|False] overrides default hold state -""" ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() @@ -1921,90 +1689,12 @@ ax.hold(washold) return ret +if Axes.axhspan.__doc__ is not None: + axhspan.__doc__ = dedent(Axes.axhspan.__doc__) + __docstring_addendum # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def axvline(x=0, ymin=0, ymax=1, hold=None, **kwargs): - """call signature:: - - axvline(x=0, ymin=0, ymax=1, **kwargs) - -Axis Vertical Line - -Draw a vertical line at *x* from *ymin* to *ymax*. With the -default values of *ymin* = 0 and *ymax* = 1, this line will -always span the vertical extent of the axes, regardless of the -ylim settings, even if you change them, eg. with the -:meth:`set_ylim` command. That is, the vertical extent is in -axes coords: 0=bottom, 0.5=middle, 1.0=top but the *x* location -is in data coordinates. - -Return value is the :class:`~matplotlib.lines.Line2D` -instance. kwargs are the same as kwargs to plot, and can be -used to control the line properties. Eg., - -* draw a thick red vline at *x* = 0 that spans the yrange - - >>> axvline(linewidth=4, color='r') - -* draw a default vline at *x* = 1 that spans the yrange - - >>> axvline(x=1) - -* draw a default vline at *x* = .5 that spans the the middle half of - the yrange - - >>> axvline(x=.5, ymin=0.25, ymax=0.75) - -Valid kwargs are :class:`~matplotlib.lines.Line2D` properties: - - alpha: float (0.0 transparent through 1.0 opaque) - animated: [True | False] - antialiased or aa: [True | False] - axes: an :class:`~matplotlib.axes.Axes` instance - clip_box: a :class:`matplotlib.transforms.Bbox` instance - clip_on: [True | False] - clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] - color or c: any matplotlib color - contains: a callable function - dash_capstyle: ['butt' | 'round' | 'projecting'] - dash_joinstyle: ['miter' | 'round' | 'bevel'] - dashes: sequence of on/off ink in points - data: 2D array - drawstyle: [ 'default' | 'steps' | 'steps-pre' | 'steps-mid' | 'steps-post' ] - figure: a :class:`matplotlib.figure.Figure` instance - fillstyle: ['full' | 'left' | 'right' | 'bottom' | 'top'] - gid: an id string - label: any string - linestyle or ls: [ '-' | '--' | '-.' | ':' | 'None' | ' ' | '' ] and any drawstyle in combination with a linestyle, e.g. 'steps--'. - linewidth or lw: float value in points - lod: [True | False] - marker: [ '+' | '*' | ',' | '.' | '1' | '2' | '3' | '4' | '<' | '>' | 'D' | 'H' | '^' | '_' | 'd' | 'h' | 'o' | 'p' | 's' | 'v' | 'x' | '|' | TICKUP | TICKDOWN | TICKLEFT | TICKRIGHT | 'None' | ' ' | '' ] - markeredgecolor or mec: any matplotlib color - markeredgewidth or mew: float value in points - markerfacecolor or mfc: any matplotlib color - markersize or ms: float - markevery: None | integer | (startind, stride) - picker: float distance in points or callable pick function ``fn(artist, event)`` - pickradius: float distance in points - rasterized: [True | False | None] - snap: unknown - solid_capstyle: ['butt' | 'round' | 'projecting'] - solid_joinstyle: ['miter' | 'round' | 'bevel'] - transform: a :class:`matplotlib.transforms.Transform` instance - url: a url string - visible: [True | False] - xdata: 1D array - ydata: 1D array - zorder: any number - -.. seealso:: - - :meth:`axhspan` - for example plot and source code - -Additional kwargs: hold = [True|False] overrides default hold state -""" ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() @@ -2018,73 +1708,12 @@ ax.hold(washold) return ret +if Axes.axvline.__doc__ is not None: + axvline.__doc__ = dedent(Axes.axvline.__doc__) + __docstring_addendum # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def axvspan(xmin, xmax, ymin=0, ymax=1, hold=None, **kwargs): - """call signature:: - - axvspan(xmin, xmax, ymin=0, ymax=1, **kwargs) - -Axis Vertical Span. - -*x* coords are in data units and *y* coords are in axes (relative -0-1) units. - -Draw a vertical span (rectangle) from *xmin* to *xmax*. With -the default values of *ymin* = 0 and *ymax* = 1, this always -spans the yrange, regardless of the ylim settings, even if you -change them, eg. with the :meth:`set_ylim` command. That is, -the vertical extent is in axes coords: 0=bottom, 0.5=middle, -1.0=top but the *y* location is in data coordinates. - -Return value is the :class:`matplotlib.patches.Polygon` -instance. - -Examples: - -* draw a vertical green translucent rectangle from x=1.25 to 1.55 that - spans the yrange of the axes - - >>> axvspan(1.25, 1.55, facecolor='g', alpha=0.5) - -Valid kwargs are :class:`~matplotlib.patches.Polygon` -properties: - - alpha: float (0.0 transparent through 1.0 opaque) - animated: [True | False] - antialiased or aa: [True | False] or None for default - axes: an :class:`~matplotlib.axes.Axes` instance - clip_box: a :class:`matplotlib.transforms.Bbox` instance - clip_on: [True | False] - clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] - color: matplotlib color arg or sequence of rgba tuples - contains: a callable function - edgecolor or ec: mpl color spec, or None for default, or 'none' for no color - facecolor or fc: mpl color spec, or None for default, or 'none' for no color - figure: a :class:`matplotlib.figure.Figure` instance - fill: [True | False] - gid: an id string - hatch: [ '/' | '\\\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*' ] - label: any string - linestyle or ls: ['solid' | 'dashed' | 'dashdot' | 'dotted'] - linewidth or lw: float or None for default - lod: [True | False] - picker: [None|float|boolean|callable] - rasterized: [True | False | None] - snap: unknown - transform: :class:`~matplotlib.transforms.Transform` instance - url: a url string - visible: [True | False] - zorder: any number - -.. seealso:: - - :meth:`axhspan` - for example plot and source code - -Additional kwargs: hold = [True|False] overrides default hold state -""" ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() @@ -2098,110 +1727,12 @@ ax.hold(washold) return ret +if Axes.axvspan.__doc__ is not None: + axvspan.__doc__ = dedent(Axes.axvspan.__doc__) + __docstring_addendum # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def bar(left, height, width=0.80000000000000004, bottom=None, color=None, edgecolor=None, linewidth=None, yerr=None, xerr=None, ecolor=None, capsize=3, align='edge', orientation='vertical', log=False, hold=None, **kwargs): - """call signature:: - - bar(left, height, width=0.8, bottom=0, - color=None, edgecolor=None, linewidth=None, - yerr=None, xerr=None, ecolor=None, capsize=3, - align='edge', orientation='vertical', log=False) - -Make a bar plot with rectangles bounded by: - - *left*, *left* + *width*, *bottom*, *bottom* + *height* - (left, right, bottom and top edges) - -*left*, *height*, *width*, and *bottom* can be either scalars -or sequences - -Return value is a list of -:class:`matplotlib.patches.Rectangle` instances. - -Required arguments: - - ======== =============================================== - Argument Description - ======== =============================================== - *left* the x coordinates of the left sides of the bars - *height* the heights of the bars - ======== =============================================== - -Optional keyword arguments: - - =============== ========================================== - Keyword Description - =============== ========================================== - *width* the widths of the bars - *bottom* the y coordinates of the bottom edges of - the bars - *color* the colors of the bars - *edgecolor* the colors of the bar edges - *linewidth* width of bar edges; None means use default - linewidth; 0 means don't draw edges. - *xerr* if not None, will be used to generate - errorbars on the bar chart - *yerr* if not None, will be used to generate - errorbars on the bar chart - *ecolor* specifies the color of any errorbar - *capsize* (default 3) determines the length in - points of the error bar caps - *align* 'edge' (default) | 'center' - *orientation* 'vertical' | 'horizontal' - *log* [False|True] False (default) leaves the - orientation axis as-is; True sets it to - log scale - =============== ========================================== - -For vertical bars, *align* = 'edge' aligns bars by their left -edges in left, while *align* = 'center' interprets these -values as the *x* coordinates of the bar centers. For -horizontal bars, *align* = 'edge' aligns bars by their bottom -edges in bottom, while *align* = 'center' interprets these -values as the *y* coordinates of the bar centers. - -The optional arguments *color*, *edgecolor*, *linewidth*, -*xerr*, and *yerr* can be either scalars or sequences of -length equal to the number of bars. This enables you to use -bar as the basis for stacked bar charts, or candlestick plots. - -Other optional kwargs: - - alpha: float (0.0 transparent through 1.0 opaque) - animated: [True | False] - antialiased or aa: [True | False] or None for default - axes: an :class:`~matplotlib.axes.Axes` instance - clip_box: a :class:`matplotlib.transforms.Bbox` instance - clip_on: [True | False] - clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] - color: matplotlib color arg or sequence of rgba tuples - contains: a callable function - edgecolor or ec: mpl color spec, or None for default, or 'none' for no color - facecolor or fc: mpl color spec, or None for default, or 'none' for no color - figure: a :class:`matplotlib.figure.Figure` instance - fill: [True | False] - gid: an id string - hatch: [ '/' | '\\\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*' ] - label: any string - linestyle or ls: ['solid' | 'dashed' | 'dashdot' | 'dotted'] - linewidth or lw: float or None for default - lod: [True | False] - picker: [None|float|boolean|callable] - rasterized: [True | False | None] - snap: unknown - transform: :class:`~matplotlib.transforms.Transform` instance - url: a url string - visible: [True | False] - zorder: any number - -**Example:** A stacked bar chart. - -.. plot:: mpl_examples/pylab_examples/bar_stacked.py - -Additional kwargs: hold = [True|False] overrides default hold state -""" ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() @@ -2215,100 +1746,12 @@ ax.hold(washold) return ret +if Axes.bar.__doc__ is not None: + bar.__doc__ = dedent(Axes.bar.__doc__) + __docstring_addendum # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def barh(bottom, width, height=0.80000000000000004, left=None, hold=None, **kwargs): - """call signature:: - - barh(bottom, width, height=0.8, left=0, **kwargs) - -Make a horizontal bar plot with rectangles bounded by: - - *left*, *left* + *width*, *bottom*, *bottom* + *height* - (left, right, bottom and top edges) - -*bottom*, *width*, *height*, and *left* can be either scalars -or sequences - -Return value is a list of -:class:`matplotlib.patches.Rectangle` instances. - -Required arguments: - - ======== ====================================================== - Argument Description - ======== ====================================================== - *bottom* the vertical positions of the bottom edges of the bars - *width* the lengths of the bars - ======== ====================================================== - -Optional keyword arguments: - - =============== ========================================== - Keyword Description - =============== ========================================== - *height* the heights (thicknesses) of the bars - *left* the x coordinates of the left edges of the - bars - *color* the colors of the bars - *edgecolor* the colors of the bar edges - *linewidth* width of bar edges; None means use default - linewidth; 0 means don't draw edges. - *xerr* if not None, will be used to generate - errorbars on the bar chart - *yerr* if not None, will be used to generate - errorbars on the bar chart - *ecolor* specifies the color of any errorbar - *capsize* (default 3) determines the length in - points of the error bar caps - *align* 'edge' (default) | 'center' - *log* [False|True] False (default) leaves the - horizontal axis as-is; True sets it to log - scale - =============== ========================================== - -Setting *align* = 'edge' aligns bars by their bottom edges in -bottom, while *align* = 'center' interprets these values as -the *y* coordinates of the bar centers. - -The optional arguments *color*, *edgecolor*, *linewidth*, -*xerr*, and *yerr* can be either scalars or sequences of -length equal to the number of bars. This enables you to use -barh as the basis for stacked bar charts, or candlestick -plots. - -other optional kwargs: - - alpha: float (0.0 transparent through 1.0 opaque) - animated: [True | False] - antialiased or aa: [True | False] or None for default - axes: an :class:`~matplotlib.axes.Axes` instance - clip_box: a :class:`matplotlib.transforms.Bbox` instance - clip_on: [True | False] - clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] - color: matplotlib color arg or sequence of rgba tuples - contains: a callable function - edgecolor or ec: mpl color spec, or None for default, or 'none' for no color - facecolor or fc: mpl color spec, or None for default, or 'none' for no color - figure: a :class:`matplotlib.figure.Figure` instance - fill: [True | False] - gid: an id string - hatch: [ '/' | '\\\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*' ] - label: any string - linestyle or ls: ['solid' | 'dashed' | 'dashdot' | 'dotted'] - linewidth or lw: float or None for default - lod: [True | False] - picker: [None|float|boolean|callable] - rasterized: [True | False | None] - snap: unknown - transform: :class:`~matplotlib.transforms.Transform` instance - url: a url string - visible: [True | False] - zorder: any number - -Additional kwargs: hold = [True|False] overrides default hold state -""" ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() @@ -2322,77 +1765,12 @@ ax.hold(washold) return ret +if Axes.barh.__doc__ is not None: + barh.__doc__ = dedent(Axes.barh.__doc__) + __docstring_addendum # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def broken_barh(xranges, yrange, hold=None, **kwargs): - """call signature:: - - broken_barh(self, xranges, yrange, **kwargs) - -A collection of horizontal bars spanning *yrange* with a sequence of -*xranges*. - -Required arguments: - - ========= ============================== - Argument Description - ========= ============================== - *xranges* sequence of (*xmin*, *xwidth*) - *yrange* sequence of (*ymin*, *ywidth*) - ========= ============================== - -kwargs are -:class:`matplotlib.collections.BrokenBarHCollection` -properties: - - alpha: float - animated: [True | False] - antialiased or antialiaseds: Boolean or sequence of booleans - array: unknown - axes: an :class:`~matplotlib.axes.Axes` instance - clim: a length 2 sequence of floats - clip_box: a :class:`matplotlib.transforms.Bbox` instance - clip_on: [True | False] - clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] - cmap: a colormap - color: matplotlib color arg or sequence of rgba tuples - colorbar: unknown - contains: a callable function - edgecolor or edgecolors: matplotlib color arg or sequence of rgba tuples - facecolor or facecolors: matplotlib color arg or sequence of rgba tuples - figure: a :class:`matplotlib.figure.Figure` instance - gid: an id string - label: any string - linestyle or linestyles or dashes: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq) ] - linewidth or lw or linewidths: float or sequence of floats - lod: [True | False] - norm: unknown - offsets: float or sequence of floats - picker: [None|float|boolean|callable] - pickradius: unknown - rasterized: [True | False | None] - snap: unknown - transform: :class:`~matplotlib.transforms.Transform` instance - url: a url string - urls: unknown - visible: [True | False] - zorder: any number - -these can either be a single argument, ie:: - - facecolors = 'black' - -or a sequence of arguments for the various bars, ie:: - - facecolors = ('black', 'red', 'green') - -**Example:** - -.. plot:: mpl_examples/pylab_examples/broken_barh.py - -Additional kwargs: hold = [True|False] overrides default hold state -""" ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() @@ -2406,55 +1784,12 @@ ax.hold(washold) return ret +if Axes.broken_barh.__doc__ is not None: + broken_barh.__doc__ = dedent(Axes.broken_barh.__doc__) + __docstring_addendum # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def boxplot(x, notch=0, sym='b+', vert=1, whis=1.5, positions=None, widths=None, hold=None): - """call signature:: - - boxplot(x, notch=0, sym='+', vert=1, whis=1.5, - positions=None, widths=None) - -Make a box and whisker plot for each column of *x* or each -vector in sequence *x*. The box extends from the lower to -upper quartile values of the data, with a line at the median. -The whiskers extend from the box to show the range of the -data. Flier points are those past the end of the whiskers. - -- *notch* = 0 (default) produces a rectangular box plot. -- *notch* = 1 will produce a notched box plot - -*sym* (default 'b+') is the default symbol for flier points. -Enter an empty string ('') if you don't want to show fliers. - -- *vert* = 1 (default) makes the boxes vertical. -- *vert* = 0 makes horizontal boxes. This seems goofy, but - that's how Matlab did it. - -*whis* (default 1.5) defines the length of the whiskers as -a function of the inner quartile range. They extend to the -most extreme data point within ( ``whis*(75%-25%)`` ) data range. - -*positions* (default 1,2,...,n) sets the horizontal positions of -the boxes. The ticks and limits are automatically set to match -the positions. - -*widths* is either a scalar or a vector and sets the width of -each box. The default is 0.5, or ``0.15*(distance between extreme -positions)`` if that is smaller. - -*x* is an array or a sequence of vectors. - -Returns a dictionary mapping each component of the boxplot -to a list of the :class:`matplotlib.lines.Line2D` -instances created. - -**Example:** - -.. plot:: pyplots/boxplot_demo.py - -Additional kwargs: hold = [True|False] overrides default hold state -""" ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() @@ -2468,145 +1803,12 @@ ax.hold(washold) return ret +if Axes.boxplot.__doc__ is not None: + boxplot.__doc__ = dedent(Axes.boxplot.__doc__) + __docstring_addendum # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def cohere(x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, window=mlab.window_hanning, noverlap=0, pad_to=None, sides='default', scale_by_freq=None, hold=None, **kwargs): - """call signature:: - - cohere(x, y, NFFT=256, Fs=2, Fc=0, detrend = mlab.detrend_none, - window = mlab.window_hanning, noverlap=0, pad_to=None, - sides='default', scale_by_freq=None, **kwargs) - -cohere the coherence between *x* and *y*. Coherence is the normalized -cross spectral density: - -.. math:: - - C_{xy} = \\frac{|P_{xy}|^2}{P_{xx}P_{yy}} - -Keyword arguments: - - *NFFT*: integer - The number of data points used in each block for the FFT. - Must be even; a power 2 is most efficient. The default value is 256. - - *Fs*: scalar - The sampling frequency (samples per time unit). It is used - to calculate the Fourier frequencies, freqs, in cycles per time - unit. The default value is 2. - - *detrend*: callable - The function applied to each segment before fft-ing, - designed to remove the mean or linear trend. Unlike in - matlab, where the *detrend* parameter is a vector, in - matplotlib is it a function. The :mod:`~matplotlib.pylab` - module defines :func:`~matplotlib.pylab.detrend_none`, - :func:`~matplotlib.pylab.detrend_mean`, and - :func:`~matplotlib.pylab.detrend_linear`, but you can use - a custom function as well. - - *window*: callable or ndarray - A function or a vector of length *NFFT*. To create window - vectors see :func:`window_hanning`, :func:`window_none`, - :func:`numpy.blackman`, :func:`numpy.hamming`, - :func:`numpy.bartlett`, :func:`scipy.signal`, - :func:`scipy.signal.get_window`, etc. The default is - :func:`window_hanning`. If a function is passed as the - argument, it must take a data segment as an argument and - return the windowed version of the segment. - - *noverlap*: integer - The number of points of overlap between blocks. The default value - is 0 (no overlap). - - *pad_to*: integer - The number of points to which the data segment is padded when - performing the FFT. This can be different from *NFFT*, which - specifies the number of data points used. While not increasing - the actual resolution of the psd (the minimum distance between - resolvable peaks), this can give more points in the plot, - allowing for more detail. This corresponds to the *n* parameter - in the call to fft(). The default is None, which sets *pad_to* - equal to *NFFT* - - *sides*: [ 'default' | 'onesided' | 'twosided' ] - Specifies which sides of the PSD to return. Default gives the - default behavior, which returns one-sided for real data and both - for complex data. 'onesided' forces the return of a one-sided PSD, - while 'twosided' forces two-sided. - - *scale_by_freq*: boolean - Specifies whether the resulting density values should be scaled - by the scaling frequency, which gives density in units of Hz^-1. - This allows for integration over the returned frequency values. - The default is True for MatLab compatibility. - - *Fc*: integer - The center frequency of *x* (defaults to 0), which offsets - the x extents of the plot to reflect the frequency range used - when a signal is acquired and then filtered and downsampled to - baseband. - -The return value is a tuple (*Cxy*, *f*), where *f* are the -frequencies of the coherence vector. - -kwargs are applied to the lines. - -References: - - * Bendat & Piersol -- Random Data: Analysis and Measurement - Procedures, John Wiley & Sons (1986) - -kwargs control the :class:`~matplotlib.lines.Line2D` -properties of the coherence plot: - - alpha: float (0.0 transparent through 1.0 opaque) - animated: [True | False] - antialiased or aa: [True | False] - axes: an :class:`~matplotlib.axes.Axes` instance - clip_box: a :class:`matplotlib.transforms.Bbox` instance - clip_on: [True | False] - clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] - color or c: any matplotlib color - contains: a callable function - dash_capstyle: ['butt' | 'round' | 'projecting'] - dash_joinstyle: ['miter' | 'round' | 'bevel'] - dashes: sequence of on/off ink in points - data: 2D array - drawstyle: [ 'default' | 'steps' | 'steps-pre' | 'steps-mid' | 'steps-post' ] - figure: a :class:`matplotlib.figure.Figure` instance - fillstyle: ['full' | 'left' | 'right' | 'bottom' | 'top'] - gid: an id string - label: any string - linestyle or ls: [ '-' | '--' | '-.' | ':' | 'None' | ' ' | '' ] and any drawstyle in combination with a linestyle, e.g. 'steps--'. - linewidth or lw: float value in points - lod: [True | False] - marker: [ '+' | '*' | ',' | '.' | '1' | '2' | '3' | '4' | '<' | '>' | 'D' | 'H' | '^' | '_' | 'd' | 'h' | 'o' | 'p' | 's' | 'v' | 'x' | '|' | TICKUP | TICKDOWN | TICKLEFT | TICKRIGHT | 'None' | ' ' | '' ] - markeredgecolor or mec: any matplotlib color - markeredgewidth or mew: float value in points - markerfacecolor or mfc: any matplotlib color - markersize or ms: float - markevery: None | integer | (startind, stride) - picker: float distance in points or callable pick function ``fn(artist, event)`` - pickradius: float distance in points - rasterized: [True | False | None] - snap: unknown - solid_capstyle: ['butt' | 'round' | 'projecting'] - solid_joinstyle: ['miter' | 'round' | 'bevel'] - transform: a :class:`matplotlib.transforms.Transform` instance - url: a url string - visible: [True | False] - xdata: 1D array - ydata: 1D array - zorder: any number - -**Example:** - -.. plot:: mpl_examples/pylab_examples/cohere_demo.py - -Additional kwargs: hold = [True|False] overrides default hold state -""" ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() @@ -2620,75 +1822,12 @@ ax.hold(washold) return ret +if Axes.cohere.__doc__ is not None: + cohere.__doc__ = dedent(Axes.cohere.__doc__) + __docstring_addendum # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def clabel(CS, *args, **kwargs): - """call signature:: - - clabel(cs, **kwargs) - -adds labels to line contours in *cs*, where *cs* is a -:class:`~matplotlib.contour.ContourSet` object returned by -contour. - -:: - - clabel(cs, v, **kwargs) - -only labels contours listed in *v*. - -Optional keyword arguments: - - *fontsize*: - See http://matplotlib.sf.net/fonts.html - - *colors*: - - if *None*, the color of each label matches the color of - the corresponding contour - - - if one string color, e.g. *colors* = 'r' or *colors* = - 'red', all labels will be plotted in this color - - - if a tuple of matplotlib color args (string, float, rgb, etc), - different labels will be plotted in different colors in the order - specified - - *inline*: - controls whether the underlying contour is removed or - not. Default is *True*. - - *inline_spacing*: - space in pixels to leave on each side of label when - placing inline. Defaults to 5. This spacing will be - exact for labels at locations where the contour is - straight, less so for labels on curved contours. - - *fmt*: - a format string for the label. Default is '%1.3f' - Alternatively, this can be a dictionary matching contour - levels with arbitrary strings to use for each contour level - (i.e., fmt[level]=string) - - *manual*: - if *True*, contour labels will be placed manually using - mouse clicks. Click the first button near a contour to - add a label, click the second button (or potentially both - mouse buttons at once) to finish adding labels. The third - button can be used to remove the last label added, but - only if labels are not inline. Alternatively, the keyboard - can be used to select label locations (enter to end label - placement, delete or backspace act like the third mouse button, - and any other key will select a label location). - - *rightside_up*: - if *True* (default), label rotations will always be plus - or minus 90 degrees from level. - -.. plot:: mpl_examples/pylab_examples/contour_demo.py - -Additional kwargs: hold = [True|False] overrides default hold state -""" ax = gca() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() @@ -2702,172 +1841,12 @@ ax.hold(washold) return ret +if Axes.clabel.__doc__ is not None: + clabel.__doc__ = dedent(Axes.clabel.__doc__) + __docstring_addendum # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def contour(*args, **kwargs): - """:func:`~matplotlib.pyplot.contour` and -:func:`~matplotlib.pyplot.contourf` draw contour lines and -filled contours, respectively. Except as noted, function -signatures and return values are the same for both versions. - -:func:`~matplotlib.pyplot.contourf` differs from the Matlab -(TM) version in that it does not draw the polygon edges, -because the contouring engine yields simply connected regions -with branch cuts. To draw the edges, add line contours with -calls to :func:`~matplotlib.pyplot.contour`. - - -call signatures:: - - contour(Z) - -make a contour plot of an array *Z*. The level values are chosen -automatically. - -:: - - contour(X,Y,Z) - -*X*, *Y* specify the (*x*, *y*) coordinates of the surface - -:: - - contour(Z,N) - contour(X,Y,Z,N) - -contour *N* automatically-chosen levels. - -:: - - contour(Z,V) - contour(X,Y,Z,V) - -draw contour lines at the values specified in sequence *V* - -:: - - contourf(..., V) - -fill the (len(*V*)-1) regions between the values in *V* - -:: - - contour(Z, **kwargs) - -Use keyword args to control colors, linewidth, origin, cmap ... see -below for more details. - -*X*, *Y*, and *Z* must be arrays with the same dimensions. - -*Z* may be a masked array, but filled contouring may not -handle internal masked regions correctly. - -``C = contour(...)`` returns a -:class:`~matplotlib.contour.ContourSet` object. - -Optional keyword arguments: - - *colors*: [ None | string | (mpl_colors) ] - If *None*, the colormap specified by cmap will be used. - - If a string, like 'r' or 'red', all levels will be plotted in this - color. - - If a tuple of matplotlib color args (string, float, rgb, etc), - different levels will be plotted in different colors in the order - specified. - - *alpha*: float - The alpha blending value - - *cmap*: [ None | Colormap ] - A cm :class:`~matplotlib.cm.Colormap` instance or - *None*. If *cmap* is *None* and *colors* is *None*, a - default Colormap is used. - - *norm*: [ None | Normalize ] - A :class:`matplotlib.colors.Normalize` instance for - scaling data values to colors. If *norm* is *None* and - *colors* is *None*, the default linear scaling is used. - - *origin*: [ None | 'upper' | 'lower' | 'image' ] - If *None*, the first value of *Z* will correspond to the - lower left corner, location (0,0). If 'image', the rc - value for ``image.origin`` will be used. - - This keyword is not active if *X* and *Y* are specified in - the call to contour. - - *extent*: [ None | (x0,x1,y0,y1) ] - - If *origin* is not *None*, then *extent* is interpreted as - in :func:`matplotlib.pyplot.imshow`: it gives the outer - pixel boundaries. In this case, the position of Z[0,0] - is the center of the pixel, not a corner. If *origin* is - *None*, then (*x0*, *y0*) is the position of Z[0,0], and - (*x1*, *y1*) is the position of Z[-1,-1]. - - This keyword is not active if *X* and *Y* are specified in - the call to contour. - - *locator*: [ None | ticker.Locator subclass ] - If *locator* is None, the default - :class:`~matplotlib.ticker.MaxNLocator` is used. The - locator is used to determine the cont... [truncated message content] |
From: <ef...@us...> - 2009-08-04 07:01:54
|
Revision: 7341 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7341&view=rev Author: efiring Date: 2009-08-04 07:01:43 +0000 (Tue, 04 Aug 2009) Log Message: ----------- contourf uses complex paths instead of simple paths with cuts Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/contour.py trunk/matplotlib/src/cntr.c Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-08-04 06:52:24 UTC (rev 7340) +++ trunk/matplotlib/CHANGELOG 2009-08-04 07:01:43 UTC (rev 7341) @@ -1,3 +1,6 @@ +2009-08-03 Add PathCollection; modify contourf to use complex + paths instead of simple paths with cuts. - EF + 2009-08-03 Fixed boilerplate.py so it doesn't break the ReST docs. - JKS ====================================================================== Modified: trunk/matplotlib/lib/matplotlib/contour.py =================================================================== --- trunk/matplotlib/lib/matplotlib/contour.py 2009-08-04 06:52:24 UTC (rev 7340) +++ trunk/matplotlib/lib/matplotlib/contour.py 2009-08-04 07:01:43 UTC (rev 7341) @@ -8,7 +8,7 @@ import numpy as np from numpy import ma import matplotlib._cntr as _cntr -import matplotlib.path as path +import matplotlib.path as mpath import matplotlib.ticker as ticker import matplotlib.cm as cm import matplotlib.colors as colors @@ -499,7 +499,7 @@ if inline: for n in new: # Add path if not empty or single point - if len(n)>1: additions.append( path.Path(n) ) + if len(n)>1: additions.append( mpath.Path(n) ) else: # If not adding label, keep old path additions.append(linepath) @@ -579,6 +579,8 @@ self.collections = cbook.silent_list('collections.PolyCollection') else: self.collections = cbook.silent_list('collections.LineCollection') + self.segs = [] + self.kinds = [] # label lists must be initialized here self.labelTexts = [] self.labelCValues = [] @@ -601,13 +603,21 @@ for level, level_upper in zip(lowers, uppers): nlist = C.trace(level, level_upper, points = 0, nchunk = self.nchunk) - col = collections.PolyCollection(nlist, + nseg = len(nlist)//2 + segs = nlist[:nseg] + kinds = nlist[nseg:] + + + paths = self._make_paths(segs, kinds) + + col = collections.PathCollection(paths, antialiaseds = (self.antialiased,), edgecolors= 'none', alpha=self.alpha) self.ax.add_collection(col) self.collections.append(col) - + self.segs.append(segs) + self.kinds.append(kinds) else: tlinewidths = self._process_linewidths() self.tlinewidths = tlinewidths @@ -615,7 +625,10 @@ C = _cntr.Cntr(x, y, z.filled(), _mask) for level, width, lstyle in zip(self.levels, tlinewidths, tlinestyles): nlist = C.trace(level, points = 0) - col = collections.LineCollection(nlist, + nseg = len(nlist)//2 + segs = nlist[:nseg] + kinds = nlist[nseg:] + col = collections.LineCollection(segs, linewidths = width, linestyle = lstyle, alpha=self.alpha) @@ -623,6 +636,8 @@ col.set_label('_nolegend_') self.ax.add_collection(col, False) self.collections.append(col) + self.segs.append(segs) + self.kinds.append(kinds) self.changed() # set the colors x0 = ma.minimum(x) x1 = ma.maximum(x) @@ -631,6 +646,17 @@ self.ax.update_datalim([(x0,y0), (x1,y1)]) self.ax.autoscale_view() + @staticmethod + def _make_paths(segs, kinds): + paths = [] + for seg, kind in zip(segs, kinds): + codes = np.zeros(kind.shape, dtype=mpath.Path.code_type) + codes.fill(mpath.Path.LINETO) + codes[0] = mpath.Path.MOVETO + codes[kinds >= _cntr._slitkind] = mpath.Path.MOVETO + paths.append(mpath.Path(seg, codes)) + return paths + def changed(self): tcolors = [ (tuple(rgba),) for rgba in self.to_rgba(self.cvalues, alpha=self.alpha)] Modified: trunk/matplotlib/src/cntr.c =================================================================== --- trunk/matplotlib/src/cntr.c 2009-08-04 06:52:24 UTC (rev 7340) +++ trunk/matplotlib/src/cntr.c 2009-08-04 07:01:43 UTC (rev 7341) @@ -199,6 +199,7 @@ /* making the actual marks requires a bunch of other stuff */ const double *x, *y, *z; /* mesh coordinates and function values */ double *xcp, *ycp; /* output contour points */ + short *kcp; /* kind of contour point */ }; void print_Csite(Csite *Csite) @@ -268,6 +269,9 @@ #define START_MARK(left) \ ((left)>0?((left)>1?J1_START:I1_START):((left)<-1?J0_START:I0_START)) +enum {kind_zone, kind_edge1, kind_edge2, + kind_slit_up, kind_slit_down, kind_start_slit=16} point_kinds; + /* ------------------------------------------------------------------------ */ /* these actually mark points */ @@ -317,6 +321,7 @@ double zlevel = pass2 ? site->zlevel[level] : 0.0; double *xcp = pass2 ? site->xcp : 0; double *ycp = pass2 ? site->ycp : 0; + short *kcp = pass2 ? site->kcp : 0; int z0, z1, z2, z3; int keep_left = 0; /* flag to try to minimize curvature in saddles */ @@ -338,6 +343,7 @@ double zcp = (zlevel - z[p0]) / (z[p1] - z[p0]); xcp[n] = zcp * (x[p1] - x[p0]) + x[p0]; ycp[n] = zcp * (y[p1] - y[p0]) + y[p0]; + kcp[n] = kind_zone; } if (!done && !jedge) { @@ -487,7 +493,15 @@ site->edge = edge; site->n = n; site->left = left; - return done > 4 ? slit_cutter (site, done - 5, pass2) : done; + if (done <= 4) + { + return done; + } + if (pass2 && n > 0) + { + kcp[n-1] += kind_start_slit; + } + return slit_cutter (site, done - 5, pass2); } /* edge_walker assumes that the current edge is being drawn CCW @@ -513,11 +527,13 @@ long left0 = site->left0; int level0 = site->level0 == 2; int marked; + int n_kind = 0; const double *x = pass2 ? site->x : 0; const double *y = pass2 ? site->y : 0; double *xcp = pass2 ? site->xcp : 0; double *ycp = pass2 ? site->ycp : 0; + short *kcp = pass2 ? site->kcp : 0; int z0, z1, heads_up = 0; @@ -528,6 +544,7 @@ z0 = data[p0] & Z_VALUE; z1 = data[p1] & Z_VALUE; marked = 0; + n_kind = 0; if (z0 == 1) { /* mark current boundary point */ @@ -535,6 +552,8 @@ { xcp[n] = x[p0]; ycp[n] = y[p0]; + kcp[n] = kind_edge1; + n_kind = n; } marked = 1; } @@ -549,6 +568,8 @@ zcp = (zcp - site->z[p0]) / (site->z[p1] - site->z[p0]); xcp[n] = zcp * (x[p1] - x[p0]) + x[p0]; ycp[n] = zcp * (y[p1] - y[p0]) + y[p0]; + kcp[n] = kind_edge2; + n_kind = n; } marked = 1; } @@ -562,7 +583,10 @@ site->n = n + marked; /* if the curve is closing on a hole, need to make a downslit */ if (fwd < 0 && !(data[edge] & (jedge ? J_BNDY : I_BNDY))) + { + if (n_kind) kcp[n_kind] += kind_start_slit; return slit_cutter (site, 0, pass2); + } return 3; } else if (pass2) @@ -572,6 +596,7 @@ site->edge = edge; site->left = left; site->n = n + marked; + if (n_kind) kcp[n_kind] += kind_start_slit; return slit_cutter (site, heads_up, pass2); } } @@ -649,6 +674,7 @@ const double *y = pass2 ? site->y : 0; double *xcp = pass2 ? site->xcp : 0; double *ycp = pass2 ? site->ycp : 0; + short *kcp = pass2 ? site->kcp : 0; if (up) { @@ -677,6 +703,7 @@ } xcp[n] = x[p1]; ycp[n] = y[p1]; + kcp[n] = kind_slit_up; n++; p1 += imax; } @@ -733,6 +760,7 @@ { xcp[n] = x[p0]; ycp[n] = y[p0]; + kcp[n] = kind_slit_down; n++; } else @@ -1230,6 +1258,7 @@ site->triangle = NULL; site->xcp = NULL; site->ycp = NULL; + site->kcp = NULL; site->x = NULL; site->y = NULL; site->z = NULL; @@ -1279,6 +1308,7 @@ site->z = z; site->xcp = NULL; site->ycp = NULL; + site->kcp = NULL; return 0; } @@ -1291,11 +1321,12 @@ site = NULL; } -/* Build a list of lists of points, where each point is an (x,y) +/* Build a list of lists of points, where each point is an (x,y,k) tuple. */ static PyObject * -build_cntr_list_p(long *np, double *xp, double *yp, int nparts, long ntotal) +build_cntr_list_p(long *np, double *xp, double *yp, short *kp, + int nparts, long ntotal) { PyObject *point, *contourList, *all_contours; int start = 0, end = 0; @@ -1310,7 +1341,7 @@ contourList = PyList_New(np[i]); for (k = 0, j = start; j < end; j++, k++) { - point = Py_BuildValue("(dd)", xp[j], yp[j]); + point = Py_BuildValue("(ddh)", xp[j], yp[j], kp[j]); if (PyList_SetItem(contourList, k, point)) goto error; } if (PyList_SetItem(all_contours, i, contourList)) goto error; @@ -1323,73 +1354,43 @@ } -#if 0 -/* the following function is not used, so it produces a warning - * commented it out NN - 070630 */ - -/* Build a list of tuples (X, Y), where X and Y are 1-D arrays. */ +/* Build a list of XY 2-D arrays, shape (N,2), to which a list of K arrays + is concatenated concatenated. */ static PyObject * -build_cntr_list_v(long *np, double *xp, double *yp, int nparts, long ntotal) +build_cntr_list_v2(long *np, double *xp, double *yp, short *kp, + int nparts, long ntotal) { - PyObject *point, *all_contours; - PyArrayObject *xv, *yv; - npy_intp dims[1]; - int i; - long j, k; - - all_contours = PyList_New(nparts); - - k = 0; - for (i = 0; i < nparts; i++) - { - dims[0] = np[i]; - xv = (PyArrayObject *) PyArray_SimpleNew(1, dims, PyArray_DOUBLE); - yv = (PyArrayObject *) PyArray_SimpleNew(1, dims, PyArray_DOUBLE); - if (xv == NULL || yv == NULL) goto error; - for (j = 0; j < dims[0]; j++) - { - ((double *)xv->data)[j] = xp[k]; - ((double *)yv->data)[j] = yp[k]; - k++; - } - point = Py_BuildValue("(NN)", xv, yv); - /* "O" increments ref count; "N" does not. */ - if (PyList_SetItem(all_contours, i, point)) goto error; - } - return all_contours; - - error: - Py_XDECREF(all_contours); - return NULL; -} -#endif - -/* Build a list of XY 2-D arrays, shape (N,2) */ -static PyObject * -build_cntr_list_v2(long *np, double *xp, double *yp, int nparts, long ntotal) -{ PyObject *all_contours; PyArrayObject *xyv; + PyArrayObject *kv; npy_intp dims[2]; + npy_intp kdims[1]; int i; long j, k; - all_contours = PyList_New(nparts); + all_contours = PyList_New(nparts*2); k = 0; for (i = 0; i < nparts; i++) { dims[0] = np[i]; dims[1] = 2; + kdims[0] = np[i]; xyv = (PyArrayObject *) PyArray_SimpleNew(2, dims, PyArray_DOUBLE); if (xyv == NULL) goto error; + kv = (PyArrayObject *) PyArray_SimpleNew(1, kdims, PyArray_SHORT); + if (kv == NULL) goto error; + for (j = 0; j < dims[0]; j++) { ((double *)xyv->data)[2*j] = xp[k]; ((double *)xyv->data)[2*j+1] = yp[k]; + ((short *)kv->data)[j] = kp[k]; k++; } if (PyList_SetItem(all_contours, i, (PyObject *)xyv)) goto error; + if (PyList_SetItem(all_contours, nparts+i, + (PyObject *)kv)) goto error; } return all_contours; @@ -1413,6 +1414,7 @@ PyObject *c_list = NULL; double *xp0; double *yp0; + short *kp0; long *nseg0; int iseg; @@ -1451,12 +1453,14 @@ } xp0 = (double *) PyMem_Malloc(ntotal * sizeof(double)); yp0 = (double *) PyMem_Malloc(ntotal * sizeof(double)); + kp0 = (short *) PyMem_Malloc(ntotal * sizeof(short)); nseg0 = (long *) PyMem_Malloc(nparts * sizeof(long)); - if (xp0 == NULL || yp0 == NULL || nseg0 == NULL) goto error; + if (xp0 == NULL || yp0 == NULL || kp0 == NULL || nseg0 == NULL) goto error; /* second pass */ site->xcp = xp0; site->ycp = yp0; + site->kcp = kp0; iseg = 0; for (;;iseg++) { @@ -1475,6 +1479,7 @@ nseg0[iseg] = n; site->xcp += n; site->ycp += n; + site->kcp += n; ntotal2 += n; nparts2++; } @@ -1487,21 +1492,31 @@ } - if (points) + if (points) /* It is False when called; we don't need the point version */ { - c_list = build_cntr_list_p(nseg0, xp0, yp0, nparts, ntotal); + c_list = build_cntr_list_p(nseg0, xp0, yp0, kp0, nparts, ntotal); } else { - c_list = build_cntr_list_v2(nseg0, xp0, yp0, nparts, ntotal); + c_list = build_cntr_list_v2(nseg0, xp0, yp0, kp0, nparts, ntotal); } - PyMem_Free(xp0); PyMem_Free(yp0); PyMem_Free(nseg0); - site->xcp = NULL; site->ycp = NULL; + PyMem_Free(xp0); + PyMem_Free(yp0); + PyMem_Free(kp0); + PyMem_Free(nseg0); + site->xcp = NULL; + site->ycp = NULL; + site->kcp = NULL; return c_list; error: - PyMem_Free(xp0); PyMem_Free(yp0); PyMem_Free(nseg0); - site->xcp = NULL; site->ycp = NULL; + PyMem_Free(xp0); + PyMem_Free(yp0); + PyMem_Free(kp0); + PyMem_Free(nseg0); + site->xcp = NULL; + site->ycp = NULL; + site->kcp = NULL; Py_XDECREF(c_list); return NULL; } @@ -1603,16 +1618,14 @@ } xpa = (PyArrayObject *) PyArray_ContiguousFromObject(xarg, - PyArray_DOUBLE, 2, 2); + PyArray_DOUBLE, 2, 2); ypa = (PyArrayObject *) PyArray_ContiguousFromObject(yarg, - PyArray_DOUBLE, - 2, 2); - zpa = (PyArrayObject *) PyArray_ContiguousFromObject(zarg, PyArray_DOUBLE, - 2, 2); + PyArray_DOUBLE, 2, 2); + zpa = (PyArrayObject *) PyArray_ContiguousFromObject(zarg, + PyArray_DOUBLE, 2, 2); if (marg) mpa = (PyArrayObject *) PyArray_ContiguousFromObject(marg, - PyArray_SBYTE, - 2, 2); + PyArray_SBYTE, 2, 2); else mpa = NULL; @@ -1751,7 +1764,8 @@ if (m == NULL) return; - + PyModule_AddIntConstant(m, "_slitkind", (long)kind_slit_up ); + /* We can add all the point_kinds values later if we need them. */ import_array(); Py_INCREF(&CntrType); PyModule_AddObject(m, "Cntr", (PyObject *)&CntrType); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ef...@us...> - 2009-08-04 07:13:44
|
Revision: 7342 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7342&view=rev Author: efiring Date: 2009-08-04 07:13:37 +0000 (Tue, 04 Aug 2009) Log Message: ----------- Remove unneeded function and argument from contouring internals Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/contour.py trunk/matplotlib/src/cntr.c Modified: trunk/matplotlib/lib/matplotlib/contour.py =================================================================== --- trunk/matplotlib/lib/matplotlib/contour.py 2009-08-04 07:01:43 UTC (rev 7341) +++ trunk/matplotlib/lib/matplotlib/contour.py 2009-08-04 07:13:37 UTC (rev 7342) @@ -601,8 +601,7 @@ lowers = self._levels[:-1] uppers = self._levels[1:] for level, level_upper in zip(lowers, uppers): - nlist = C.trace(level, level_upper, points = 0, - nchunk = self.nchunk) + nlist = C.trace(level, level_upper, nchunk = self.nchunk) nseg = len(nlist)//2 segs = nlist[:nseg] kinds = nlist[nseg:] @@ -624,7 +623,7 @@ tlinestyles = self._process_linestyles() C = _cntr.Cntr(x, y, z.filled(), _mask) for level, width, lstyle in zip(self.levels, tlinewidths, tlinestyles): - nlist = C.trace(level, points = 0) + nlist = C.trace(level) nseg = len(nlist)//2 segs = nlist[:nseg] kinds = nlist[nseg:] Modified: trunk/matplotlib/src/cntr.c =================================================================== --- trunk/matplotlib/src/cntr.c 2009-08-04 07:01:43 UTC (rev 7341) +++ trunk/matplotlib/src/cntr.c 2009-08-04 07:13:37 UTC (rev 7342) @@ -1321,39 +1321,7 @@ site = NULL; } -/* Build a list of lists of points, where each point is an (x,y,k) - tuple. -*/ -static PyObject * -build_cntr_list_p(long *np, double *xp, double *yp, short *kp, - int nparts, long ntotal) -{ - PyObject *point, *contourList, *all_contours; - int start = 0, end = 0; - int i, j, k; - all_contours = PyList_New(nparts); - - for (i = 0; i < nparts; i++) - { - start = end; - end += np[i]; - contourList = PyList_New(np[i]); - for (k = 0, j = start; j < end; j++, k++) - { - point = Py_BuildValue("(ddh)", xp[j], yp[j], kp[j]); - if (PyList_SetItem(contourList, k, point)) goto error; - } - if (PyList_SetItem(all_contours, i, contourList)) goto error; - } - return all_contours; - - error: - Py_XDECREF(all_contours); - return NULL; -} - - /* Build a list of XY 2-D arrays, shape (N,2), to which a list of K arrays is concatenated concatenated. */ static PyObject * @@ -1409,7 +1377,7 @@ */ PyObject * -cntr_trace(Csite *site, double levels[], int nlevels, int points, long nchunk) +cntr_trace(Csite *site, double levels[], int nlevels, long nchunk) { PyObject *c_list = NULL; double *xp0; @@ -1491,15 +1459,8 @@ } } + c_list = build_cntr_list_v2(nseg0, xp0, yp0, kp0, nparts, ntotal); - if (points) /* It is False when called; we don't need the point version */ - { - c_list = build_cntr_list_p(nseg0, xp0, yp0, kp0, nparts, ntotal); - } - else - { - c_list = build_cntr_list_v2(nseg0, xp0, yp0, kp0, nparts, ntotal); - } PyMem_Free(xp0); PyMem_Free(yp0); PyMem_Free(kp0); @@ -1676,18 +1637,17 @@ { double levels[2] = {0.0, -1e100}; int nlevels = 2; - int points = 0; long nchunk = 0L; - static char *kwlist[] = {"level0", "level1", "points", "nchunk", NULL}; + static char *kwlist[] = {"level0", "level1", "nchunk", NULL}; - if (! PyArg_ParseTupleAndKeywords(args, kwds, "d|dil", kwlist, - levels, levels+1, &points, &nchunk)) + if (! PyArg_ParseTupleAndKeywords(args, kwds, "d|dl", kwlist, + levels, levels+1, &nchunk)) { return NULL; } if (levels[1] == -1e100 || levels[1] <= levels[0]) nlevels = 1; - return cntr_trace(self->site, levels, nlevels, points, nchunk); + return cntr_trace(self->site, levels, nlevels, nchunk); } static PyMethodDef Cntr_methods[] = { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2009-08-04 13:15:24
|
Revision: 7345 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7345&view=rev Author: jdh2358 Date: 2009-08-04 13:15:14 +0000 (Tue, 04 Aug 2009) Log Message: ----------- get data example Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/examples/pylab_examples/scatter_demo2.py trunk/matplotlib/lib/matplotlib/__init__.py trunk/matplotlib/lib/matplotlib/cbook.py Added Paths: ----------- trunk/matplotlib/examples/misc/mpl_data_demo.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-08-04 13:11:35 UTC (rev 7344) +++ trunk/matplotlib/CHANGELOG 2009-08-04 13:15:14 UTC (rev 7345) @@ -1,3 +1,4 @@ + 2009-08-03 Add PathCollection; modify contourf to use complex paths instead of simple paths with cuts. - EF @@ -3,4 +4,8 @@ 2009-08-03 Fixed boilerplate.py so it doesn't break the ReST docs. - JKS +2009-07-31 Added cbook.get_mpl_data for urllib enabled fetching and + cacheing of data needed for examples. See + examples/misc/mpl_data_demo.py - JDH + ====================================================================== Added: trunk/matplotlib/examples/misc/mpl_data_demo.py =================================================================== --- trunk/matplotlib/examples/misc/mpl_data_demo.py (rev 0) +++ trunk/matplotlib/examples/misc/mpl_data_demo.py 2009-08-04 13:15:14 UTC (rev 7345) @@ -0,0 +1,12 @@ + """ + Grab mpl data from the ~/.matplotlib/mpl_data cache if it exists, else + fetch it from svn and cache it + """ +import matplotlib.cbook as cbook +import matplotlib.pyplot as plt +fname = cbook.get_mpl_data('lena.png', asfileobj=False) + +print 'fname', fname +im = plt.imread(fname) +plt.imshow(im) +plt.show() Modified: trunk/matplotlib/examples/pylab_examples/scatter_demo2.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/scatter_demo2.py 2009-08-04 13:11:35 UTC (rev 7344) +++ trunk/matplotlib/examples/pylab_examples/scatter_demo2.py 2009-08-04 13:15:14 UTC (rev 7345) @@ -1,7 +1,7 @@ """ make a scatter plot with varying color and size arguments """ -import matplotlib +import matplotlib import numpy as np import matplotlib.pyplot as plt import matplotlib.mlab as mlab Modified: trunk/matplotlib/lib/matplotlib/__init__.py =================================================================== --- trunk/matplotlib/lib/matplotlib/__init__.py 2009-08-04 13:11:35 UTC (rev 7344) +++ trunk/matplotlib/lib/matplotlib/__init__.py 2009-08-04 13:15:14 UTC (rev 7345) @@ -487,6 +487,7 @@ always=False) + def get_example_data(fname): """ return a filehandle to one of the example files in mpl-data/example Modified: trunk/matplotlib/lib/matplotlib/cbook.py =================================================================== --- trunk/matplotlib/lib/matplotlib/cbook.py 2009-08-04 13:11:35 UTC (rev 7344) +++ trunk/matplotlib/lib/matplotlib/cbook.py 2009-08-04 13:15:14 UTC (rev 7345) @@ -10,6 +10,8 @@ import numpy.ma as ma from weakref import ref +import matplotlib + major, minor1, minor2, s, tmp = sys.version_info @@ -338,6 +340,55 @@ def is_scalar_or_string(val): return is_string_like(val) or not iterable(val) + + +def get_mpl_data(fname, asfileobj=True): + """ + Check the cachedirectory ~/.matplotlib/mpl_data for an mpl_data + file. If it does not exist, fetch it with urllib from the mpl svn repo + + http://matplotlib.svn.sourceforge.net/viewvc/matplotlib/trunk/mpl_data/ + + and store it in the cachedir. + + If asfileobj is True, a file object will be returned. Else the + path to the file as a string will be returned + + To add a datafile to this directory, you need to check out + mpl_data from matplotlib svn:: + + svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/mpl_data + + and svn add the data file you want to support. This is primarily + intended for use in mpl examples that need custom data + """ + + # TODO: how to handle stale data in the cache that has been + # updated from svn -- is there a clean http way to get the current + # revision number that will not leave us at the mercy of html + # changes at sf? + + + configdir = matplotlib.get_configdir() + cachedir = os.path.join(configdir, 'mpl_data') + if not os.path.exists(cachedir): + os.mkdir(cachedir) + + cachefile = os.path.join(cachedir, fname) + + if not os.path.exists(cachefile): + import urllib + url = 'http://matplotlib.svn.sourceforge.net/viewvc/matplotlib/trunk/mpl_data/%s'%urllib.quote(fname) + matplotlib.verbose.report('Attempting to download %s to %s'%(url, cachefile)) + urllib.urlretrieve(url, filename=cachefile) + else: + matplotlib.verbose.report('Aleady have mpl_data %s'%fname) + + if asfileobj: + return to_filehandle(cachefile) + else: + return cachefile + def flatten(seq, scalarp=is_scalar_or_string): """ this generator flattens nested containers such as This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2009-08-04 13:20:40
|
Revision: 7346 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7346&view=rev Author: jdh2358 Date: 2009-08-04 13:20:29 +0000 (Tue, 04 Aug 2009) Log Message: ----------- Merged revisions 7323-7326,7328-7331,7334-7337,7343 via svnmerge from https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/v0_99_maint ........ r7323 | jdh2358 | 2009-07-31 10:32:11 -0500 (Fri, 31 Jul 2009) | 2 lines apply sf patches 2830233 and 2823885 for osx setup and 64 bit; thanks Michiel ........ r7324 | jdh2358 | 2009-07-31 10:39:30 -0500 (Fri, 31 Jul 2009) | 1 line revert setupext.py patch for osx; breaks my osx test build ........ r7325 | jdh2358 | 2009-07-31 10:52:19 -0500 (Fri, 31 Jul 2009) | 1 line added miktex win32 patch from sf patch 2820194 ........ r7326 | jdh2358 | 2009-07-31 13:11:50 -0500 (Fri, 31 Jul 2009) | 1 line update the makefile for win32 build ........ r7328 | jdh2358 | 2009-08-01 12:37:26 -0500 (Sat, 01 Aug 2009) | 1 line Applied Michiel's sf patch 2823885 to remove the /usr/X11R6 dirs from darwin ........ r7329 | jdh2358 | 2009-08-01 14:11:58 -0500 (Sat, 01 Aug 2009) | 1 line some fixes for the binary builds ........ r7330 | jdh2358 | 2009-08-01 14:27:43 -0500 (Sat, 01 Aug 2009) | 1 line more fixes for osx ........ r7331 | jdh2358 | 2009-08-01 14:34:05 -0500 (Sat, 01 Aug 2009) | 1 line update the readme with build requirements ........ r7334 | jdh2358 | 2009-08-03 11:38:25 -0500 (Mon, 03 Aug 2009) | 1 line handled sf bugs 2831556 and 2830525; better bar error messages and backend driver configs ........ r7335 | jdh2358 | 2009-08-03 12:19:42 -0500 (Mon, 03 Aug 2009) | 1 line added two examples from Josh Hemann ........ r7336 | jdh2358 | 2009-08-03 12:40:17 -0500 (Mon, 03 Aug 2009) | 1 line fixed rec2csv win32 file handle bug from sf patch 2831018 ........ r7337 | jdh2358 | 2009-08-03 14:31:05 -0500 (Mon, 03 Aug 2009) | 1 line removed a couple of cases of mlab.load ........ r7343 | jdh2358 | 2009-08-04 06:50:09 -0500 (Tue, 04 Aug 2009) | 1 line applied sf patch 2815064 (middle button events for wx) and patch 2818092 (resize events for wx) ........ Modified Paths: -------------- trunk/matplotlib/doc/_templates/index.html trunk/matplotlib/doc/_templates/indexsidebar.html trunk/matplotlib/doc/api/spine_api.rst trunk/matplotlib/doc/faq/installing_faq.rst trunk/matplotlib/doc/pyplots/plotmap.py trunk/matplotlib/doc/users/installing.rst trunk/matplotlib/examples/pylab_examples/load_converter.py trunk/matplotlib/examples/tests/backend_driver.py trunk/matplotlib/lib/matplotlib/axes.py trunk/matplotlib/lib/matplotlib/backends/backend_wx.py trunk/matplotlib/lib/matplotlib/mlab.py trunk/matplotlib/lib/matplotlib/texmanager.py trunk/matplotlib/release/osx/Makefile trunk/matplotlib/release/osx/README.txt trunk/matplotlib/release/win32/Makefile trunk/matplotlib/setupext.py trunk/matplotlib/src/_macosx.m Added Paths: ----------- trunk/matplotlib/examples/pylab_examples/barchart_demo2.py trunk/matplotlib/examples/pylab_examples/boxplot_demo2.py Property Changed: ---------------- trunk/matplotlib/ Property changes on: trunk/matplotlib ___________________________________________________________________ Modified: svnmerge-integrated - /branches/mathtex:1-7263 /branches/v0_98_5_maint:1-7253 /branches/v0_99_maint:1-7318,7338 + /branches/mathtex:1-7263 /branches/v0_98_5_maint:1-7253 /branches/v0_99_maint:1-7345 Modified: trunk/matplotlib/doc/_templates/index.html =================================================================== --- trunk/matplotlib/doc/_templates/index.html 2009-08-04 13:15:14 UTC (rev 7345) +++ trunk/matplotlib/doc/_templates/index.html 2009-08-04 13:20:29 UTC (rev 7346) @@ -3,7 +3,7 @@ {% block body %} - <h1>Welcome</h1> + <h1>mpl</h1> <p>matplotlib is a python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and Modified: trunk/matplotlib/doc/_templates/indexsidebar.html =================================================================== --- trunk/matplotlib/doc/_templates/indexsidebar.html 2009-08-04 13:15:14 UTC (rev 7345) +++ trunk/matplotlib/doc/_templates/indexsidebar.html 2009-08-04 13:20:29 UTC (rev 7346) @@ -4,11 +4,14 @@ <p>Please <a href="http://sourceforge.net/project/project_donations.php?group_id=80706">donate</a> to support matplotlib development.</p> +<p>A release candidate rc1 of matplotlib-0.99.0 is <a href="http://drop.io/xortel1#">available</a> for testing. Please post any bugs to the <a href="http://sourceforge.net/tracker2/?group_id=80706">tracker</a> +</p> <p>Watch a <a href="http://videolectures.net/mloss08_hunter_mat">video lecture</a> about matplotlib presented at <a href="http://videolectures.net/mloss08_whistler">NIPS 08 Workshop</a> <i>Machine Learning Open Source Software</i></a>. </p> <h3>Download</h3> + <p>Current version: <b>{{ version }}</b></p> Modified: trunk/matplotlib/doc/api/spine_api.rst =================================================================== --- trunk/matplotlib/doc/api/spine_api.rst 2009-08-04 13:15:14 UTC (rev 7345) +++ trunk/matplotlib/doc/api/spine_api.rst 2009-08-04 13:20:29 UTC (rev 7346) @@ -4,7 +4,7 @@ :mod:`matplotlib.spine` -====================== +======================== .. automodule:: matplotlib.spine :members: Modified: trunk/matplotlib/doc/faq/installing_faq.rst =================================================================== --- trunk/matplotlib/doc/faq/installing_faq.rst 2009-08-04 13:15:14 UTC (rev 7345) +++ trunk/matplotlib/doc/faq/installing_faq.rst 2009-08-04 13:20:29 UTC (rev 7346) @@ -287,11 +287,66 @@ <http://www.python.org/download/>`_. +.. _install_osx_binaries: + +Installing OSX binaries +----------------------- + +If you want to install matplotlib from one of the binary installers we +build, you have two choices: a mpkg installer, which is a typical +Installer.app, or an binary OSX egg, which you can install via +setuptools easy_install. + +The mkpg installer will have a "zip" extension, and will have a name +like file:`matplotlib-0.99.0.rc1-py2.5-macosx10.5_mpkg.zip` depending on +the python, matplotlib, and OSX versions. You need to unzip this file +using either the "unzip" command on OSX, or simply double clicking on +it to run StuffIt Expander. When you double click on the resultant +mpkd directory, which will have a name like +file:`matplotlib-0.99.0.rc1-py2.5-macosx10.5.mpkg`, it will run the +Installer.app, prompt you for a password if you need system wide +installation privileges, and install to a directory like +file:`/Library/Python/2.5/site-packages/`, again depedending on your +python version. This directory may not be in your python path, so you +can test your installation with:: + + > python -c 'import matplotlib; print matplotlib.__version__, matplotlib.__file__' + +If you get an error like:: + + Traceback (most recent call last): + File "<string>", line 1, in <module> + ImportError: No module named matplotlib + +then you will need to set your PYTHONPATH, eg:: + + export PYTHONPATH=/Library/Python/2.5/site-packages:$PYTHONPATH + +See also ref:`environment-variables`. + .. _easy-install-osx-egg: -easy_install from egg? +easy_install from egg ------------------------------ +You can also us the eggs we build for OSX (see the `installation +instructions +<http://pypi.python.org/pypi/setuptools#cygwin-mac-os-x-linux-other>`_ +for easy_install if you do not have it on your system already). You +can try:: + + > easy_install matplotlib + +which should grab the latest egg from the sourceforge site, but the +naming conventions for OSX eggs appear to be broken (see below) so +there is no guarantee the right egg will be found. We recommend you +download the latest egg from our `download site +<http://sourceforge.net/projects/matplotlib/files/>`_ directly to your +harddrive, and manually install it with + + > easy_install --install-dir=~/dev/lib/python2.5/site-packages/ matplotlib-0.99.0.rc1-py2.5-macosx-10.5-i386.egg + + Some users have reported problems with the egg for 0.98 from the matplotlib download site, with ``easy_install``, getting an error:: Modified: trunk/matplotlib/doc/pyplots/plotmap.py =================================================================== --- trunk/matplotlib/doc/pyplots/plotmap.py 2009-08-04 13:15:14 UTC (rev 7345) +++ trunk/matplotlib/doc/pyplots/plotmap.py 2009-08-04 13:20:29 UTC (rev 7346) @@ -5,7 +5,9 @@ # the data is interpolated to the native projection grid. import os from mpl_toolkits.basemap import Basemap, shiftgrid -from pylab import title, colorbar, show, axes, cm, load, arange, figure, \ +import numpy as np + +from pylab import title, colorbar, show, axes, cm, arange, figure, \ text # read in topo data (on a regular lat/lon grid) @@ -15,9 +17,9 @@ if not os.path.exists(datadir): raise SystemExit('You need to download the data with svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk/htdocs/screenshots/data/" and set the datadir variable in %s'%__file__) -topoin = load(os.path.join(datadir, 'etopo20data.gz')) -lons = load(os.path.join(datadir, 'etopo20lons.gz')) -lats = load(os.path.join(datadir, 'etopo20lats.gz')) +topoin = np.loadtxt(os.path.join(datadir, 'etopo20data.gz')) +lons = np.loadtxt(os.path.join(datadir, 'etopo20lons.gz')) +lats = np.loadtxt(os.path.join(datadir, 'etopo20lats.gz')) # shift data so lons go from -180 to 180 instead of 20 to 380. topoin,lons = shiftgrid(180.,topoin,lons,start=False) Modified: trunk/matplotlib/doc/users/installing.rst =================================================================== --- trunk/matplotlib/doc/users/installing.rst 2009-08-04 13:15:14 UTC (rev 7345) +++ trunk/matplotlib/doc/users/installing.rst 2009-08-04 13:20:29 UTC (rev 7346) @@ -63,14 +63,17 @@ And a *voila*, a figure pops up. But we are putting the cart ahead of the horse -- first we need to get matplotlib installed. We provide prebuilt binaries for OS X and Windows on the matplotlib `download -<http://sourceforge.net/project/showfiles.php?group_id=80706>`_ page. -Click on the latest release of the "matplotlib" package, choose your -python version (2.4 or 2.5) and your platform (macosx or win32) and -you should be good to go. If you have any problems, please check the +<http://sourceforge.net/projects/matplotlib/files/>`_ page. Click on +the latest release of the "matplotlib" package, choose your python +version (2.4 or 2.5) and your platform (macosx or win32) and you +should be good to go. If you have any problems, please check the :ref:`installing-faq`, google around a little bit, and post a question the `mailing list <http://sourceforge.net/project/showfiles.php?group_id=80706>`_. +Instructions for installing our OSX binaries are found in the FAQ +ref:`install_osx_binaries`. + Note that when testing matplotlib installations from the interactive python console, there are some issues relating to user interface toolkits and interactive settings that are discussed in @@ -114,7 +117,8 @@ These are external packages which you will need to install before installing matplotlib. Windows users only need the first two (python and numpy) since the others are built into the matplotlib windows -installers available for download at the sourceforge site. +installers available for download at the sourceforge site. If you are +building on OSX, see :ref:`build_osx` :term:`python` 2.4 (or later but not python3) matplotlib requires python 2.4 or later (`download <http://www.python.org/download/>`__) @@ -183,3 +187,19 @@ +.. _build_osx: + +Building on OSX +================== + +The build situation on OSX is complicated by the various places one +can get the png and freetype requirements from (darwinports, fink, +/usr/X11R6) and the different architectures (x86, ppc, universal) and +the different OSX version (10.4 and 10.5). We recommend that you build +the way we do for the OSX release: by grabbing the tarbar or svn +repository, cd-ing into the release/osx dir, and following the +instruction in the README. This directory has a Makefile which will +automatically grab the zlib, png and freetype dependencies from the +web, build them with the right flags to make universal libraries, and +then build the matplotlib source and binary installers. + \ No newline at end of file Copied: trunk/matplotlib/examples/pylab_examples/barchart_demo2.py (from rev 7337, branches/v0_99_maint/examples/pylab_examples/barchart_demo2.py) =================================================================== --- trunk/matplotlib/examples/pylab_examples/barchart_demo2.py (rev 0) +++ trunk/matplotlib/examples/pylab_examples/barchart_demo2.py 2009-08-04 13:20:29 UTC (rev 7346) @@ -0,0 +1,107 @@ +""" +Thanks Josh Hemann for the example + +This examples comes from an application in which grade school gym +teachers wanted to be able to show parents how their child did across +a handful of fitness tests, and importantly, relative to how other +children did. To extract the plotting code for demo purposes, we'll +just make up some data for little Johnny Doe... + +""" +import numpy as np +import matplotlib.pyplot as plt +import pylab +from matplotlib.patches import Polygon +from matplotlib.ticker import MaxNLocator + + + +student = 'Johnny Doe' +grade = 2 +gender = 'boy' +cohortSize = 62 #The number of other 2nd grade boys + +numTests = 5 +testNames = ['Pacer Test', 'Flexed Arm\n Hang', 'Mile Run', 'Agility', + 'Push Ups'] +testMeta = ['laps', 'sec', 'min:sec', 'sec', ''] +scores = ['7', '48', '12:52', '17', '14'] +rankings = np.round(np.random.uniform(0, 1, numTests)*100, 0) + +fig = plt.figure(figsize=(9,7)) +ax1 = fig.add_subplot(111) +plt.subplots_adjust(left=0.115, right=0.88) +fig.canvas.set_window_title('Eldorado K-8 Fitness Chart') +pos = np.arange(numTests)+0.5 #Center bars on the Y-axis ticks +rects = ax1.barh(pos, rankings, align='center', height=0.5, color='m') + +ax1.axis([0,100,0,5]) +pylab.yticks(pos, testNames) +ax1.set_title('Johnny Doe') +plt.text(50, -0.5, 'Cohort Size: ' + str(cohortSize), + horizontalalignment='center', size='small') + +# Set the right-hand Y-axis ticks and labels and set X-axis tick marks at the +# deciles +ax2 = ax1.twinx() +ax2.plot([100,100], [0, 5], 'white', alpha=0.1) +ax2.xaxis.set_major_locator(MaxNLocator(11)) +xticks = pylab.setp(ax2, xticklabels=['0','10','20','30','40','50','60', +'70', + '80','90','100']) +ax2.xaxis.grid(True, linestyle='--', which='major', color='grey', +alpha=0.25) +#Plot a solid vertical gridline to highlight the median position +plt.plot([50,50], [0, 5], 'grey', alpha=0.25) + +# Build up the score labels for the right Y-axis by first appending a carriage +# return to each string and then tacking on the appropriate meta information +# (i.e., 'laps' vs 'seconds'). We want the labels centered on the ticks, so if +# there is no meta info (like for pushups) then don't add the carriage return to +# the string + +def withnew(i, scr): + if testMeta[i] != '' : return '%s\n'%scr + else: return scr +scoreLabels = [withnew(i, scr) for i,scr in enumerate(scores)] +scoreLabels = [i+j for i,j in zip(scoreLabels, testMeta)] +pylab.yticks(pos, scoreLabels) +ax2.set_ylabel('Test Scores') +#Make list of numerical suffixes corresponding to position in a list +# 0 1 2 3 4 5 6 7 8 9 +suffixes =['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'] +ax2.set_xlabel('Percentile Ranking Across ' + str(grade) + suffixes[grade] \ + + ' Grade ' + gender.title() + 's') + +# Lastly, write in the ranking inside each bar to aid in interpretation +for rect in rects: + # Rectangle widths are already integer-valued but are floating + # type, so it helps to remove the trailing decimal point and 0 by + # converting width to int type + width = int(rect.get_width()) + + # Figure out what the last digit (width modulo 10) so we can add + # the appropriate numerical suffix (e.g. 1st, 2nd, 3rd, etc) + lastDigit = width % 10 + # Note that 11, 12, and 13 are special cases + if (width == 11) or (width == 12) or (width == 13): + suffix = 'th' + else: + suffix = suffixes[lastDigit] + + rankStr = str(width) + suffix + if (width < 5): # The bars aren't wide enough to print the ranking inside + xloc = width + 1 # Shift the text to the right side of the right edge + clr = 'black' # Black against white background + align = 'left' + else: + xloc = 0.98*width # Shift the text to the left side of the right edge + clr = 'white' # White on magenta + align = 'right' + + yloc = rect.get_y()+rect.get_height()/2.0 #Center the text vertically in the bar + ax1.text(xloc, yloc, rankStr, horizontalalignment=align, + verticalalignment='center', color=clr, weight='bold') + +plt.show() + Copied: trunk/matplotlib/examples/pylab_examples/boxplot_demo2.py (from rev 7337, branches/v0_99_maint/examples/pylab_examples/boxplot_demo2.py) =================================================================== --- trunk/matplotlib/examples/pylab_examples/boxplot_demo2.py (rev 0) +++ trunk/matplotlib/examples/pylab_examples/boxplot_demo2.py 2009-08-04 13:20:29 UTC (rev 7346) @@ -0,0 +1,121 @@ +""" +Thanks Josh Hemann for the example +""" + +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.patches import Polygon + + +# Generate some data from five different probability distributions, +# each with different characteristics. We want to play with how an IID +# bootstrap resample of the data preserves the distributional +# properties of the original sample, and a boxplot is one visual tool +# to make this assessment +numDists = 5 +randomDists = ['Normal(1,1)',' Lognormal(1,1)', 'Exp(1)', 'Gumbel(6,4)', + 'Triangular(2,9,11)'] +N = 500 +norm = np.random.normal(1,1, N) +logn = np.random.lognormal(1,1, N) +expo = np.random.exponential(1, N) +gumb = np.random.gumbel(6, 4, N) +tria = np.random.triangular(2, 9, 11, N) + +# Generate some random indices that we'll use to resample the original data +# arrays. For code brevity, just use the same random indices for each array +bootstrapIndices = np.random.random_integers(0, N-1, N) +normBoot = norm[bootstrapIndices] +expoBoot = expo[bootstrapIndices] +gumbBoot = gumb[bootstrapIndices] +lognBoot = logn[bootstrapIndices] +triaBoot = tria[bootstrapIndices] + +data = [norm, normBoot, logn, lognBoot, expo, expoBoot, gumb, gumbBoot, + tria, triaBoot] + +fig = plt.figure(figsize=(10,6)) +fig.canvas.set_window_title('A Boxplot Example') +ax1 = fig.add_subplot(111) +plt.subplots_adjust(left=0.075, right=0.95, top=0.9, bottom=0.25) + +bp = plt.boxplot(data, notch=0, sym='+', vert=1, whis=1.5) +plt.setp(bp['boxes'], color='black') +plt.setp(bp['whiskers'], color='black') +plt.setp(bp['fliers'], color='red', marker='+') + +# Add a horizontal grid to the plot, but make it very light in color +# so we can use it for reading data values but not be distracting +ax1.yaxis.grid(True, linestyle='-', which='major', color='lightgrey', + alpha=0.5) + +# Hide these grid behind plot objects +ax1.set_axisbelow(True) +ax1.set_title('Comparison of IID Bootstrap Resampling Across Five Distributions') +ax1.set_xlabel('Distribution') +ax1.set_ylabel('Value') + +# Now fill the boxes with desired colors +boxColors = ['darkkhaki','royalblue'] +numBoxes = numDists*2 +medians = range(numBoxes) +for i in range(numBoxes): + box = bp['boxes'][i] + boxX = [] + boxY = [] + for j in range(5): + boxX.append(box.get_xdata()[j]) + boxY.append(box.get_ydata()[j]) + boxCoords = zip(boxX,boxY) + # Alternate between Dark Khaki and Royal Blue + k = i % 2 + boxPolygon = Polygon(boxCoords, facecolor=boxColors[k]) + ax1.add_patch(boxPolygon) + # Now draw the median lines back over what we just filled in + med = bp['medians'][i] + medianX = [] + medianY = [] + for j in range(2): + medianX.append(med.get_xdata()[j]) + medianY.append(med.get_ydata()[j]) + plt.plot(medianX, medianY, 'k') + medians[i] = medianY[0] + # Finally, overplot the sample averages, with horixzontal alignment + # in the center of each box + plt.plot([np.average(med.get_xdata())], [np.average(data[i])], + color='w', marker='*', markeredgecolor='k') + +# Set the axes ranges and axes labels +ax1.set_xlim(0.5, numBoxes+0.5) +top = 40 +bottom = -5 +ax1.set_ylim(bottom, top) +xtickNames = plt.setp(ax1, xticklabels=np.repeat(randomDists, 2)) +plt.setp(xtickNames, rotation=45, fontsize=8) + +# Due to the Y-axis scale being different across samples, it can be +# hard to compare differences in medians across the samples. Add upper +# X-axis tick labels with the sample medians to aid in comparison +# (just use two decimal places of precision) +pos = np.arange(numBoxes)+1 +upperLabels = [str(np.round(s, 2)) for s in medians] +weights = ['bold', 'semibold'] +for tick,label in zip(range(numBoxes),ax1.get_xticklabels()): + k = tick % 2 + ax1.text(pos[tick], top-(top*0.05), upperLabels[tick], + horizontalalignment='center', size='x-small', weight=weights[k], + color=boxColors[k]) + +# Finally, add a basic legend +plt.figtext(0.80, 0.08, str(N) + ' Random Numbers' , + backgroundcolor=boxColors[0], color='black', weight='roman', + size='x-small') +plt.figtext(0.80, 0.045, 'IID Bootstrap Resample', +backgroundcolor=boxColors[1], + color='white', weight='roman', size='x-small') +plt.figtext(0.80, 0.015, '*', color='white', backgroundcolor='silver', + weight='roman', size='medium') +plt.figtext(0.815, 0.013, ' Average Value', color='black', weight='roman', + size='x-small') + +plt.show() Modified: trunk/matplotlib/examples/pylab_examples/load_converter.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/load_converter.py 2009-08-04 13:15:14 UTC (rev 7345) +++ trunk/matplotlib/examples/pylab_examples/load_converter.py 2009-08-04 13:20:29 UTC (rev 7346) @@ -1,8 +1,9 @@ from matplotlib.dates import strpdate2num -from matplotlib.mlab import load +#from matplotlib.mlab import load +import numpy as np from pylab import figure, show -dates, closes = load( +dates, closes = np.loadtxt( '../data/msft.csv', delimiter=',', converters={0:strpdate2num('%d-%b-%y')}, skiprows=1, usecols=(0,2), unpack=True) Modified: trunk/matplotlib/examples/tests/backend_driver.py =================================================================== --- trunk/matplotlib/examples/tests/backend_driver.py 2009-08-04 13:15:14 UTC (rev 7345) +++ trunk/matplotlib/examples/tests/backend_driver.py 2009-08-04 13:20:29 UTC (rev 7346) @@ -373,7 +373,7 @@ if backend in rcsetup.interactive_bk: tmpfile.write('show()') else: - tmpfile.write('\nsavefig("%s", dpi=150)' % outfile) + tmpfile.write('\nsavefig(r"%s", dpi=150)' % outfile) tmpfile.close() start_time = time.time() @@ -457,7 +457,7 @@ python = ['valgrind', '--tool=memcheck', '--leak-check=yes', '--log-file=%(name)s', 'python'] elif sys.platform == 'win32': - python = [r'c:\Python24\python.exe'] + python = [sys.executable] else: python = ['python'] Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2009-08-04 13:15:14 UTC (rev 7345) +++ trunk/matplotlib/lib/matplotlib/axes.py 2009-08-04 13:20:29 UTC (rev 7346) @@ -4229,20 +4229,20 @@ # FIXME: convert the following to proper input validation # raising ValueError; don't use assert for this. - assert len(left)==nbars, "argument 'left' must be %d or scalar" % nbars - assert len(height)==nbars, ("argument 'height' must be %d or scalar" % + assert len(left)==nbars, "incompatible sizes: argument 'left' must be length %d or scalar" % nbars + assert len(height)==nbars, ("incompatible sizes: argument 'height' must be length %d or scalar" % nbars) - assert len(width)==nbars, ("argument 'width' must be %d or scalar" % + assert len(width)==nbars, ("incompatible sizes: argument 'width' must be length %d or scalar" % nbars) - assert len(bottom)==nbars, ("argument 'bottom' must be %d or scalar" % + assert len(bottom)==nbars, ("incompatible sizes: argument 'bottom' must be length %d or scalar" % nbars) if yerr is not None and len(yerr)!=nbars: raise ValueError( - "bar() argument 'yerr' must be len(%s) or scalar" % nbars) + "incompatible sizes: bar() argument 'yerr' must be len(%s) or scalar" % nbars) if xerr is not None and len(xerr)!=nbars: raise ValueError( - "bar() argument 'xerr' must be len(%s) or scalar" % nbars) + "incompatible sizes: bar() argument 'xerr' must be len(%s) or scalar" % nbars) patches = [] Modified: trunk/matplotlib/lib/matplotlib/backends/backend_wx.py =================================================================== --- trunk/matplotlib/lib/matplotlib/backends/backend_wx.py 2009-08-04 13:15:14 UTC (rev 7345) +++ trunk/matplotlib/lib/matplotlib/backends/backend_wx.py 2009-08-04 13:20:29 UTC (rev 7346) @@ -772,6 +772,11 @@ bind(self, wx.EVT_LEAVE_WINDOW, self._onLeave) bind(self, wx.EVT_ENTER_WINDOW, self._onEnter) bind(self, wx.EVT_IDLE, self._onIdle) + #Add middle button events + bind(self, wx.EVT_MIDDLE_DOWN, self._onMiddleButtonDown) + bind(self, wx.EVT_MIDDLE_DCLICK, self._onMiddleButtonDown) + bind(self, wx.EVT_MIDDLE_UP, self._onMiddleButtonUp) + self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM) self.macros = {} # dict from wx id to seq of macros @@ -1183,6 +1188,7 @@ # so no need to do anything here except to make sure # the whole background is repainted. self.Refresh(eraseBackground=False) + FigureCanvasBase.resize_event(self) def _get_key(self, evt): @@ -1251,6 +1257,24 @@ if self.HasCapture(): self.ReleaseMouse() FigureCanvasBase.button_release_event(self, x, y, 1, guiEvent=evt) + #Add middle button events + def _onMiddleButtonDown(self, evt): + """Start measuring on an axis.""" + x = evt.GetX() + y = self.figure.bbox.height - evt.GetY() + evt.Skip() + self.CaptureMouse() + FigureCanvasBase.button_press_event(self, x, y, 2, guiEvent=evt) + + def _onMiddleButtonUp(self, evt): + """End measuring on an axis.""" + x = evt.GetX() + y = self.figure.bbox.height - evt.GetY() + #print 'release button', 1 + evt.Skip() + if self.HasCapture(): self.ReleaseMouse() + FigureCanvasBase.button_release_event(self, x, y, 2, guiEvent=evt) + def _onMouseWheel(self, evt): """Translate mouse wheel events into matplotlib events""" Modified: trunk/matplotlib/lib/matplotlib/mlab.py =================================================================== --- trunk/matplotlib/lib/matplotlib/mlab.py 2009-08-04 13:15:14 UTC (rev 7345) +++ trunk/matplotlib/lib/matplotlib/mlab.py 2009-08-04 13:20:29 UTC (rev 7346) @@ -2595,7 +2595,7 @@ for i, name in enumerate(r.dtype.names): funcs.append(with_mask(csvformat_factory(formatd[name]).tostr)) - fh, opened = cbook.to_filehandle(fname, 'w', return_opened=True) + fh, opened = cbook.to_filehandle(fname, 'wb', return_opened=True) writer = csv.writer(fh, delimiter=delimiter) header = r.dtype.names if withheader: Modified: trunk/matplotlib/lib/matplotlib/texmanager.py =================================================================== --- trunk/matplotlib/lib/matplotlib/texmanager.py 2009-08-04 13:15:14 UTC (rev 7345) +++ trunk/matplotlib/lib/matplotlib/texmanager.py 2009-08-04 13:20:29 UTC (rev 7346) @@ -56,7 +56,7 @@ def dvipng_hack_alpha(): p = Popen('dvipng -version', shell=True, stdin=PIPE, stdout=PIPE, - stderr=STDOUT, close_fds=True) + stderr=STDOUT, close_fds=(sys.platform!='win32')) stdin, stdout = p.stdin, p.stdout for line in stdout: if line.startswith('dvipng '): Modified: trunk/matplotlib/release/osx/Makefile =================================================================== --- trunk/matplotlib/release/osx/Makefile 2009-08-04 13:15:14 UTC (rev 7345) +++ trunk/matplotlib/release/osx/Makefile 2009-08-04 13:20:29 UTC (rev 7346) @@ -1,3 +1,5 @@ +PYVERSION=2.6 +PYTHON=python${PYVERSION} SRCDIR=${PWD} ZLIBVERSION=1.2.3 PNGVERSION=1.2.33 @@ -2,3 +4,4 @@ FREETYPEVERSION=2.3.7 -MPLVERSION=0.98.5.3 +MPLVERSION=0.99.0.rc1 +BDISTMPKGVERSION=0.4.4 MPLSRC=matplotlib-${MPLVERSION} @@ -20,8 +23,8 @@ clean: rm -rf zlib-${ZLIBVERSION}.tar.gz libpng-${PNGVERSION}.tar.bz2 \ - freetype-${FREETYPEVERSION}.tar.bz2 bdist_mpkg-0.4.3.tar.gz \ - bdist_mpkg-0.4.3 \ + freetype-${FREETYPEVERSION}.tar.bz2 bdist_mpkg-${BDISTMPKGVERSION}.tar.gz \ + bdist_mpkg-${BDISTMPKGVERSION} \ zlib-${ZLIBVERSION} libpng-${PNGVERSION} freetype-${FREETYPEVERSION} \ matplotlib-${MPLVERSION} *~ @@ -29,10 +32,9 @@ wget http://www.zlib.net/zlib-${ZLIBVERSION}.tar.gz &&\ wget http://internap.dl.sourceforge.net/sourceforge/libpng/libpng-${PNGVERSION}.tar.bz2 &&\ wget http://download.savannah.gnu.org/releases/freetype/freetype-${FREETYPEVERSION}.tar.bz2&&\ - wget http://pypi.python.org/packages/source/b/bdist_mpkg/bdist_mpkg-0.4.3.tar.gz&&\ - tar xvfz bdist_mpkg-0.4.3.tar.gz &&\ - patch -p0 < data/bdist.patch - echo "You need to to install bdist_mpkg-0.4.3 now" + wget http://pypi.python.org/packages/source/b/bdist_mpkg/bdist_mpkg-${BDISTMPKGVERSION}.tar.gz&&\ + tar xvfz bdist_mpkg-${BDISTMPKGVERSION}.tar.gz &&\ + echo "You need to to install bdist_mpkg-${BDISTMPKGVERSION} now" @@ -87,16 +89,16 @@ export CFLAGS=${CFLAGS} &&\ export LDFLAGS=${LDFLAGS} &&\ bdist_mpkg &&\ - python setupegg.py bdist_egg &&\ + ${PYTHON} setupegg.py bdist_egg &&\ cd dist && \ - zip -ro matplotlib-${MPLVERSION}-py2.5-macosx10.5.zip matplotlib-${MPLVERSION}-py2.5-macosx10.5.mpkg + zip -ro matplotlib-${MPLVERSION}-py${PYVERSION}-macosx10.5_mpkg.zip matplotlib-${MPLVERSION}-py${PYVERSION}-macosx10.5.mpkg upload: rm -rf upload &&\ mkdir upload &&\ cp matplotlib-${MPLVERSION}.tar.gz upload/ &&\ - cp matplotlib-${MPLVERSION}/dist/matplotlib-${MPLVERSION}_r0-py2.5-macosx-10.3-fat.egg upload/matplotlib-${MPLVERSION}-macosx-py2.5.egg &&\ - cp matplotlib-${MPLVERSION}/dist/matplotlib-${MPLVERSION}-py2.5-macosx10.5.zip upload/matplotlib-${MPLVERSION}-py2.5-mpkg.zip&&\ + cp matplotlib-${MPLVERSION}/dist/matplotlib-${MPLVERSION}_r0-py${PYVERSION}-macosx-10.3-fat.egg upload/matplotlib-${MPLVERSION}-macosx-py${PYVERSION}.egg &&\ + cp matplotlib-${MPLVERSION}/dist/matplotlib-${MPLVERSION}-py${PYVERSION}-macosx10.5.zip upload/matplotlib-${MPLVERSION}-py${PYVERSION}-mpkg.zip&&\ scp upload/* jd...@fr...:uploads/ all: Modified: trunk/matplotlib/release/osx/README.txt =================================================================== --- trunk/matplotlib/release/osx/README.txt 2009-08-04 13:15:14 UTC (rev 7345) +++ trunk/matplotlib/release/osx/README.txt 2009-08-04 13:20:29 UTC (rev 7346) @@ -7,9 +7,7 @@ ------------- * :file:`bdist_mkpg` - the distutils.extension to build Installer.app - mpkg installers. It is patched from the tarball with - file:`data/bdist.patch` because 0.4.3 is broken on OS X 10.5. - Instructions on how to patch and install are below + mpkg installers. * :file:`data` - some config files and patches needed for the build @@ -21,6 +19,16 @@ How to build -------------- +* You need a python framework build , numpy and wxpython to build the + mpl installers (wx requires this and we need wx to build the wxagg + extension). You can get the three required dependencies as + Installer apps, eg: + + + http://www.python.org/ftp/python/2.6.2/python-2.6.2-macosx2009-04-16.dmg + http://downloads.sourceforge.net/project/numpy/NumPy/1.3.0/numpy-1.3.0-py2.6-macosx10.5.dmg?use_mirror=voxel + http://downloads.sourceforge.net/project/wxpython/wxPython/2.8.10.1/wxPython2.8-osx-unicode-2.8.10.1-universal-py2.6.dmg?use_mirror=voxel + * You need to make sure to unset PKG_CONFIG_PATH to make sure the static linking below is respected. Otherwise the mpl build script will dynamically link using the libs from pkgconfig if you have this @@ -38,7 +46,7 @@ * install the patched bdist_mpkg, that the fetch_deps step just created:: - cd bdist_mpkg-0.4.3 + cd bdist_mpkg-0.4.4 sudo python setup.py install * build the dependencies:: @@ -64,7 +72,7 @@ cd release/osx/ unset PKG_CONFIG_PATH make fetch_deps - cd bdist_mpkg-0.4.3 + cd bdist_mpkg-0.4.4 sudo python setup.py install cd .. make dependencies Modified: trunk/matplotlib/release/win32/Makefile =================================================================== --- trunk/matplotlib/release/win32/Makefile 2009-08-04 13:15:14 UTC (rev 7345) +++ trunk/matplotlib/release/win32/Makefile 2009-08-04 13:20:29 UTC (rev 7346) @@ -1,4 +1,4 @@ -PYDIR = C:/Python26 +PYDIR = C:/Python25 PYTHON = ${PYDIR}/python.exe SRCDIR = ${PWD} WINSRCDIR = `${PWD}/data/mingw_path.sh ${PWD}` @@ -6,7 +6,7 @@ PNGVERSION = 1.2.36 FREETYPEVERSION = 2.3.9 TCLTKVERSION = 8.5.7 -MPLVERSION = 0.98.5.3 +MPLVERSION = 0.99.0.rc1 ## You shouldn't need to configure past this point @@ -89,8 +89,8 @@ rm -rf build &&\ cp ../data/setup*.* . &&\ export CFLAGS="${CFLAGS}" &&\ - ${PYTHON} setupwin.py build_ext -c mingw32 -I ${PY_INCLUDE} -L ${PY_LINKER} bdist_wininst - #${PYTHON} setupwinegg.py build_ext -c mingw32 -I ${PY_INCLUDE} -L ${PY_LINKER} bdist_egg + ${PYTHON} setupwin.py build_ext -c mingw32 -I ${PY_INCLUDE} -L ${PY_LINKER} bdist_wininst &&\ + ${PYTHON} setupwinegg.py build_ext -c mingw32 -I ${PY_INCLUDE} -L ${PY_LINKER} bdist_egg inplace: Modified: trunk/matplotlib/setupext.py =================================================================== --- trunk/matplotlib/setupext.py 2009-08-04 13:15:14 UTC (rev 7345) +++ trunk/matplotlib/setupext.py 2009-08-04 13:20:29 UTC (rev 7346) @@ -51,7 +51,7 @@ 'linux' : ['/usr/local', '/usr',], 'cygwin' : ['/usr/local', '/usr',], 'darwin' : ['/sw/lib/freetype2', '/sw/lib/freetype219', '/usr/local', - '/usr', '/sw', '/usr/X11R6'], + '/usr', '/sw'], 'freebsd4' : ['/usr/local', '/usr'], 'freebsd5' : ['/usr/local', '/usr'], 'freebsd6' : ['/usr/local', '/usr'], @@ -174,7 +174,7 @@ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, - close_fds=True) + close_fds=(sys.platform != 'win32')) return p.stdin, p.stdout class CleanUpFile: @@ -458,7 +458,7 @@ try: stdin, stdout = run_child_process('latex -version') line = stdout.readlines()[0] - pattern = '3\.1\d+' + pattern = '(3\.1\d+)|(MiKTeX \d+.\d+)' match = re.search(pattern, line) print_status("latex", match.group(0)) return True Modified: trunk/matplotlib/src/_macosx.m =================================================================== --- trunk/matplotlib/src/_macosx.m 2009-08-04 13:15:14 UTC (rev 7345) +++ trunk/matplotlib/src/_macosx.m 2009-08-04 13:20:29 UTC (rev 7346) @@ -7,15 +7,19 @@ static int nwin = 0; /* The number of open windows */ + +/* Use Atsui for Mac OS X 10.4, CoreText for Mac OS X 10.5 */ +#ifndef MAC_OS_X_VERSION_10_5 static int ngc = 0; /* The number of graphics contexts in use */ /* For drawing Unicode strings with ATSUI */ static ATSUStyle style = NULL; static ATSUTextLayout layout = NULL; +#endif /* CGFloat was defined in Mac OS X 10.5 */ -#ifndef CGFloat +#ifndef CGFLOAT_DEFINED #define CGFloat float #endif @@ -171,6 +175,7 @@ return 1; } +#ifndef MAC_OS_X_VERSION_10_5 static int _init_atsui(void) { OSStatus status; @@ -208,6 +213,7 @@ if (status!=noErr) PyErr_WarnEx(PyExc_RuntimeWarning, "ATSUDisposeTextLayout failed", 1); } +#endif static int _draw_path(CGContextRef cr, void* iterator) { @@ -336,6 +342,10 @@ - (void)mouseUp:(NSEvent*)event; - (void)mouseDragged:(NSEvent*)event; - (void)mouseMoved:(NSEvent*)event; +- (void)rightMouseDown:(NSEvent*)event; +- (void)rightMouseUp:(NSEvent*)event; +- (void)otherMouseDown:(NSEvent*)event; +- (void)otherMouseUp:(NSEvent*)event; - (void)setRubberband:(NSRect)rect; - (void)removeRubberband; - (const char*)convertKeyEvent:(NSEvent*)event; @@ -375,6 +385,7 @@ CGContextRef cr; NSSize size; int level; + CGFloat color[4]; } GraphicsContext; static CGMutablePathRef _create_path(void* iterator) @@ -440,6 +451,7 @@ self->cr = NULL; self->level = 0; +#ifndef MAC_OS_X_VERSION_10_5 if (ngc==0) { int ok = _init_atsui(); @@ -449,10 +461,12 @@ } } ngc++; +#endif return (PyObject*) self; } +#ifndef MAC_OS_X_VERSION_10_5 static void GraphicsContext_dealloc(GraphicsContext *self) { @@ -461,6 +475,7 @@ self->ob_type->tp_free((PyObject*)self); } +#endif static PyObject* GraphicsContext_repr(GraphicsContext* self) @@ -516,6 +531,9 @@ return NULL; } CGContextSetAlpha(cr, alpha); + + self->color[3] = alpha; + Py_INCREF(Py_None); return Py_None; } @@ -651,7 +669,7 @@ static BOOL _set_dashes(CGContextRef cr, PyObject* linestyle) { - float phase = 0.0; + CGFloat phase = 0.0; PyObject* offset; PyObject* dashes; @@ -686,7 +704,7 @@ } int n = PyTuple_GET_SIZE(dashes); int i; - float* lengths = malloc(n*sizeof(float)); + CGFloat* lengths = malloc(n*sizeof(CGFloat)); if(!lengths) { PyErr_SetString(PyExc_MemoryError, "Failed to store dashes"); @@ -697,9 +715,9 @@ { PyObject* value = PyTuple_GET_ITEM(dashes, i); if (PyFloat_Check(value)) - lengths[i] = (float) PyFloat_AS_DOUBLE(value); + lengths[i] = (CGFloat) PyFloat_AS_DOUBLE(value); else if (PyInt_Check(value)) - lengths[i] = (float) PyInt_AS_LONG(value); + lengths[i] = (CGFloat) PyInt_AS_LONG(value); else break; } Py_DECREF(dashes); @@ -750,6 +768,11 @@ CGContextSetRGBStrokeColor(cr, r, g, b, 1.0); CGContextSetRGBFillColor(cr, r, g, b, 1.0); + + self->color[0] = r; + self->color[1] = g; + self->color[2] = b; + Py_INCREF(Py_None); return Py_None; } @@ -889,28 +912,12 @@ } else { - int ok; - float color[4] = {0, 0, 0, 1}; CGPatternRef pattern; CGColorSpaceRef baseSpace; CGColorSpaceRef patternSpace; static const CGPatternCallbacks callbacks = {0, &_draw_hatch, &_release_hatch}; - PyObject* rgb = PyObject_CallMethod((PyObject*)self, "get_rgb", ""); - if (!rgb) - { - Py_DECREF(hatchpath); - return NULL; - } - ok = PyArg_ParseTuple(rgb, "ffff", &color[0], &color[1], &color[2], &color[3]); - Py_DECREF(rgb); - if (!ok) - { - Py_DECREF(hatchpath); - return NULL; - } - baseSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB); if (!baseSpace) { @@ -938,7 +945,7 @@ kCGPatternTilingNoDistortion, false, &callbacks); - CGContextSetFillPattern(cr, pattern, color); + CGContextSetFillPattern(cr, pattern, self->color); CGPatternRelease(pattern); iterator = get_path_iterator(path, transform, @@ -1227,6 +1234,8 @@ if (Ntransforms) { + CGAffineTransform master; + double a, b, c, d, tx, ty; PyObject* values = PyObject_CallMethod(master_transform, "to_values", ""); if (!values) { @@ -1239,15 +1248,15 @@ ok = 0; goto exit; } - CGAffineTransform master; - ok = PyArg_ParseTuple(values, "ffffff", - &master.a, - &master.b, - &master.c, - &master.d, - &master.tx, - &master.ty); + /* CGAffineTransform contains CGFloat; cannot use master directly */ + ok = PyArg_ParseTuple(values, "dddddd", &a, &b, &c, &d, &tx, &ty); Py_DECREF(values); + master.a = a; + master.b = b; + master.c = c; + master.d = d; + master.tx = tx; + master.ty = ty; if (!ok) goto exit; CGContextConcatCTM(cr, master); } @@ -1652,13 +1661,15 @@ } if (PyTuple_Check(values)) { - ok = PyArg_ParseTuple(values, "ffffff", - &master.a, - &master.b, - &master.c, - &master.d, - &master.tx, - &master.ty); + double a, b, c, d, tx, ty; + /* CGAffineTransform contains CGFloat; cannot use master directly */ + ok = PyArg_ParseTuple(values, "dddddd", &a, &b, &c, &d, &tx, &ty); + master.a = a; + master.b = b; + master.c = c; + master.d = d; + master.tx = tx; + master.ty = ty; } else { @@ -1866,7 +1877,11 @@ } +#ifdef MAC_OS_X_VERSION_10_5 +static CTFontRef +#else static ATSFontRef +#endif setfont(CGContextRef cr, PyObject* family, float size, const char weight[], const char italic[]) { @@ -1876,7 +1891,11 @@ const char* temp; const char* name = "Times-Roman"; CFStringRef string; - ATSFontRef atsfont = 0; +#ifdef MAC_OS_X_VERSION_10_5 + CTFontRef font = 0; +#else + ATSFontRef font = 0; +#endif const int k = (strcmp(italic, "italic") ? 0 : 2) + (strcmp(weight, "bold") ? 0 : 1); @@ -2072,26 +2091,38 @@ string = CFStringCreateWithCString(kCFAllocatorDefault, temp, kCFStringEncodingMacRoman); - atsfont = ATSFontFindFromPostScriptName(string, kATSOptionFlagsDefault); +#ifdef MAC_OS_X_VERSION_10_5 + font = CTFontCreateWithName(string, size, NULL); +#else + font = ATSFontFindFromPostScriptName(string, kATSOptionFlagsDefault); +#endif + CFRelease(string); - if(atsfont) + if(font) { name = temp; break; } } - if(!atsfont) + if(!font) { string = CFStringCreateWithCString(kCFAllocatorDefault, name, kCFStringEncodingMacRoman); - atsfont = ATSFontFindFromPostScriptName(string, kATSOptionFlagsDefault); +#ifdef MAC_OS_X_VERSION_10_5 + font = CTFontCreateWithName(string, size, NULL); +#else + font = ATSFontFindFromPostScriptName(string, kATSOptionFlagsDefault); +#endif CFRelease(string); } +#ifndef MAC_OS_X_VERSION_10_5 CGContextSelectFont(cr, name, size, kCGEncodingMacRoman); - return atsfont; +#endif + return font; } +#ifdef MAC_OS_X_VERSION_10_5 static PyObject* GraphicsContext_draw_text (GraphicsContext* self, PyObject* args) { @@ -2104,6 +2135,174 @@ const char* weight; const char* italic; float angle; + CTFontRef font; + CGColorRef color; + CGFloat descent; + + CFStringRef keys[2]; + CFTypeRef values[2]; + + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + + if(!PyArg_ParseTuple(args, "ffu#Ofssf", + &x, + &y, + &text, + &n, + &family, + &size, + &weight, + &italic, + &angle)) return NULL; + + font = setfont(cr, family, size, weight, italic); + + color = CGColorCreateGenericRGB(self->color[0], + self->color[1], + self->color[2], + self->color[3]); + + keys[0] = kCTFontAttributeName; + keys[1] = kCTForegroundColorAttributeName; + values[0] = font; + values[1] = color; + CFDictionaryRef attributes = CFDictionaryCreate(kCFAllocatorDefault, + (const void**)&keys, + (const void**)&values, + 2, + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + CGColorRelease(color); + CFRelease(font); + + CFStringRef s = CFStringCreateWithCharacters(kCFAllocatorDefault, text, n); + + CFAttributedStringRef string = CFAttributedStringCreate(kCFAllocatorDefault, + s, + attributes); + CFRelease(s); + CFRelease(attributes); + + CTLineRef line = CTLineCreateWithAttributedString(string); + CFRelease(string); + + CTLineGetTypographicBounds(line, NULL, &descent, NULL); + + if (!line) + { + PyErr_SetString(PyExc_RuntimeError, + "CTLineCreateWithAttributedString failed"); + return NULL; + } + + CGContextSetTextMatrix(cr, CGAffineTransformIdentity); + if (angle) + { + CGContextSaveGState(cr); + CGContextTranslateCTM(cr, x, y); + CGContextRotateCTM(cr, angle*M_PI/180); + CTLineDraw(line, cr); + CGContextRestoreGState(cr); + } + else + { + CGContextSetTextPosition(cr, x, y); + CTLineDraw(line, cr); + } + CFRelease(line); + + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject* +GraphicsContext_get_text_width_height_descent(GraphicsContext* self, PyObject* args) +{ + const UniChar* text; + int n; + PyObject* family; + float size; + const char* weight; + const char* italic; + + CGFloat ascent; + CGFloat descent; + double width; + CGRect rect; + + CTFontRef font; + + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + + if(!PyArg_ParseTuple(args, "u#Ofss", + &text, &n, &family, &size, &weight, &italic)) + return NULL; + + font = setfont(cr, family, size, weight, italic); + + CFStringRef keys[1]; + CFTypeRef values[1]; + + keys[0] = kCTFontAttributeName; + values[0] = font; + CFDictionaryRef attributes = CFDictionaryCreate(kCFAllocatorDefault, + (const void**)&keys, + (const void**)&values, + 1, + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + CFRelease(font); + + CFStringRef s = CFStringCreateWithCharacters(kCFAllocatorDefault, text, n); + + CFAttributedStringRef string = CFAttributedStringCreate(kCFAllocatorDefault, + s, + attributes); + CFRelease(s); + CFRelease(attributes); + + CTLineRef line = CTLineCreateWithAttributedString(string); + CFRelease(string); + + if (!line) + { + PyErr_SetString(PyExc_RuntimeError, + "CTLineCreateWithAttributedString failed"); + return NULL; + } + + width = CTLineGetTypographicBounds(line, &ascent, &descent, NULL); + rect = CTLineGetImageBounds(line, cr); + + CFRelease(line); + + return Py_BuildValue("fff", width, rect.size.height, descent); +} + +#else + +static PyObject* +GraphicsContext_draw_text (GraphicsContext* self, PyObject* args) +{ + float x; + float y; + const UniChar* text; + int n; + PyObject* family; + float size; + const char* weight; + const char* italic; + float angle; ATSFontRef atsfont; CGContextRef cr = self->cr; if (!cr) @@ -2188,6 +2387,102 @@ return Py_None; } +static PyObject* +GraphicsContext_get_text_width_height_descent(GraphicsContext* self, PyObject* args) +{ + const UniChar* text; + int n; + PyObject* family; + float size; + const char* weight; + const char* italic; + + ATSFontRef atsfont; + + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + + if(!PyArg_ParseTuple(args, "u#Ofss", &text, &n, &family, &size, &weight, &italic)) return NULL; + + atsfont = setfont(cr, family, size, weight, italic); + + OSStatus status = noErr; + ATSUAttributeTag tags[] = {kATSUFontTag, + kATSUSizeTag, + kATSUQDBoldfaceTag, + kATSUQDItalicTag}; + ByteCount sizes[] = {sizeof(ATSUFontID), + sizeof(Fixed), + sizeof(Boolean), + sizeof(Boolean)}; + Fixed atsuSize = Long2Fix(size); + Boolean isBold = FALSE; /* setfont takes care of this */ + Boolean isItalic = FALSE; /* setfont takes care of this */ + ATSUAttributeValuePtr values[] = {&atsfont, &atsuSize, &isBold, &isItalic}; + + status = ATSUSetAttributes(style, 4, tags, sizes, values); + if (status!=noErr) + { + PyErr_SetString(PyExc_RuntimeError, "ATSUSetAttributes failed"); + return NULL; + } + + status = ATSUSetTextPointerLocation(layout, + text, + kATSUFromTextBeginning, /* offset from beginning */ + kATSUToTextEnd, /* length of text range */ + n); /* length of text buffer */ + if (status!=noErr) + { + PyErr_SetString(PyExc_RuntimeError, + "ATSUCreateTextLayoutWithTextPtr failed"); + return NULL; + } + + status = ATSUSetRunStyle(layout, + style, + kATSUFromTextBeginning, + kATSUToTextEnd); + if (status!=noErr) + { + PyErr_SetString(PyExc_RuntimeError, "ATSUSetRunStyle failed"); + return NULL; + } + + ATSUAttributeTag tag = kATSUCGContextTag; + ByteCount bc = sizeof (CGContextRef); + ATSUAttributeValuePtr value = &cr; + status = ATSUSetLayoutControls(layout, 1, &tag, &bc, &value); + if (status!=noErr) + { + PyErr_SetString(PyExc_RuntimeError, "ATSUSetLayoutControls failed"); + return NULL; + } + + ATSUTextMeasurement before; + ATSUTextMeasurement after; + ATSUTextMeasurement ascent; + ATSUTextMeasurement descent; + status = ATSUGetUnjustifiedBounds(layout, + kATSUFromTextBeginning, kATSUToTextEnd, + &before, &after, &ascent, &descent); + if (status!=noErr) + { + PyErr_SetString(PyExc_RuntimeError, "ATSUGetUnjustifiedBounds failed"); + return NULL; + } + + const float width = FixedToFloat(after-before); + const float height = FixedToFloat(ascent-descent); + + return Py_BuildValue("fff", width, height, FixedToFloat(descent)); +} +#endif + static void _data_provider_release(void* info, const void* data, size_t size) { PyObject* image = (PyObject*)info; @@ -2293,101 +2588,6 @@ } static PyObject* -GraphicsContext_get_text_width_height_descent(GraphicsContext* self, PyObject* args) -{ - const UniChar* text; - int n; - PyObject* family; - float size; - const char* weight; - const char* italic; - - ATSFontRef atsfont; - - CGContextRef cr = self->cr; - if (!cr) - { - PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); - return NULL; - } - - if(!PyArg_ParseTuple(args, "u#Ofss", &text, &n, &family, &size, &weight, &italic)) return NULL; - - atsfont = setfont(cr, family, size, weight, italic); - - OSStatus status = noErr; - ATSUAttributeTag tags[] = {kATSUFontTag, - kATSUSizeTag, - kATSUQDBoldfaceTag, - kATSUQDItalicTag}; - ByteCount sizes[] = {sizeof(ATSUFontID), - sizeof(Fixed), - sizeof(Boolean), - sizeof(Boolean)}; - Fixed atsuSize = Long2Fix(size); - Boolean isBold = FALSE; /* setfont takes care of this */ - Boolean isItalic = FALSE; /* setfont takes care of this */ - ATSUAttributeValuePtr values[] = {&atsfont, &atsuSize, &isBold, &isItalic}; - - status = ATSUSetAttributes(style, 4, tags, sizes, values); - if (status!=noErr) - { - PyErr_SetString(PyExc_RuntimeError, "ATSUSetAttributes failed"); - return NULL; - } - - status = ATSUSetTextPointerLocation(layout, - text, - kATSUFromTextBeginning, /* offset from beginning */ - kATSUToTextEnd, /* length of text range */ - n); /* length of text buffer */ - if (status!=noErr) - { - PyErr_SetString(PyExc_RuntimeError, - "ATSUCreateTextLayoutWithTextPtr failed"); - return NULL; - } - - status = ATSUSetRunStyle(layout, - style, - kATSUFromTextBeginning, - kATSUToTextEnd); - if (status!=noErr) - { - PyErr_SetString(PyExc_RuntimeError, "ATSUSetRunStyle failed"); - return NULL; - } - - ATSUAttributeTag tag = kATSUCGContextTag; - ByteCount bc = sizeof (CGContextRef); - ATSUAttributeValuePtr value = &cr; - status = ATSUSetLayoutControls(layout, 1, &tag, &bc, &value); - if (status!=noErr) - { - PyErr_SetString(PyExc_RuntimeError, "ATSUSetLayoutControls failed"); - return NULL; - } - - ATSUTextMeasurement before; - ATSUTextMeasurement after; - ATSUTextMeasurement ascent; - ATSUTextMeasurement descent; - status = ATSUGetUnjustifiedBounds(layout, - kATSUFromTextBeginning, kATSUToTextEnd, - &before, &after, &ascent, &descent); - if (status!=noErr) - { - PyErr_SetString(PyExc_RuntimeError, "ATSUGetUnjustifiedBounds failed"); - return NULL; - } - - const float width = FixedToFloat(after-before); - const float height = FixedToFloat(ascent-descent); - - return Py_BuildValue("fff", width, height, FixedToFloat(descent)); -} - -static PyObject* GraphicsContext_draw_image(GraphicsContext* self, PyObject* args) { float x, y; @@ -2621,7 +2821,11 @@ "_macosx.GraphicsContext", /*tp_name*/ sizeof(GraphicsContext), /*tp_basicsize*/ 0, /*tp_itemsize*/ +#ifdef MAC_OS_X_VERSION_10_5 + 0, /*tp_dealloc*/ +#else (destructor)GraphicsContext_dealloc, /*tp_dealloc*/ +#endif 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ @@ -2826,15 +3030,18 @@ int n; const unichar* characters; NSSize size; + double width, height; if(!view) { PyErr_SetString(PyExc_RuntimeError, "NSView* is NULL"); return NULL; } - if(!PyArg_ParseTuple(args, "u#ff", - &characters, &n, - &size.width, &size.height)) return NULL; + /* NSSize contains CGFloat; cannot use size directly */ + if(!PyArg_ParseTuple(args, "u#dd", + &characters, &n, &width, &height)) return NULL; + size.width = width; + size.height = height; /* This function may be called from inside the event loop, when an * autorelease pool is available, or from Python, when no autorelease @@ -4492,6 +4699,86 @@ PyGILState_Release(gstate); } +- (void)rightMouseDown:(NSEvent *)event +{ + int x, y; + int num = 3; + PyObject* result; + PyGILState_STATE gstate; + NSPoint location = [event locationInWindow]; + location = [self convertPoint: location fromView: nil]; + x = location.x; + y = location.y; + gstate = PyGILState_Ensure(); + result = PyObject_CallMethod(canvas, "button_press_event", "iii", x, y, num); + if(result) + Py_DECREF(result); + else + PyErr_Print(); + + PyGILState_Release(gstate); +} + +- (void)rightMouseUp:(NSEvent *)event +{ + int x, y; + int num = 3; + PyObject* result; + PyGILState_STATE gstate; + NSPoint location = [event locationInWindow]; + location = [self convertPoint: location fromView: nil]; + x = location.x; + y = location.y; + gstate = PyGILState_Ensure(); + result = PyObject_CallMethod(canvas, "button_release_event", "iii", x, y, num); + if(result) + Py_DECREF(result); + else + PyErr_Print(); + + PyGILState_Release(gstate); +} + +- (void)otherMouseDown:(NSEvent *)event +{ + int x, y; + int num = 2; + PyObject* result; + PyGILState_STATE gstate; + NSPoint location = [event locationInWindow]; + location = [self convertPoint: location fromView: nil]; + x = location.x; + y = location.y; + gstate = PyGILState_Ensure(); + result = PyObject_CallMethod(canvas, "button_press_event", "iii", x, y, num); + if(result) + Py_DECREF(result); + else + PyErr_Print(); + + PyGILState_Release(gstate); +} + +- (void)otherMouseUp:(NSEvent *)event +{ + int x, y; + int num = 2; + PyObject* result; + PyGILState_STATE gstate; + NSPoint location = [event locationInWindow]; + location = [self convertPoint: location fromView: nil]; + x = location.x; + y = location.y; + gstate = PyGILState_Ensure(); + result = PyObject_CallMethod(canvas, "button_release_event", "iii", x, y, num); + if(result) + Py_DECREF(result); + else + PyErr_Print(); + + PyGILState_Release(gstate); +} + - (void)setRubberband:(NSRect)rect { if (!NSIsEmptyRect(rubberband)) [self setNeedsDisplayInRect: rubberband]; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |