From: <jd...@us...> - 2009-05-17 14:55:02
|
Revision: 7111 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7111&view=rev Author: jdh2358 Date: 2009-05-17 14:54:57 +0000 (Sun, 17 May 2009) Log Message: ----------- Merged revisions 7106-7109 via svnmerge from https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/v0_98_5_maint ........ r7106 | jdh2358 | 2009-05-17 09:11:35 -0500 (Sun, 17 May 2009) | 1 line tagging changelog for release ........ r7107 | jdh2358 | 2009-05-17 09:13:14 -0500 (Sun, 17 May 2009) | 1 line removed some deprecation warnings from mlab ........ r7108 | jdh2358 | 2009-05-17 09:22:31 -0500 (Sun, 17 May 2009) | 1 line tag changelog for release ........ r7109 | jdh2358 | 2009-05-17 09:51:09 -0500 (Sun, 17 May 2009) | 1 line updated url in release doc ........ Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/doc/devel/release_guide.rst trunk/matplotlib/lib/matplotlib/mlab.py Property Changed: ---------------- trunk/matplotlib/ Property changes on: trunk/matplotlib ___________________________________________________________________ Modified: svnmerge-integrated - /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-7082 + /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-7110 Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-05-17 14:52:47 UTC (rev 7110) +++ trunk/matplotlib/CHANGELOG 2009-05-17 14:54:57 UTC (rev 7111) @@ -1,10 +1,12 @@ ====================================================================== -2009-05-13 An optional offset and bbox support in restore_bbox. +2008-05-17 Release 0.98.5.3 at r7107 from the branch - JDH + +2009-05-13 An optional offset and bbox support in restore_bbox. Add animation_blit_gtk2.py. -JJL -2009-05-13 psfrag in backend_ps now uses baseline-alignment +2009-05-13 psfrag in backend_ps now uses baseline-alignment when preview.sty is used ((default is - bottom-alignment). Also, a small api imporvement + bottom-alignment). Also, a small api imporvement in OffsetBox-JJL 2009-05-13 When the x-coordinate of a line is monotonically Modified: trunk/matplotlib/doc/devel/release_guide.rst =================================================================== --- trunk/matplotlib/doc/devel/release_guide.rst 2009-05-17 14:52:47 UTC (rev 7110) +++ trunk/matplotlib/doc/devel/release_guide.rst 2009-05-17 14:54:57 UTC (rev 7111) @@ -120,7 +120,7 @@ sftp> put matplotlib-0.98.2.tar.gz Uploading matplotlib-0.98.2.tar.gz to /incoming/j/jd/jdh2358/uploads/matplotlib-0.98.2.tar.gz -* go https://sourceforge.net/project/admin/?group_id=80706 and do a +* go https://sourceforge.net/project/admin/editpackages.php?group_id=80706 and do a file release. Click on the "Admin" tab to log in as an admin, and then the "File Releases" tab. Go to the bottom and click "add release" and enter the package name but not the version number in Modified: trunk/matplotlib/lib/matplotlib/mlab.py =================================================================== --- trunk/matplotlib/lib/matplotlib/mlab.py 2009-05-17 14:52:47 UTC (rev 7110) +++ trunk/matplotlib/lib/matplotlib/mlab.py 2009-05-17 14:54:57 UTC (rev 7111) @@ -275,11 +275,6 @@ pad_to = NFFT if scale_by_freq is None: - warnings.warn("psd, csd, and specgram have changed to scale their " - "densities by the sampling frequency for better MatLab " - "compatibility. You can pass scale_by_freq=False to disable " - "this behavior. Also, one-sided densities are scaled by a " - "factor of 2.") scale_by_freq = True # For real x, ignore the negative frequencies unless told otherwise @@ -1884,8 +1879,6 @@ much faster. """ if typecode is not None: - warnings.warn("Use dtype kwarg instead of typecode", - DeprecationWarning) dtype = typecode iden = np.zeros((n,)*rank, dtype) for i in range(n): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2009-05-17 15:08:13
|
Revision: 7112 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7112&view=rev Author: jdh2358 Date: 2009-05-17 15:08:07 +0000 (Sun, 17 May 2009) Log Message: ----------- applied Michiel's sf patch 2792742 to speed up Cairo and macosx collections Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/backend_bases.py trunk/matplotlib/lib/matplotlib/backends/backend_cairo.py trunk/matplotlib/lib/matplotlib/backends/backend_gtkcairo.py trunk/matplotlib/lib/matplotlib/backends/backend_macosx.py trunk/matplotlib/lib/matplotlib/lines.py trunk/matplotlib/lib/matplotlib/patches.py trunk/matplotlib/lib/matplotlib/text.py trunk/matplotlib/lib/mpl_toolkits/axes_grid/axislines.py trunk/matplotlib/src/_macosx.m Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-05-17 14:54:57 UTC (rev 7111) +++ trunk/matplotlib/CHANGELOG 2009-05-17 15:08:07 UTC (rev 7112) @@ -1,4 +1,8 @@ +2009-05-19 applied Michiel's sf patch 2792742 to speed up Cairo and + macosx collections; speedups can be 20x + ====================================================================== + 2008-05-17 Release 0.98.5.3 at r7107 from the branch - JDH 2009-05-13 An optional offset and bbox support in restore_bbox. Modified: trunk/matplotlib/lib/matplotlib/backend_bases.py =================================================================== --- trunk/matplotlib/lib/matplotlib/backend_bases.py 2009-05-17 14:54:57 UTC (rev 7111) +++ trunk/matplotlib/lib/matplotlib/backend_bases.py 2009-05-17 15:08:07 UTC (rev 7112) @@ -277,6 +277,7 @@ gc.set_url(urls[i % Nurls]) yield xo, yo, path_id, gc, rgbFace + gc.restore() def get_image_magnification(self): """ @@ -459,6 +460,13 @@ self._url = gc._url self._snap = gc._snap + def restore(self): + """ + Restore the graphics context from the stack - needed only + for backends that save graphics contexts on a stack + """ + pass + def get_alpha(self): """ Return the alpha value used for blending - not supported on Modified: trunk/matplotlib/lib/matplotlib/backends/backend_cairo.py =================================================================== --- trunk/matplotlib/lib/matplotlib/backends/backend_cairo.py 2009-05-17 14:54:57 UTC (rev 7111) +++ trunk/matplotlib/lib/matplotlib/backends/backend_cairo.py 2009-05-17 15:08:07 UTC (rev 7112) @@ -91,13 +91,13 @@ """ if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name()) self.dpi = dpi + self.gc = GraphicsContextCairo (renderer=self) self.text_ctx = cairo.Context ( cairo.ImageSurface (cairo.FORMAT_ARGB32,1,1)) self.mathtext_parser = MathTextParser('Cairo') def set_ctx_from_surface (self, surface): - self.ctx = cairo.Context (surface) - self.ctx.save() # restore, save - when call new_gc() + self.gc.ctx = cairo.Context (surface) def set_width_height(self, width, height): @@ -109,22 +109,6 @@ # font transform? - def _do_clip(self, ctx, cliprect, clippath): - if cliprect is not None: - x,y,w,h = cliprect.bounds - # pixel-aligned clip-regions are faster - x,y,w,h = round(x), round(y), round(w), round(h) - ctx.new_path() - ctx.rectangle (x, self.height - h - y, w, h) - ctx.clip () - - if clippath is not None: - tpath, affine = clippath.get_transformed_path_and_affine() - ctx.new_path() - affine = affine + Affine2D().scale(1.0, -1.0).translate(0.0, self.height) - RendererCairo.convert_path(ctx, tpath, affine) - ctx.clip() - def _fill_and_stroke (self, ctx, fill_c, alpha): if fill_c is not None: ctx.save() @@ -158,8 +142,6 @@ raise ValueError("The Cairo backend can not draw paths longer than 18980 points.") ctx = gc.ctx - ctx.save() - self._do_clip(ctx, gc._cliprect, gc._clippath) transform = transform + \ Affine2D().scale(1.0, -1.0).translate(0, self.height) @@ -168,7 +150,6 @@ self.convert_path(ctx, path, transform) self._fill_and_stroke(ctx, rgbFace, gc.get_alpha()) - ctx.restore() def draw_image(self, x, y, im, bbox, clippath=None, clippath_trans=None): # bbox - not currently used @@ -180,7 +161,7 @@ surface = cairo.ImageSurface.create_for_data ( buf, cairo.FORMAT_ARGB32, cols, rows, cols*4) # function does not pass a 'gc' so use renderer.ctx - ctx = self.ctx + ctx = self.gc.ctx ctx.save() if clippath is not None: ctx.new_path() @@ -297,9 +278,8 @@ def new_gc(self): if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name()) - self.ctx.restore() # matches save() in set_ctx_from_surface() - self.ctx.save() - return GraphicsContextCairo (renderer=self) + self.gc.ctx.save() + return self.gc def points_to_pixels(self, points): @@ -324,9 +304,12 @@ def __init__(self, renderer): GraphicsContextBase.__init__(self) self.renderer = renderer - self.ctx = renderer.ctx + def restore(self): + self.ctx.restore() + + def set_alpha(self, alpha): self._alpha = alpha rgb = self._rgb @@ -346,10 +329,23 @@ def set_clip_rectangle(self, rectangle): - self._cliprect = rectangle + if not rectangle: return + x,y,w,h = rectangle.bounds + # pixel-aligned clip-regions are faster + x,y,w,h = round(x), round(y), round(w), round(h) + ctx = self.ctx + ctx.new_path() + ctx.rectangle (x, self.renderer.height - h - y, w, h) + ctx.clip () def set_clip_path(self, path): - self._clippath = path + if not path: return + tpath, affine = path.get_transformed_path_and_affine() + ctx = self.ctx + ctx.new_path() + affine = affine + Affine2D().scale(1.0, -1.0).translate(0.0, self.renderer.height) + RendererCairo.convert_path(ctx, tpath, affine) + ctx.clip() def set_dashes(self, offset, dashes): self._dashes = offset, dashes @@ -468,7 +464,7 @@ renderer = RendererCairo (self.figure.dpi) renderer.set_width_height (width_in_points, height_in_points) renderer.set_ctx_from_surface (surface) - ctx = renderer.ctx + ctx = renderer.gc.ctx if orientation == 'landscape': ctx.rotate (npy.pi/2) Modified: trunk/matplotlib/lib/matplotlib/backends/backend_gtkcairo.py =================================================================== --- trunk/matplotlib/lib/matplotlib/backends/backend_gtkcairo.py 2009-05-17 14:54:57 UTC (rev 7111) +++ trunk/matplotlib/lib/matplotlib/backends/backend_gtkcairo.py 2009-05-17 15:08:07 UTC (rev 7112) @@ -31,12 +31,10 @@ class RendererGTKCairo (backend_cairo.RendererCairo): if gtk.pygtk_version >= (2,7,0): def set_pixmap (self, pixmap): - self.ctx = pixmap.cairo_create() - self.ctx.save() # restore, save - when call new_gc() + self.gc.ctx = pixmap.cairo_create() else: def set_pixmap (self, pixmap): - self.ctx = cairo.gtk.gdk_cairo_create (pixmap) - self.ctx.save() # restore, save - when call new_gc() + self.gc.ctx = cairo.gtk.gdk_cairo_create (pixmap) class FigureCanvasGTKCairo(backend_cairo.FigureCanvasCairo, FigureCanvasGTK): Modified: trunk/matplotlib/lib/matplotlib/backends/backend_macosx.py =================================================================== --- trunk/matplotlib/lib/matplotlib/backends/backend_macosx.py 2009-05-17 14:54:57 UTC (rev 7111) +++ trunk/matplotlib/lib/matplotlib/backends/backend_macosx.py 2009-05-17 15:08:07 UTC (rev 7112) @@ -51,19 +51,11 @@ def draw_path(self, gc, path, transform, rgbFace=None): if rgbFace is not None: rgbFace = tuple(rgbFace) - if gc!=self.gc: - n = self.gc.level() - gc.level() - for i in range(n): self.gc.restore() - self.gc = gc gc.draw_path(path, transform, rgbFace) def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None): if rgbFace is not None: rgbFace = tuple(rgbFace) - if gc!=self.gc: - n = self.gc.level() - gc.level() - for i in range(n): self.gc.restore() - self.gc = gc gc.draw_markers(marker_path, marker_trans, path, trans, rgbFace) def draw_path_collection(self, *args): @@ -76,7 +68,7 @@ gc.draw_quad_mesh(*args) def new_gc(self): - self.gc.reset() + self.gc.save() self.gc.set_hatch(None) return self.gc @@ -87,10 +79,6 @@ im.flipud_out() def draw_tex(self, gc, x, y, s, prop, angle): - if gc!=self.gc: - n = self.gc.level() - gc.level() - for i in range(n): self.gc.restore() - self.gc = gc # todo, handle props, angle, origins size = prop.get_size_in_points() texmanager = self.get_texmanager() @@ -103,19 +91,11 @@ gc.draw_mathtext(x, y, angle, Z) def _draw_mathtext(self, gc, x, y, s, prop, angle): - if gc!=self.gc: - n = self.gc.level() - gc.level() - for i in range(n): self.gc.restore() - self.gc = gc ox, oy, width, height, descent, image, used_characters = \ self.mathtext_parser.parse(s, self.dpi, prop) gc.draw_mathtext(x, y, angle, 255 - image.as_array()) def draw_text(self, gc, x, y, s, prop, angle, ismath=False): - if gc!=self.gc: - n = self.gc.level() - gc.level() - for i in range(n): self.gc.restore() - self.gc = gc if ismath: self._draw_mathtext(gc, x, y, s, prop, angle) else: Modified: trunk/matplotlib/lib/matplotlib/lines.py =================================================================== --- trunk/matplotlib/lib/matplotlib/lines.py 2009-05-17 14:54:57 UTC (rev 7111) +++ trunk/matplotlib/lib/matplotlib/lines.py 2009-05-17 15:08:07 UTC (rev 7112) @@ -540,7 +540,9 @@ markerFunc = getattr(self, funcname) markerFunc(renderer, gc, subsampled, affine.frozen()) + gc.restore() + gc.restore() renderer.close_group('line2d') def get_antialiased(self): return self._antialiased Modified: trunk/matplotlib/lib/matplotlib/patches.py =================================================================== --- trunk/matplotlib/lib/matplotlib/patches.py 2009-05-17 14:54:57 UTC (rev 7111) +++ trunk/matplotlib/lib/matplotlib/patches.py 2009-05-17 15:08:07 UTC (rev 7112) @@ -302,6 +302,7 @@ renderer.draw_path(gc, tpath, affine, rgbFace) + gc.restore() renderer.close_group('patch') def get_path(self): @@ -3705,4 +3706,5 @@ renderer.draw_path(gc, p, affine, None) + gc.restore() renderer.close_group('patch') Modified: trunk/matplotlib/lib/matplotlib/text.py =================================================================== --- trunk/matplotlib/lib/matplotlib/text.py 2009-05-17 14:54:57 UTC (rev 7111) +++ trunk/matplotlib/lib/matplotlib/text.py 2009-05-17 15:08:07 UTC (rev 7112) @@ -507,6 +507,7 @@ self._fontproperties, angle, ismath=ismath) + gc.restore() renderer.close_group('text') def get_color(self): Modified: trunk/matplotlib/lib/mpl_toolkits/axes_grid/axislines.py =================================================================== --- trunk/matplotlib/lib/mpl_toolkits/axes_grid/axislines.py 2009-05-17 14:54:57 UTC (rev 7111) +++ trunk/matplotlib/lib/mpl_toolkits/axes_grid/axislines.py 2009-05-17 15:08:07 UTC (rev 7112) @@ -65,6 +65,7 @@ lineFunc = getattr(self, funcname) lineFunc(renderer, gc, tpath, affine.frozen()) + gc.restore() renderer.close_group('line2d') @@ -548,6 +549,7 @@ renderer.draw_markers(gc, self._tickvert_path, marker_transform, Path(locs), path_trans.get_affine()) + gc.restore() Modified: trunk/matplotlib/src/_macosx.m =================================================================== --- trunk/matplotlib/src/_macosx.m 2009-05-17 14:54:57 UTC (rev 7111) +++ trunk/matplotlib/src/_macosx.m 2009-05-17 15:08:07 UTC (rev 7112) @@ -374,6 +374,7 @@ PyObject_HEAD CGContextRef cr; NSSize size; + int level; } GraphicsContext; static CGMutablePathRef _create_path(void* iterator) @@ -437,6 +438,7 @@ GraphicsContext* self = (GraphicsContext*)type->tp_alloc(type, 0); if (!self) return NULL; self->cr = NULL; + self->level = 0; if (ngc==0) { @@ -467,7 +469,7 @@ } static PyObject* -GraphicsContext_reset (GraphicsContext* self) +GraphicsContext_save (GraphicsContext* self) { CGContextRef cr = self->cr; if (!cr) @@ -475,9 +477,29 @@ PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); return NULL; } + CGContextSaveGState(cr); + self->level++; + Py_INCREF(Py_None); + return Py_None; +} +static PyObject* +GraphicsContext_restore (GraphicsContext* self) +{ + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + if (self->level==0) + { + PyErr_SetString(PyExc_RuntimeError, + "Attempting to execute CGContextRestoreGState on an empty stack"); + return NULL; + } CGContextRestoreGState(cr); - CGContextSaveGState(cr); + self->level--; Py_INCREF(Py_None); return Py_None; } @@ -1543,11 +1565,15 @@ const double b = *(double*)PyArray_GETPTR2(facecolors, fi, 2); const double a = *(double*)PyArray_GETPTR2(facecolors, fi, 3); CGContextSetRGBFillColor(cr, r, g, b, a); - CGContextDrawPath(cr, kCGPathFillStroke); + if (Nedgecolors > 0) CGContextDrawPath(cr, kCGPathFillStroke); + else CGContextFillPath(cr); } else if (Nfacecolors==1) - CGContextDrawPath(cr, kCGPathFillStroke); - else + { + if (Nedgecolors > 0) CGContextDrawPath(cr, kCGPathFillStroke); + else CGContextFillPath(cr); + } + else /* We checked Nedgecolors != 0 above */ CGContextStrokePath(cr); CGContextRestoreGState(cr); } @@ -2480,11 +2506,16 @@ static PyMethodDef GraphicsContext_methods[] = { - {"reset", - (PyCFunction)GraphicsContext_reset, + {"save", + (PyCFunction)GraphicsContext_save, METH_NOARGS, - "Resets the current graphics context by restoring it from the stack and copying it back onto the stack." + "Saves the current graphics context onto the stack." }, + {"restore", + (PyCFunction)GraphicsContext_restore, + METH_NOARGS, + "Restores the current graphics context from the stack." + }, {"get_text_width_height_descent", (PyCFunction)GraphicsContext_get_text_width_height_descent, METH_VARARGS, @@ -4293,17 +4324,14 @@ CGContextRef cr = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort]; gc->cr = cr; + gc->level = 0; - CGContextSaveGState(cr); - CGContextSetTextMatrix(cr, CGAffineTransformIdentity); - result = PyObject_CallMethod(figure, "draw", "O", renderer); if(result) Py_DECREF(result); else PyErr_Print(); - CGContextRestoreGState(cr); gc->cr = nil; if (!NSIsEmptyRect(rubberband)) NSFrameRect(rubberband); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2009-05-17 18:00:11
|
Revision: 7113 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7113&view=rev Author: jdh2358 Date: 2009-05-17 18:00:10 +0000 (Sun, 17 May 2009) Log Message: ----------- applied Michiel's sf patch 2790638 to turn off gtk event for setupext Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/setupext.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-05-17 15:08:07 UTC (rev 7112) +++ trunk/matplotlib/CHANGELOG 2009-05-17 18:00:10 UTC (rev 7113) @@ -1,6 +1,10 @@ -2009-05-19 applied Michiel's sf patch 2792742 to speed up Cairo and - macosx collections; speedups can be 20x +2009-05-17 applied Michiel's sf patch 2790638 to turn off gtk event + loop in setupext for pygtk>=2.15.10 - JDH +2009-05-17 applied Michiel's sf patch 2792742 to speed up Cairo and + macosx collections; speedups can be 20x. Also fixes some + bugs in which gc got into inconsistent state + ====================================================================== 2008-05-17 Release 0.98.5.3 at r7107 from the branch - JDH Modified: trunk/matplotlib/setupext.py =================================================================== --- trunk/matplotlib/setupext.py 2009-05-17 15:08:07 UTC (rev 7112) +++ trunk/matplotlib/setupext.py 2009-05-17 18:00:10 UTC (rev 7113) @@ -595,6 +595,13 @@ if explanation is not None: print_message(explanation) + # Switch off the event loop for PyGTK >= 2.15.0 + if gotit: + try: + gtk.set_interactive(False) + except AttributeError: # PyGTK < 2.15.0 + pass + return gotit def add_pygtk_flags(module): @@ -842,6 +849,7 @@ tk.withdraw() tcl_lib_dir = str(tk.getvar('tcl_library')) tk_lib_dir = str(tk.getvar('tk_library')) + tk.destroy() # Save directories and version string to cache TCL_TK_CACHE = tcl_lib_dir, tk_lib_dir, str(Tkinter.TkVersion)[:3] This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lee...@us...> - 2009-05-17 22:13:30
|
Revision: 7116 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7116&view=rev Author: leejjoon Date: 2009-05-17 22:13:22 +0000 (Sun, 17 May 2009) Log Message: ----------- Merged revisions 7115 via svnmerge from https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/v0_98_5_maint ........ r7115 | leejjoon | 2009-05-17 18:04:38 -0400 (Sun, 17 May 2009) | 2 lines Fix bug(#2749174) that some properties of minor ticks are not conserved. ........ Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/axis.py Property Changed: ---------------- trunk/matplotlib/ Property changes on: trunk/matplotlib ___________________________________________________________________ Modified: svnmerge-integrated - /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-7110 + /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-7115 Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-05-17 22:04:38 UTC (rev 7115) +++ trunk/matplotlib/CHANGELOG 2009-05-17 22:13:22 UTC (rev 7116) @@ -1,3 +1,6 @@ +2009-05-17 Fix bug(#2749174) that some properties of minor ticks are + not conserved -JJL + 2009-05-17 applied Michiel's sf patch 2790638 to turn off gtk event loop in setupext for pygtk>=2.15.10 - JDH Modified: trunk/matplotlib/lib/matplotlib/axis.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axis.py 2009-05-17 22:04:38 UTC (rev 7115) +++ trunk/matplotlib/lib/matplotlib/axis.py 2009-05-17 22:13:22 UTC (rev 7116) @@ -1325,8 +1325,12 @@ assert position in ('top', 'bottom', 'both', 'default', 'none') - ticks = list( self.get_major_ticks() ) # a copy - ticks.extend( self.get_minor_ticks() ) + # The first ticks of major & minor ticks should always be + # included, otherwise, the information can be lost. Thus, use + # majorTicks instead of get_major_ticks() which may return + # empty list. + ticks = list( self.majorTicks ) # a copy + ticks.extend( self.minorTicks ) if position == 'top': for t in ticks: @@ -1566,8 +1570,12 @@ """ assert position in ('left', 'right', 'both', 'default', 'none') - ticks = list( self.get_major_ticks() ) # a copy - ticks.extend( self.get_minor_ticks() ) + # The first ticks of major & minor ticks should always be + # included, otherwise, the information can be lost. Thus, use + # majorTicks instead of get_major_ticks() which may return + # empty list. + ticks = list( self.majorTicks ) # a copy + ticks.extend( self.minorTicks ) if position == 'right': self.set_offset_position('right') This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lee...@us...> - 2009-05-18 17:25:55
|
Revision: 7119 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7119&view=rev Author: leejjoon Date: 2009-05-18 17:25:46 +0000 (Mon, 18 May 2009) Log Message: ----------- Add *annotation_clip* attr. for text.Annotation class Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/axes.py trunk/matplotlib/lib/matplotlib/patches.py trunk/matplotlib/lib/matplotlib/text.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-05-18 01:11:49 UTC (rev 7118) +++ trunk/matplotlib/CHANGELOG 2009-05-18 17:25:46 UTC (rev 7119) @@ -1,3 +1,7 @@ +2009-05-18 Add *annotation_clip* attr. for text.Annotation class. + If True, annotation is only drawn when the annotated point is + inside the axes area. -JJL + 2009-05-17 Fix bug(#2749174) that some properties of minor ticks are not conserved -JJL Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2009-05-18 01:11:49 UTC (rev 7118) +++ trunk/matplotlib/lib/matplotlib/axes.py 2009-05-18 17:25:46 UTC (rev 7119) @@ -2657,6 +2657,15 @@ return self.patch.contains(mouseevent) + def contains_point(self, point): + """ + Returns True if the point (tuple of x,y) is inside the axes + (the area defined by the its patch). A pixel coordinate is + required. + + """ + return self.patch.contains_point(point) + def pick(self, *args): """ call signature:: Modified: trunk/matplotlib/lib/matplotlib/patches.py =================================================================== --- trunk/matplotlib/lib/matplotlib/patches.py 2009-05-18 01:11:49 UTC (rev 7118) +++ trunk/matplotlib/lib/matplotlib/patches.py 2009-05-18 17:25:46 UTC (rev 7119) @@ -81,6 +81,14 @@ (mouseevent.x, mouseevent.y), self.get_transform()) return inside, {} + def contains_point(self, point): + """ + Returns *True* if the given point is inside the path + (transformed with its transform attribute). + """ + return self.get_path().contains_point(point, + self.get_transform()) + def update_from(self, other): """ Updates this :class:`Patch` from the properties of *other*. Modified: trunk/matplotlib/lib/matplotlib/text.py =================================================================== --- trunk/matplotlib/lib/matplotlib/text.py 2009-05-18 01:11:49 UTC (rev 7118) +++ trunk/matplotlib/lib/matplotlib/text.py 2009-05-18 17:25:46 UTC (rev 7119) @@ -1408,6 +1408,8 @@ else: self.arrow_patch = None + # if True, draw annotation only if self.xy is inside the axes + self._annotation_clip = None __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd @@ -1525,15 +1527,44 @@ trans = self.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 update_positions(self, renderer): + "Update the pixel positions of the annotated point and the text." + xy_pixel = self._get_position_xy(renderer) + self._update_position_xytext(renderer, xy_pixel) + + def _get_position_xy(self, renderer): + "Return the pixel position of the the annotated point." + x, y = self.xy + return self._get_xy(x, y, self.xycoords) + + + def _update_position_xytext(self, renderer, xy_pixel): + "Update the pixel positions of the annotation text and the arrow patch." + x, y = self.xytext self._x, self._y = self._get_xy(x, y, self.textcoords) - x, y = self.xy - x, y = self._get_xy(x, y, self.xycoords) + x, y = xy_pixel ox0, oy0 = self._x, self._y ox1, oy1 = x, y @@ -1609,6 +1640,22 @@ self.arrow.set_clip_box(self.get_clip_box()) + + def _check_xy(self, renderer, xy_pixel): + """ + given the xy pixel coordinate, check if the annotation need to + be drawn. + """ + + b = self.get_annotation_clip() + if b or (b is None and self.xycoords == "data"): + # check if self.xy is inside the axes. + if not self.axes.contains_point(xy_pixel): + return False + + return True + + def draw(self, renderer): """ Draw the :class:`Annotation` object to the given *renderer*. @@ -1618,7 +1665,13 @@ self._renderer = renderer if not self.get_visible(): return - self.update_positions(renderer) + xy_pixel = self._get_position_xy(renderer) + + if not self._check_xy(renderer, xy_pixel): + return + + self._update_position_xytext(renderer, xy_pixel) + self.update_bbox_position_size(renderer) if self.arrow is not None: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lee...@us...> - 2009-05-18 19:19:43
|
Revision: 7120 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7120&view=rev Author: leejjoon Date: 2009-05-18 19:19:33 +0000 (Mon, 18 May 2009) Log Message: ----------- Fix the linespacing bug of multiline text (#1239682) Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/examples/pylab_examples/multiline.py trunk/matplotlib/lib/matplotlib/text.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-05-18 17:25:46 UTC (rev 7119) +++ trunk/matplotlib/CHANGELOG 2009-05-18 19:19:33 UTC (rev 7120) @@ -1,3 +1,6 @@ +2009-05-18 Fix the linespacing bug of multiline text (#1239682). See + examples/pylab_examples/multiline.py -JJL + 2009-05-18 Add *annotation_clip* attr. for text.Annotation class. If True, annotation is only drawn when the annotated point is inside the axes area. -JJL Modified: trunk/matplotlib/examples/pylab_examples/multiline.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/multiline.py 2009-05-18 17:25:46 UTC (rev 7119) +++ trunk/matplotlib/examples/pylab_examples/multiline.py 2009-05-18 19:19:33 UTC (rev 7120) @@ -1,15 +1,46 @@ #!/usr/bin/env python from pylab import * +#from matplotlib.pyplot import * +#from numpy import arange -plot(arange(10)) -xlabel('this is a xlabel\n(with newlines!)') -ylabel('this is vertical\ntest', multialignment='center') -#ylabel('this is another!') -text(2, 7,'this is\nyet another test', - rotation=45, - horizontalalignment = 'center', - verticalalignment = 'top', - multialignment = 'center') +if 1: + figure(figsize=(7, 4)) + ax = subplot(121) + ax.set_aspect(1) + plot(arange(10)) + xlabel('this is a xlabel\n(with newlines!)') + ylabel('this is vertical\ntest', multialignment='center') + #ylabel('this is another!') + text(2, 7,'this is\nyet another test', + rotation=45, + horizontalalignment = 'center', + verticalalignment = 'top', + multialignment = 'center') -grid(True) + grid(True) + + + + subplot(122) + + text(0.29, 0.7, "Mat\nTTp\n123", size=18, + va="baseline", ha="right", multialignment="left", + bbox=dict(fc="none")) + + text(0.34, 0.7, "Mag\nTTT\n123", size=18, + va="baseline", ha="left", multialignment="left", + bbox=dict(fc="none")) + + text(0.95, 0.7, "Mag\nTTT$^{A^A}$\n123", size=18, + va="baseline", ha="right", multialignment="left", + bbox=dict(fc="none")) + + xticks([0.2, 0.4, 0.6, 0.8, 1.], + ["Jan\n2009","Feb\n2009","Mar\n2009", "Apr\n2009", "May\n2009"]) + + axhline(0.7) + title("test line spacing for multiline text") + +subplots_adjust(bottom=0.25, top=0.8) +draw() show() Modified: trunk/matplotlib/lib/matplotlib/text.py =================================================================== --- trunk/matplotlib/lib/matplotlib/text.py 2009-05-18 17:25:46 UTC (rev 7119) +++ trunk/matplotlib/lib/matplotlib/text.py 2009-05-18 19:19:33 UTC (rev 7120) @@ -8,15 +8,15 @@ from matplotlib import cbook from matplotlib import rcParams -import artist -from artist import Artist -from cbook import is_string_like, maxdict -from font_manager import FontProperties -from patches import bbox_artist, YAArrow, FancyBboxPatch, \ +import matplotlib.artist as artist +from matplotlib.artist import Artist +from matplotlib.cbook import is_string_like, maxdict +from matplotlib.font_manager import FontProperties +from matplotlib.patches import bbox_artist, YAArrow, FancyBboxPatch, \ FancyArrowPatch, Rectangle -import transforms as mtransforms -from transforms import Affine2D, Bbox -from lines import Line2D +import matplotlib.transforms as mtransforms +from matplotlib.transforms import Affine2D, Bbox +from matplotlib.lines import Line2D import matplotlib.nxutils as nxutils @@ -227,6 +227,11 @@ self._linespacing = other._linespacing def _get_layout(self, renderer): + """ + return the extent (bbox) of the text together with + multile-alignment information. Note that it returns a extent + of a rotated text when necessary. + """ key = self.get_prop_tup() if key in self.cached: return self.cached[key] @@ -242,9 +247,9 @@ # Find full vertical extent of font, # including ascenders and descenders: - tmp, heightt, bl = renderer.get_text_width_height_descent( + tmp, lp_h, lp_bl = renderer.get_text_width_height_descent( 'lp', self._fontproperties, ismath=False) - offsety = heightt * self._linespacing + offsety = lp_h * self._linespacing baseline = None for i, line in enumerate(lines): @@ -254,8 +259,22 @@ if baseline is None: baseline = h - d whs[i] = w, h - horizLayout[i] = thisx, thisy, w, h - thisy -= offsety + + # For general multiline text, we will have a fixed spacing + # between the "baseline" of the upper line and "top" of + # the lower line (instead of the "bottom" of the upper + # line and "top" of the lower line) + + # For multiline text, increase the line spacing when the + # text net-height(excluding baseline) is larger than that + # of a "l" (e.g., use of superscripts), which seems + # what TeX does. + + d_yoffset = max(0, (h-d)-(lp_h-lp_bl)) + + horizLayout[i] = thisx, thisy-(d + d_yoffset), \ + w, h + thisy -= offsety + d_yoffset width = max(width, w) ymin = horizLayout[-1][1] @@ -1688,3 +1707,4 @@ artist.kwdocd['Annotation'] = Annotation.__init__.__doc__ + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ry...@us...> - 2009-05-18 20:50:27
|
Revision: 7121 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7121&view=rev Author: ryanmay Date: 2009-05-18 20:50:20 +0000 (Mon, 18 May 2009) Log Message: ----------- Move code for wrapping negative frequencies from specgram() into _spectral_helper(), so that psd(), csd(), and cohere() can benefit from this functionality as well. While this changes API a little, this is much more sensible behavior. Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/doc/api/api_changes.rst trunk/matplotlib/lib/matplotlib/mlab.py Added Paths: ----------- trunk/matplotlib/examples/pylab_examples/psd_demo_complex.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-05-18 19:19:33 UTC (rev 7120) +++ trunk/matplotlib/CHANGELOG 2009-05-18 20:50:20 UTC (rev 7121) @@ -1,4 +1,7 @@ -2009-05-18 Fix the linespacing bug of multiline text (#1239682). See +2009-05-18 Make psd(), csd(), and cohere() wrap properly for complex/two-sided + versions, like specgram() (SF #2791686) - RMM + +2009-05-18 Fix the linespacing bug of multiline text (#1239682). See examples/pylab_examples/multiline.py -JJL 2009-05-18 Add *annotation_clip* attr. for text.Annotation class. Modified: trunk/matplotlib/doc/api/api_changes.rst =================================================================== --- trunk/matplotlib/doc/api/api_changes.rst 2009-05-18 19:19:33 UTC (rev 7120) +++ trunk/matplotlib/doc/api/api_changes.rst 2009-05-18 20:50:20 UTC (rev 7121) @@ -19,6 +19,12 @@ Changes for 0.98.x ================== +* psd(), csd(), and cohere() will now automatically wrap negative + frequency components to the beginning of the returned arrays. + This is much more sensible behavior and makes them consistent + with specgram(). The previous behavior was more of an oversight + than a design decision. + * Added new keyword parameters *nonposx*, *nonposy* to :class:`matplotlib.axes.Axes` methods that set log scale parameters. The default is still to mask out non-positive Added: trunk/matplotlib/examples/pylab_examples/psd_demo_complex.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/psd_demo_complex.py (rev 0) +++ trunk/matplotlib/examples/pylab_examples/psd_demo_complex.py 2009-05-18 20:50:20 UTC (rev 7121) @@ -0,0 +1,38 @@ +#This is a ported version of a Matlab example from the signal processing +#toolbox that showed some difference at one time between Matplotlib's and +#MatLab's scaling of the PSD. This differs from psd_demo3.py in that +#this uses a complex signal, so we can see that complex PSD's work properly +import numpy as np +import matplotlib.pyplot as plt +import matplotlib.mlab as mlab + +fs = 1000 +t = np.linspace(0, 0.3, 301) +A = np.array([2, 8]).reshape(-1, 1) +f = np.array([150, 140]).reshape(-1, 1) +xn = (A * np.exp(2j * np.pi * f * t)).sum(axis=0) + 5 * np.random.randn(*t.shape) + +yticks = np.arange(-50, 30, 10) +xticks = np.arange(-500,550,100) +plt.subplots_adjust(hspace=0.45, wspace=0.3) +ax = plt.subplot(1, 2, 1) + +plt.psd(xn, NFFT=301, Fs=fs, window=mlab.window_none, pad_to=1024, + scale_by_freq=True) +plt.title('Periodogram') +plt.yticks(yticks) +plt.xticks(xticks) +plt.grid(True) +plt.xlim(-500, 500) + +plt.subplot(1, 2, 2, sharex=ax, sharey=ax) +plt.psd(xn, NFFT=150, Fs=fs, window=mlab.window_none, noverlap=75, pad_to=512, + scale_by_freq=True) +plt.title('Welch') +plt.xticks(xticks) +plt.yticks(yticks) +plt.ylabel('') +plt.grid(True) +plt.xlim(-500, 500) + +plt.show() Modified: trunk/matplotlib/lib/matplotlib/mlab.py =================================================================== --- trunk/matplotlib/lib/matplotlib/mlab.py 2009-05-18 19:19:33 UTC (rev 7120) +++ trunk/matplotlib/lib/matplotlib/mlab.py 2009-05-18 20:50:20 UTC (rev 7121) @@ -327,6 +327,11 @@ t = 1./Fs * (ind + NFFT / 2.) freqs = float(Fs) / pad_to * np.arange(numFreqs) + if (np.iscomplexobj(x) and sides == 'default') or sides == 'twosided': + # center the frequency range at zero + freqs = np.concatenate((freqs[numFreqs//2:] - Fs, freqs[:numFreqs//2])) + Pxy = np.concatenate((Pxy[numFreqs//2:, :], Pxy[:numFreqs//2, :]), 0) + return Pxy, freqs, t #Split out these keyword docs so that they can be used elsewhere @@ -485,11 +490,6 @@ noverlap, pad_to, sides, scale_by_freq) Pxx = Pxx.real #Needed since helper implements generically - if (np.iscomplexobj(x) and sides == 'default') or sides == 'twosided': - # center the frequency range at zero - freqs = np.concatenate((freqs[NFFT/2:]-Fs,freqs[:NFFT/2])) - Pxx = np.concatenate((Pxx[NFFT/2:,:],Pxx[:NFFT/2,:]),0) - return Pxx, freqs, t specgram.__doc__ = specgram.__doc__ % kwdocd This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <as...@us...> - 2009-05-19 21:29:35
|
Revision: 7123 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7123&view=rev Author: astraw Date: 2009-05-19 21:29:29 +0000 (Tue, 19 May 2009) Log Message: ----------- Axis.grid(): allow use of which='major,minor' to have grid on major and minor ticks Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/axis.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-05-19 21:29:19 UTC (rev 7122) +++ trunk/matplotlib/CHANGELOG 2009-05-19 21:29:29 UTC (rev 7123) @@ -1,3 +1,6 @@ +2009-05-19 Axis.grid(): allow use of which='major,minor' to have grid + on major and minor ticks. -ADS + 2009-05-18 Make psd(), csd(), and cohere() wrap properly for complex/two-sided versions, like specgram() (SF #2791686) - RMM Modified: trunk/matplotlib/lib/matplotlib/axis.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axis.py 2009-05-19 21:29:19 UTC (rev 7122) +++ trunk/matplotlib/lib/matplotlib/axis.py 2009-05-19 21:29:29 UTC (rev 7123) @@ -953,7 +953,7 @@ if tick is None: continue tick.gridOn = self._gridOnMinor if len(kwargs): artist.setp(tick.gridline,**kwargs) - else: + if which.lower().find('major')>=0: if b is None: self._gridOnMajor = not self._gridOnMajor else: self._gridOnMajor = b for tick in self.majorTicks: # don't use get_ticks here! This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <as...@us...> - 2009-05-19 22:26:41
|
Revision: 7126 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7126&view=rev Author: astraw Date: 2009-05-19 22:26:33 +0000 (Tue, 19 May 2009) Log Message: ----------- support collective.buildbot by enabling buildout support Added Paths: ----------- trunk/matplotlib/bootstrap.py trunk/matplotlib/buildout.cfg Added: trunk/matplotlib/bootstrap.py =================================================================== --- trunk/matplotlib/bootstrap.py (rev 0) +++ trunk/matplotlib/bootstrap.py 2009-05-19 22:26:33 UTC (rev 7126) @@ -0,0 +1,52 @@ +############################################################################## +# +# Copyright (c) 2006 Zope Corporation and Contributors. +# All Rights Reserved. +# +# This software is subject to the provisions of the Zope Public License, +# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. +# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED +# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS +# FOR A PARTICULAR PURPOSE. +# +############################################################################## +"""Bootstrap a buildout-based project + +Simply run this script in a directory containing a buildout.cfg. +The script accepts buildout command-line options, so you can +use the -c option to specify an alternate configuration file. + +$Id$ +""" + +import os, shutil, sys, tempfile, urllib2 + +tmpeggs = tempfile.mkdtemp() + +ez = {} +exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' + ).read() in ez +ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) + +import pkg_resources + +cmd = 'from setuptools.command.easy_install import main; main()' +if sys.platform == 'win32': + cmd = '"%s"' % cmd # work around spawn lamosity on windows + +ws = pkg_resources.working_set +assert os.spawnle( + os.P_WAIT, sys.executable, sys.executable, + '-c', cmd, '-mqNxd', tmpeggs, 'zc.buildout', + dict(os.environ, + PYTHONPATH= + ws.find(pkg_resources.Requirement.parse('setuptools')).location + ), + ) == 0 + +ws.add_entry(tmpeggs) +ws.require('zc.buildout') +import zc.buildout.buildout +zc.buildout.buildout.main(sys.argv[1:] + ['bootstrap']) +shutil.rmtree(tmpeggs) Added: trunk/matplotlib/buildout.cfg =================================================================== --- trunk/matplotlib/buildout.cfg (rev 0) +++ trunk/matplotlib/buildout.cfg 2009-05-19 22:26:33 UTC (rev 7126) @@ -0,0 +1,17 @@ +[buildout] +parts = test python +develop = . +eggs = matplotlib + +[test] +recipe = pbp.recipe.noserunner +eggs = + pbp.recipe.noserunner + ${buildout:eggs} +working-directory = ${buildout:directory} + +[python] +recipe = zc.recipe.egg +interpreter = python +eggs = + ${buildout:eggs} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ry...@us...> - 2009-05-20 20:54:48
|
Revision: 7127 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7127&view=rev Author: ryanmay Date: 2009-05-20 20:54:33 +0000 (Wed, 20 May 2009) Log Message: ----------- Add an empty matplotlibrc to the tests/ directory so that running the test suite uses the default matplotlib config. Modified Paths: -------------- trunk/matplotlib/CHANGELOG Added Paths: ----------- trunk/matplotlib/test/matplotlibrc Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-05-19 22:26:33 UTC (rev 7126) +++ trunk/matplotlib/CHANGELOG 2009-05-20 20:54:33 UTC (rev 7127) @@ -1,3 +1,7 @@ +2009-05-20 Add an empty matplotlibrc to the tests/ directory so that running + tests will use the default set of rcparams rather than the user's + config. - RMM + 2009-05-19 Axis.grid(): allow use of which='major,minor' to have grid on major and minor ticks. -ADS Added: trunk/matplotlib/test/matplotlibrc =================================================================== --- trunk/matplotlib/test/matplotlibrc (rev 0) +++ trunk/matplotlib/test/matplotlibrc 2009-05-20 20:54:33 UTC (rev 7127) @@ -0,0 +1,3 @@ +#This is an empty matplotlibrc so that the tests use the +#matplotlib default config and not the user's config. This keeps +#settings like font sizes from causing the image comparison tests to fail. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2009-05-22 14:01:23
|
Revision: 7131 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7131&view=rev Author: mdboom Date: 2009-05-22 14:00:12 +0000 (Fri, 22 May 2009) Log Message: ----------- Fix problem with polar grid lines by specifying the number of interpolation steps on a per-Path basis. This isn't really a public API -- it is intended for internal use only. Modified Paths: -------------- trunk/matplotlib/doc/api/api_changes.rst trunk/matplotlib/examples/api/custom_projection_example.py trunk/matplotlib/examples/pylab_examples/polar_bar.py trunk/matplotlib/lib/matplotlib/axis.py trunk/matplotlib/lib/matplotlib/cbook.py trunk/matplotlib/lib/matplotlib/lines.py trunk/matplotlib/lib/matplotlib/path.py trunk/matplotlib/lib/matplotlib/projections/polar.py trunk/matplotlib/lib/matplotlib/transforms.py Modified: trunk/matplotlib/doc/api/api_changes.rst =================================================================== --- trunk/matplotlib/doc/api/api_changes.rst 2009-05-21 21:06:49 UTC (rev 7130) +++ trunk/matplotlib/doc/api/api_changes.rst 2009-05-22 14:00:12 UTC (rev 7131) @@ -17,6 +17,14 @@ .. _configobj: http://www.voidspace.org.uk/python/configobj.html .. _`enthought.traits`: http://code.enthought.com/projects/traits +Changes beyond 0.98.x +===================== + +* Polar plots no longer accept a resolution kwarg. Instead, each Path + must specify its own number of interpolation steps. This is + unlikely to be a user-visible change -- if interpolation of data is + required, that should be done before passing it to matplotlib. + Changes for 0.98.x ================== * psd(), csd(), and cohere() will now automatically wrap negative Modified: trunk/matplotlib/examples/api/custom_projection_example.py =================================================================== --- trunk/matplotlib/examples/api/custom_projection_example.py 2009-05-21 21:06:49 UTC (rev 7130) +++ trunk/matplotlib/examples/api/custom_projection_example.py 2009-05-22 14:00:12 UTC (rev 7131) @@ -373,15 +373,6 @@ output_dims = 2 is_separable = False - def __init__(self, resolution): - """ - Create a new Hammer transform. Resolution is the number of steps - to interpolate between each input line segment to approximate its - path in curved Hammer space. - """ - Transform.__init__(self) - self._resolution = resolution - def transform(self, ll): """ Override the transform method to implement the custom transform. @@ -410,11 +401,11 @@ # ``transform_path``. def transform_path(self, path): vertices = path.vertices - ipath = path.interpolated(self._resolution) + ipath = path.interpolated(path._interpolation_steps) return Path(self.transform(ipath.vertices), ipath.codes) def inverted(self): - return HammerAxes.InvertedHammerTransform(self._resolution) + return HammerAxes.InvertedHammerTransform() inverted.__doc__ = Transform.inverted.__doc__ class InvertedHammerTransform(Transform): @@ -422,10 +413,6 @@ output_dims = 2 is_separable = False - def __init__(self, resolution): - Transform.__init__(self) - self._resolution = resolution - def transform(self, xy): x = xy[:, 0:1] y = xy[:, 1:2] @@ -440,7 +427,7 @@ def inverted(self): # The inverse of the inverse is the original transform... ;) - return HammerAxes.HammerTransform(self._resolution) + return HammerAxes.HammerTransform() inverted.__doc__ = Transform.inverted.__doc__ # Now register the projection with matplotlib so the user can select Modified: trunk/matplotlib/examples/pylab_examples/polar_bar.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/polar_bar.py 2009-05-21 21:06:49 UTC (rev 7130) +++ trunk/matplotlib/examples/pylab_examples/polar_bar.py 2009-05-22 14:00:12 UTC (rev 7131) @@ -7,7 +7,7 @@ # force square figure and square axes looks better for polar, IMO fig = figure(figsize=(8,8)) -ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True, resolution=50) +ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True) N = 20 theta = np.arange(0.0, 2*np.pi, 2*np.pi/N) Modified: trunk/matplotlib/lib/matplotlib/axis.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axis.py 2009-05-21 21:06:49 UTC (rev 7130) +++ trunk/matplotlib/lib/matplotlib/axis.py 2009-05-22 14:00:12 UTC (rev 7131) @@ -16,6 +16,7 @@ import matplotlib.transforms as mtransforms import matplotlib.units as munits +GRIDLINE_INTERPOLATION_STEPS = 180 class Tick(artist.Artist): """ @@ -308,6 +309,7 @@ linewidth=rcParams['grid.linewidth'], ) l.set_transform(self.axes.get_xaxis_transform()) + l.get_path()._interpolation_steps = GRIDLINE_INTERPOLATION_STEPS self._set_artist_props(l) return l @@ -437,6 +439,7 @@ ) l.set_transform(self.axes.get_yaxis_transform()) + l.get_path()._interpolation_steps = GRIDLINE_INTERPOLATION_STEPS self._set_artist_props(l) return l Modified: trunk/matplotlib/lib/matplotlib/cbook.py =================================================================== --- trunk/matplotlib/lib/matplotlib/cbook.py 2009-05-21 21:06:49 UTC (rev 7130) +++ trunk/matplotlib/lib/matplotlib/cbook.py 2009-05-22 14:00:12 UTC (rev 7131) @@ -1177,6 +1177,9 @@ def simple_linear_interpolation(a, steps): + if steps == 1: + return a + steps = np.floor(steps) new_length = ((len(a) - 1) * steps) + 1 new_shape = list(a.shape) Modified: trunk/matplotlib/lib/matplotlib/lines.py =================================================================== --- trunk/matplotlib/lib/matplotlib/lines.py 2009-05-21 21:06:49 UTC (rev 7130) +++ trunk/matplotlib/lib/matplotlib/lines.py 2009-05-22 14:00:12 UTC (rev 7131) @@ -443,7 +443,11 @@ self._subslice = False if len(x) > 100 and self._is_sorted(x): self._subslice = True - self._path = Path(self._xy) + if hasattr(self, '_path'): + interpolation_steps = self._path._interpolation_steps + else: + interpolation_steps = 1 + self._path = Path(self._xy, None, interpolation_steps) self._transformed_path = None self._invalid = False Modified: trunk/matplotlib/lib/matplotlib/path.py =================================================================== --- trunk/matplotlib/lib/matplotlib/path.py 2009-05-21 21:06:49 UTC (rev 7130) +++ trunk/matplotlib/lib/matplotlib/path.py 2009-05-22 14:00:12 UTC (rev 7131) @@ -80,7 +80,7 @@ code_type = np.uint8 - def __init__(self, vertices, codes=None): + def __init__(self, vertices, codes=None, _interpolation_steps=1): """ Create a new path with the given vertices and codes. @@ -100,6 +100,11 @@ to NaNs which are then handled correctly by the Agg PathIterator and other consumers of path data, such as :meth:`iter_segments`. + + *interpolation_steps* is used as a hint to certain projections, + such as Polar, that this path should be linearly interpolated + immediately before drawing. This attribute is primarily an + implementation detail and is not intended for public use. """ if ma.isMaskedArray(vertices): vertices = vertices.astype(np.float_).filled(np.nan) @@ -118,12 +123,10 @@ (len(vertices) >= 128 and (codes is None or np.all(codes <= Path.LINETO)))) self.simplify_threshold = rcParams['path.simplify_threshold'] - # The following operation takes most of the time in this - # initialization, and it does not appear to be used anywhere; - # if it is occasionally needed, it could be made a property. - #self.has_nonfinite = not np.isfinite(vertices).all() + self.has_nonfinite = not np.isfinite(vertices).all() self.codes = codes self.vertices = vertices + self._interpolation_steps = _interpolation_steps @classmethod def make_compound_path(cls, *args): @@ -224,7 +227,8 @@ transformed result and automatically update when the transform changes. """ - return Path(transform.transform(self.vertices), self.codes) + return Path(transform.transform(self.vertices), self.codes, + self._interpolation_steps) def contains_point(self, point, transform=None): """ @@ -292,6 +296,9 @@ Returns a new path resampled to length N x steps. Does not currently handle interpolating curves. """ + if steps == 1: + return self + vertices = simple_linear_interpolation(self.vertices, steps) codes = self.codes if codes is not None: Modified: trunk/matplotlib/lib/matplotlib/projections/polar.py =================================================================== --- trunk/matplotlib/lib/matplotlib/projections/polar.py 2009-05-21 21:06:49 UTC (rev 7130) +++ trunk/matplotlib/lib/matplotlib/projections/polar.py 2009-05-22 14:00:12 UTC (rev 7131) @@ -1,4 +1,5 @@ import math +import warnings import numpy as npy @@ -32,15 +33,6 @@ output_dims = 2 is_separable = False - def __init__(self, resolution): - """ - Create a new polar transform. Resolution is the number of steps - to interpolate between each input line segment to approximate its - path in curved polar space. - """ - Transform.__init__(self) - self._resolution = resolution - def transform(self, tr): xy = npy.zeros(tr.shape, npy.float_) t = tr[:, 0:1] @@ -59,7 +51,7 @@ vertices = path.vertices if len(vertices) == 2 and vertices[0, 0] == vertices[1, 0]: return Path(self.transform(vertices), path.codes) - ipath = path.interpolated(self._resolution) + ipath = path.interpolated(path._interpolation_steps) return Path(self.transform(ipath.vertices), ipath.codes) transform_path.__doc__ = Transform.transform_path.__doc__ @@ -67,7 +59,7 @@ transform_path_non_affine.__doc__ = Transform.transform_path_non_affine.__doc__ def inverted(self): - return PolarAxes.InvertedPolarTransform(self._resolution) + return PolarAxes.InvertedPolarTransform() inverted.__doc__ = Transform.inverted.__doc__ class PolarAffine(Affine2DBase): @@ -109,10 +101,6 @@ output_dims = 2 is_separable = False - def __init__(self, resolution): - Transform.__init__(self) - self._resolution = resolution - def transform(self, xy): x = xy[:, 0:1] y = xy[:, 1:] @@ -123,7 +111,7 @@ transform.__doc__ = Transform.transform.__doc__ def inverted(self): - return PolarAxes.PolarTransform(self._resolution) + return PolarAxes.PolarTransform() inverted.__doc__ = Transform.inverted.__doc__ class ThetaFormatter(Formatter): @@ -177,8 +165,6 @@ return 0, vmax - RESOLUTION = 1 - def __init__(self, *args, **kwargs): """ Create a new Polar Axes for a polar plot. @@ -192,8 +178,11 @@ self._rpad = 0.05 self.resolution = kwargs.pop('resolution', None) - if self.resolution is None: - self.resolution = self.RESOLUTION + if self.resolution not in (None, 1): + warnings.warn( + """The resolution kwarg to Polar plots is now ignored. +If you need to interpolate data points, consider running +cbook.simple_linear_interpolation on the data before passing to matplotlib.""") Axes.__init__(self, *args, **kwargs) self.set_aspect('equal', adjustable='box', anchor='C') self.cla() @@ -221,7 +210,7 @@ self.transScale = TransformWrapper(IdentityTransform()) # A (possibly non-linear) projection on the (already scaled) data - self.transProjection = self.PolarTransform(self.resolution) + self.transProjection = self.PolarTransform() # An affine transformation on the data, generally to limit the # range of the axes Modified: trunk/matplotlib/lib/matplotlib/transforms.py =================================================================== --- trunk/matplotlib/lib/matplotlib/transforms.py 2009-05-21 21:06:49 UTC (rev 7130) +++ trunk/matplotlib/lib/matplotlib/transforms.py 2009-05-22 14:00:12 UTC (rev 7131) @@ -1119,7 +1119,8 @@ In some cases, this transform may insert curves into the path that began as line segments. """ - return Path(self.transform(path.vertices), path.codes) + return Path(self.transform(path.vertices), path.codes, + path._interpolation_steps) def transform_path_affine(self, path): """ @@ -1143,7 +1144,8 @@ ``transform_path(path)`` is equivalent to ``transform_path_affine(transform_path_non_affine(values))``. """ - return Path(self.transform_non_affine(path.vertices), path.codes) + return Path(self.transform_non_affine(path.vertices), path.codes, + self._interpolation_steps) def transform_angles(self, angles, pts, radians=False, pushoff=1e-5): """ @@ -2181,7 +2183,8 @@ self._transformed_path = \ self._transform.transform_path_non_affine(self._path) self._transformed_points = \ - Path(self._transform.transform_non_affine(self._path.vertices)) + Path(self._transform.transform_non_affine(self._path.vertices), + None, self._path._interpolation_steps) self._invalid = 0 def get_transformed_points_and_affine(self): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2009-05-22 14:22:08
|
Revision: 7132 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7132&view=rev Author: jdh2358 Date: 2009-05-22 14:22:03 +0000 (Fri, 22 May 2009) Log Message: ----------- Applied Tony's circle patch Modified Paths: -------------- trunk/matplotlib/examples/user_interfaces/embedding_in_wx3.py trunk/matplotlib/lib/matplotlib/patches.py Modified: trunk/matplotlib/examples/user_interfaces/embedding_in_wx3.py =================================================================== --- trunk/matplotlib/examples/user_interfaces/embedding_in_wx3.py 2009-05-22 14:00:12 UTC (rev 7131) +++ trunk/matplotlib/examples/user_interfaces/embedding_in_wx3.py 2009-05-22 14:22:03 UTC (rev 7132) @@ -147,7 +147,7 @@ return True def OnBang(self,event): - bang_count = XRCCTRL(self.frame,"bang_count") + bang_count = xrc.XRCCTRL(self.frame,"bang_count") bangs = bang_count.GetValue() bangs = int(bangs)+1 bang_count.SetValue(str(bangs)) Modified: trunk/matplotlib/lib/matplotlib/patches.py =================================================================== --- trunk/matplotlib/lib/matplotlib/patches.py 2009-05-22 14:00:12 UTC (rev 7131) +++ trunk/matplotlib/lib/matplotlib/patches.py 2009-05-22 14:22:03 UTC (rev 7132) @@ -1131,6 +1131,14 @@ self.radius = radius Ellipse.__init__(self, xy, radius*2, radius*2, **kwargs) __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd + + def radius(): + def fget(self): + return self.width / 2. + def fset(self, radius): + self.width = self.height = 2 * radius + return locals() + radius = property(**radius()) class Arc(Ellipse): """ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <he...@us...> - 2009-05-23 14:31:19
|
Revision: 7137 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7137&view=rev Author: heeres Date: 2009-05-23 14:31:14 +0000 (Sat, 23 May 2009) Log Message: ----------- mplot3d: contourf3d, bar / zordering Modified Paths: -------------- trunk/matplotlib/examples/mplot3d/demo.py trunk/matplotlib/lib/mpl_toolkits/mplot3d/art3d.py trunk/matplotlib/lib/mpl_toolkits/mplot3d/axes3d.py trunk/matplotlib/lib/mpl_toolkits/mplot3d/axis3d.py Modified: trunk/matplotlib/examples/mplot3d/demo.py =================================================================== --- trunk/matplotlib/examples/mplot3d/demo.py 2009-05-22 18:43:26 UTC (rev 7136) +++ trunk/matplotlib/examples/mplot3d/demo.py 2009-05-23 14:31:14 UTC (rev 7137) @@ -133,6 +133,6 @@ test_plot() test_polys() test_scatter2D() -# test_bar2D() + test_bar2D() plt.show() Modified: trunk/matplotlib/lib/mpl_toolkits/mplot3d/art3d.py =================================================================== --- trunk/matplotlib/lib/mpl_toolkits/mplot3d/art3d.py 2009-05-22 18:43:26 UTC (rev 7136) +++ trunk/matplotlib/lib/mpl_toolkits/mplot3d/art3d.py 2009-05-23 14:31:14 UTC (rev 7137) @@ -91,12 +91,21 @@ self._segments3d = segments LineCollection.set_segments(self, []) - def draw(self, renderer): + def do_3d_projection(self, renderer): xyslist = [ proj3d.proj_trans_points(points, renderer.M) for points in self._segments3d] segments_2d = [zip(xs,ys) for (xs,ys,zs) in xyslist] LineCollection.set_segments(self, segments_2d) + + minz = 1e9 + for (xs, ys, zs) in xyslist: + minz = min(minz, min(zs)) + return minz + + def draw(self, renderer, project=False): + if project: + self.do_3d_projection(renderer) LineCollection.draw(self, renderer) def line_collection_2d_to_3d(col, z=0, dir='z'): @@ -123,13 +132,16 @@ def get_facecolor(self): return self._facecolor2d - def draw(self, renderer): + def do_3d_projection(self, renderer): s = self._segment3d xs, ys, zs = zip(*s) vxs,vys,vzs,vis = proj3d.proj_transform_clip(xs,ys,zs, renderer.M) self._path2d = mpath.Path(zip(vxs, vys)) # FIXME: coloring self._facecolor2d = self._facecolor3d + return min(vzs) + + def draw(self, renderer): Patch.draw(self, renderer) def patch_2d_to_3d(patch, z=0, dir='z'): @@ -149,7 +161,7 @@ self._facecolor3d = self.get_facecolor() self._edgecolor3d = self.get_edgecolor() - def draw(self, renderer): + def do_3d_projection(self, renderer): xs,ys,zs = self._offsets3d vxs,vys,vzs,vis = proj3d.proj_transform_clip(xs,ys,zs, renderer.M) #FIXME: mpl allows us no way to unset the collection alpha value @@ -157,6 +169,10 @@ self.set_facecolors(zalpha(self._facecolor3d, vzs)) self.set_edgecolors(zalpha(self._edgecolor3d, vzs)) PatchCollection.set_offsets(self, zip(vxs, vys)) + + return min(vzs) + + def draw(self, renderer): PatchCollection.draw(self, renderer) def patch_collection_2d_to_3d(col, zs=0, dir='z'): @@ -185,6 +201,7 @@ 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): self.get_vector(verts) @@ -196,28 +213,35 @@ self._facecolors3d = PolyCollection.get_facecolors(self) self._edgecolors3d = self.get_edgecolors() - def get_facecolors(self): - return self._facecolors2d - get_facecolor = get_facecolors - - def draw(self, renderer): - txs, tys, tzs, tis = proj3d.proj_transform_vec_clip(self._vec, renderer.M) - xyslist = [(txs[si:ei], tys[si:ei], tzs[si:ei], tis[si:ei]) \ + def do_3d_projection(self, renderer): + txs, tys, tzs = proj3d.proj_transform_vec(self._vec, renderer.M) + xyzlist = [(txs[si:ei], tys[si:ei], tzs[si:ei]) \ for si, ei in self._segis] colors = self._facecolors3d - # + # if required sort by depth (furthest drawn first) if self._zsort: - z_segments_2d = [(min(zs),max(tis),zip(xs,ys),c) for - (xs,ys,zs,tis),c in zip(xyslist,colors)] + z_segments_2d = [(min(zs),zip(xs,ys),c) for + (xs,ys,zs),c in zip(xyzlist,colors)] z_segments_2d.sort() z_segments_2d.reverse() else: raise ValueError, "whoops" - segments_2d = [s for z,i,s,c in z_segments_2d if i] - colors = [c for z,i,s,c in z_segments_2d if i] + segments_2d = [s for z,s,c in z_segments_2d] + colors = [c for z,s,c in z_segments_2d] PolyCollection.set_verts(self, segments_2d) self._facecolors2d = colors + + # Return zorder value + zvec = np.array([[0], [0], [self._sort_zpos], [1]]) + ztrans = proj3d.proj_transform_vec(zvec, renderer.M) + return ztrans[2][0] + + def get_facecolors(self): + return self._facecolors2d + get_facecolor = get_facecolors + + def draw(self, renderer): return Collection.draw(self, renderer) def poly_collection_2d_to_3d(col, zs=None, dir='z'): Modified: trunk/matplotlib/lib/mpl_toolkits/mplot3d/axes3d.py =================================================================== --- trunk/matplotlib/lib/mpl_toolkits/mplot3d/axes3d.py 2009-05-22 18:43:26 UTC (rev 7136) +++ trunk/matplotlib/lib/mpl_toolkits/mplot3d/axes3d.py 2009-05-23 14:31:14 UTC (rev 7137) @@ -86,7 +86,7 @@ xdw = (0.9/self.dist) ydwl = (0.95/self.dist) ydw = (0.9/self.dist) - # + self.set_xlim(-xdwl,xdw) self.set_ylim(-ydwl,ydw) @@ -166,6 +166,22 @@ renderer.eye = self.eye renderer.get_axis_position = self.get_axis_position + # Calculate projection of collections and zorder them + zlist = [(col.do_3d_projection(renderer), col) \ + for col in self.collections] + zlist.sort() + zlist.reverse() + for i, (z, col) in enumerate(zlist): + col.zorder = i + + # Calculate projection of patches and zorder them + zlist = [(patch.do_3d_projection(renderer), patch) \ + for patch in self.patches] + zlist.sort() + zlist.reverse() + for i, (z, patch) in enumerate(zlist): + patch.zorder = i + self.w_xaxis.draw(renderer) self.w_yaxis.draw(renderer) self.w_zaxis.draw(renderer) @@ -179,7 +195,7 @@ zhigh = tc[0][2]>tc[2][2] return xhigh,yhigh,zhigh - def update_datalim(self, xys): + def update_datalim(self, xys, **kwargs): pass def update_datalim_numerix(self, x, y): @@ -293,12 +309,12 @@ # look into the middle of the new coordinates R = np.array([0.5,0.5,0.5]) - # + xp = R[0] + np.cos(razim)*np.cos(relev)*self.dist yp = R[1] + np.sin(razim)*np.cos(relev)*self.dist zp = R[2] + np.sin(relev)*self.dist E = np.array((xp, yp, zp)) - # + self.eye = E self.vvec = R - E self.vvec = self.vvec / proj3d.mod(self.vvec) @@ -393,7 +409,7 @@ ldists.sort() # nearest edge edgei = ldists[0][1] - # + p0,p1 = edges[edgei] # scale the z value to match @@ -403,7 +419,6 @@ d1 = np.hypot(x1-xd,y1-yd) dt = d0+d1 z = d1/dt * z0 + d0/dt * z1 - #print 'mid', edgei, d0, d1, z0, z1, z x,y,z = proj3d.inv_transform(xd,yd,z,self.M) @@ -440,8 +455,8 @@ if self.button_pressed == 1: # rotate viewing point # get the x and y pixel coords - if dx == 0 and dy == 0: return - # + if dx == 0 and dy == 0: + return self.elev = axis3d.norm_angle(self.elev - (dy/h)*180) self.azim = axis3d.norm_angle(self.azim - (dx/w)*180) self.get_proj() @@ -450,7 +465,6 @@ # pan view # project xv,yv,zv -> xw,yw,zw # pan - # pass elif self.button_pressed == 3: # zoom view @@ -469,7 +483,7 @@ def set_xlabel(self, xlabel, fontdict=None, **kwargs): #par = cbook.popd(kwargs, 'par',None) #label.set_par(par) - # + label = self.w_xaxis.get_label() label.set_text(xlabel) if fontdict is not None: label.update(fontdict) @@ -524,7 +538,7 @@ tX,tY,tZ = np.transpose(X), np.transpose(Y), np.transpose(Z) rstride = kwargs.pop('rstride', 10) cstride = kwargs.pop('cstride', 10) - # + polys = [] boxes = [] for rs in np.arange(0,rows-1,rstride): @@ -543,7 +557,7 @@ ps.append(z) boxes.append(map(np.array,zip(*corners))) polys.append(zip(*ps)) - # + lines = [] shade = [] for box in boxes: @@ -552,7 +566,7 @@ n = n/proj3d.mod(n)*5 shade.append(np.dot(n,[-1,-1,0.5])) lines.append((box[0],n+box[0])) - # + color = np.array([0,0,1,1]) norm = Normalize(min(shade),max(shade)) colors = [color * (0.5+norm(v)*0.5) for v in shade] @@ -560,7 +574,7 @@ polyc = art3d.Poly3DCollection(polys, facecolors=colors, *args, **kwargs) polyc._zsort = 1 self.add_collection(polyc) - # + self.auto_scale_xyz(X,Y,Z, had_data) return polyc @@ -578,11 +592,11 @@ xlines = [X[i] for i in rii] ylines = [Y[i] for i in rii] zlines = [Z[i] for i in rii] - # + txlines = [tX[i] for i in cii] tylines = [tY[i] for i in cii] tzlines = [tZ[i] for i in cii] - # + lines = [zip(xl,yl,zl) for xl,yl,zl in zip(xlines,ylines,zlines)] lines += [zip(xl,yl,zl) for xl,yl,zl in zip(txlines,tylines,tzlines)] linec = self.add_lines(lines, *args, **kwargs) @@ -614,6 +628,7 @@ zs = [z1] * (len(linec.get_paths()[0])/2) zs += [z2] * (len(linec.get_paths()[0])/2) art3d.poly_collection_2d_to_3d(linec, zs) + self.auto_scale_xyz(X,Y,Z, had_data) return cset @@ -701,6 +716,7 @@ def bar(self, left, height, z=0, dir='z', *args, **kwargs): had_data = self.has_data() + patches = self.wrapped.bar(left, height, *args, **kwargs) verts = [] for p in patches: @@ -863,6 +879,6 @@ test_plot() test_polys() test_scatter2D() -# test_bar2D() + test_bar2D() pylab.show() Modified: trunk/matplotlib/lib/mpl_toolkits/mplot3d/axis3d.py =================================================================== --- trunk/matplotlib/lib/mpl_toolkits/mplot3d/axis3d.py 2009-05-22 18:43:26 UTC (rev 7136) +++ trunk/matplotlib/lib/mpl_toolkits/mplot3d/axis3d.py 2009-05-23 14:31:14 UTC (rev 7137) @@ -85,7 +85,7 @@ # data and viewing intervals for this direction self.d_interval = d_intervalx self.v_interval = v_intervalx - # + axis.XAxis.__init__(self, axes, *args, **kwargs) self.line = lines.Line2D(xdata=(0,0),ydata=(0,0), linewidth=0.75, @@ -248,7 +248,7 @@ lines = zip(xyz1, xyz0, xyz2) self.gridlines.set_segments(lines) self.gridlines.set_color([(0.9,0.9,0.9,1)] * len(lines)) - self.gridlines.draw(renderer) + self.gridlines.draw(renderer, project=True) # Draw ticks tickdir = info['tickdir'] This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <as...@us...> - 2009-05-27 16:25:21
|
Revision: 7144 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7144&view=rev Author: astraw Date: 2009-05-27 16:25:15 +0000 (Wed, 27 May 2009) Log Message: ----------- Arbitrary spine placement Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/doc/api/api_changes.rst trunk/matplotlib/doc/users/whats_new.rst trunk/matplotlib/examples/api/custom_projection_example.py trunk/matplotlib/examples/tests/backend_driver.py trunk/matplotlib/lib/matplotlib/axes.py trunk/matplotlib/lib/matplotlib/axis.py trunk/matplotlib/lib/matplotlib/projections/geo.py trunk/matplotlib/lib/matplotlib/projections/polar.py Added Paths: ----------- trunk/matplotlib/examples/pylab_examples/spine_placement_demo.py trunk/matplotlib/lib/matplotlib/spines.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-05-27 16:24:53 UTC (rev 7143) +++ trunk/matplotlib/CHANGELOG 2009-05-27 16:25:15 UTC (rev 7144) @@ -1,3 +1,5 @@ +2009-05-26 Add support for "axis spines" to have arbitrary location. -ADS + 2009-05-20 Add an empty matplotlibrc to the tests/ directory so that running tests will use the default set of rcparams rather than the user's config. - RMM Modified: trunk/matplotlib/doc/api/api_changes.rst =================================================================== --- trunk/matplotlib/doc/api/api_changes.rst 2009-05-27 16:24:53 UTC (rev 7143) +++ trunk/matplotlib/doc/api/api_changes.rst 2009-05-27 16:25:15 UTC (rev 7144) @@ -20,6 +20,13 @@ Changes beyond 0.98.x ===================== +* Axes instanaces no longer have a "frame" attribute. Instead, use the + new "spines" attribute. Spines is a dictionary where the keys are + the names of the spines (e.g. 'left','right' and so on) and the + values are the artists that draw the spines. For normal + (rectilinear) axes, these artists are Line2D instances. For other + axes (such as polar axes), these artists may be Patch instances. + * Polar plots no longer accept a resolution kwarg. Instead, each Path must specify its own number of interpolation steps. This is unlikely to be a user-visible change -- if interpolation of data is Modified: trunk/matplotlib/doc/users/whats_new.rst =================================================================== --- trunk/matplotlib/doc/users/whats_new.rst 2009-05-27 16:24:53 UTC (rev 7143) +++ trunk/matplotlib/doc/users/whats_new.rst 2009-05-27 16:25:15 UTC (rev 7144) @@ -4,6 +4,18 @@ What's new in matplotlib *************************** +.. _whats-new-svn: + +What new in svn +=============== + +Axis spine placement +-------------------- + +Andrew Straw has added the ability to place "axis spines" -- the lines +that denote the data limits -- in various arbitrary locations. See +:class:`matplotlib.spines.Spine`. + .. _whats-new-0-98-4: What new in 0.98.4 Modified: trunk/matplotlib/examples/api/custom_projection_example.py =================================================================== --- trunk/matplotlib/examples/api/custom_projection_example.py 2009-05-27 16:24:53 UTC (rev 7143) +++ trunk/matplotlib/examples/api/custom_projection_example.py 2009-05-27 16:25:15 UTC (rev 7144) @@ -6,6 +6,8 @@ from matplotlib.transforms import Affine2D, Affine2DBase, Bbox, \ BboxTransformTo, IdentityTransform, Transform, TransformWrapper from matplotlib.projections import register_projection +import matplotlib.spines as mspines +import matplotlib.axis as maxis import numpy as np @@ -32,6 +34,14 @@ self.set_aspect(0.5, adjustable='box', anchor='C') self.cla() + def _init_axis(self): + self.xaxis = maxis.XAxis(self) + self.yaxis = maxis.YAxis(self) + # Do not register xaxis or yaxis with spines -- as done in + # Axes._init_axis() -- until HammerAxes.xaxis.cla() works. + # self.spines['hammer'].register_axis(self.yaxis) + self._update_transScale() + def cla(self): """ Override to set up some reasonable defaults. @@ -163,11 +173,12 @@ yaxis_text_base + \ Affine2D().translate(8.0, 0.0) - def get_xaxis_transform(self): + def get_xaxis_transform(self,which=None): """ Override this method to provide a transformation for the x-axis grid and ticks. """ + assert which in ['tick1','tick2','grid'] return self._xaxis_transform def get_xaxis_text1_transform(self, pixelPad): @@ -188,11 +199,12 @@ """ return self._xaxis_text2_transform, 'top', 'center' - def get_yaxis_transform(self): + def get_yaxis_transform(self,which=None): """ Override this method to provide a transformation for the y-axis grid and ticks. """ + assert which in ['tick1','tick2','grid'] return self._yaxis_transform def get_yaxis_text1_transform(self, pixelPad): @@ -224,6 +236,9 @@ """ return Circle((0.5, 0.5), 0.5) + def _gen_axes_spines(self): + return {'hammer':mspines.Spine(self,'hammer',Circle((0.5, 0.5), 0.5))} + # Prevent the user from applying scales to one or both of the # axes. In this particular case, scaling the axes wouldn't make # sense, so we don't allow it. Added: trunk/matplotlib/examples/pylab_examples/spine_placement_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/spine_placement_demo.py (rev 0) +++ trunk/matplotlib/examples/pylab_examples/spine_placement_demo.py 2009-05-27 16:25:15 UTC (rev 7144) @@ -0,0 +1,116 @@ +import matplotlib.pyplot as plt +import numpy as np +from matplotlib.pyplot import show + +fig = plt.figure() +x = np.linspace(0,2*np.pi,100) +y = 2*np.sin(x) +ax = fig.add_subplot(1,2,1) +ax.set_title('dropped spines') +ax.plot(x,y) +for loc, spine in ax.spines.iteritems(): + if loc in ['left','bottom']: + spine.set_position(('outward',10)) # outward by 10 points + elif loc in ['right','top']: + spine.set_color('none') # don't draw spine + else: + raise ValueError('unknown spine location: %s'%loc) + +# turn off ticks where there is no spine +ax.xaxis.set_ticks_position('bottom') +ax.yaxis.set_ticks_position('left') + +ax = fig.add_subplot(1,2,2,sharex=ax) +ax.plot(x,y) +ax.set_title('normal spines') + +# ---------------------------------------------------- + +fig = plt.figure() +x = np.linspace(-np.pi,np.pi,100) +y = 2*np.sin(x) + +ax = fig.add_subplot(2,2,1) +ax.set_title('centered spines') +ax.plot(x,y) +ax.spines['left'].set_position('center') +ax.spines['right'].set_color('none') +ax.spines['bottom'].set_position('center') +ax.spines['top'].set_color('none') +ax.xaxis.set_ticks_position('bottom') +ax.yaxis.set_ticks_position('left') + +ax = fig.add_subplot(2,2,2) +ax.set_title('zeroed spines') +ax.plot(x,y) +ax.spines['left'].set_position('zero') +ax.spines['right'].set_color('none') +ax.spines['bottom'].set_position('zero') +ax.spines['top'].set_color('none') +ax.xaxis.set_ticks_position('bottom') +ax.yaxis.set_ticks_position('left') + +ax = fig.add_subplot(2,2,3) +ax.set_title('spines at axes (0.6, 0.1)') +ax.plot(x,y) +ax.spines['left'].set_position(('axes',0.6)) +ax.spines['right'].set_color('none') +ax.spines['bottom'].set_position(('axes',0.1)) +ax.spines['top'].set_color('none') +ax.xaxis.set_ticks_position('bottom') +ax.yaxis.set_ticks_position('left') + +ax = fig.add_subplot(2,2,4) +ax.set_title('spines at data (1,2)') +ax.plot(x,y) +ax.spines['left'].set_position(('data',1)) +ax.spines['right'].set_color('none') +ax.spines['bottom'].set_position(('data',2)) +ax.spines['top'].set_color('none') +ax.xaxis.set_ticks_position('bottom') +ax.yaxis.set_ticks_position('left') + +# ---------------------------------------------------- + +def adjust_spines(ax,spines): + for loc, spine in ax.spines.iteritems(): + if loc in spines: + spine.set_position(('outward',10)) # outward by 10 points + else: + spine.set_color('none') # don't draw spine + + # turn off ticks where there is no spine + if 'left' in spines: + ax.yaxis.set_ticks_position('left') + else: + # no yaxis ticks + ax.yaxis.set_ticks([]) + + if 'bottom' in spines: + ax.xaxis.set_ticks_position('bottom') + else: + # no xaxis ticks + ax.xaxis.set_ticks([]) + +fig = plt.figure() + +x = np.linspace(0,2*np.pi,100) +y = 2*np.sin(x) + +ax = fig.add_subplot(2,2,1) +ax.plot(x,y) +adjust_spines(ax,['left']) + +ax = fig.add_subplot(2,2,2) +ax.plot(x,y) +adjust_spines(ax,[]) + +ax = fig.add_subplot(2,2,3) +ax.plot(x,y) +adjust_spines(ax,['left','bottom']) + +ax = fig.add_subplot(2,2,4) +ax.plot(x,y) +adjust_spines(ax,['bottom']) + +show() Modified: trunk/matplotlib/examples/tests/backend_driver.py =================================================================== --- trunk/matplotlib/examples/tests/backend_driver.py 2009-05-27 16:24:53 UTC (rev 7143) +++ trunk/matplotlib/examples/tests/backend_driver.py 2009-05-27 16:25:15 UTC (rev 7144) @@ -173,6 +173,7 @@ 'simple_plot.py', 'simplification_clipping_test.py', 'specgram_demo.py', + 'spine_placement_demo.py', 'spy_demos.py', 'stem_plot.py', 'step_demo.py', Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2009-05-27 16:24:53 UTC (rev 7143) +++ trunk/matplotlib/lib/matplotlib/axes.py 2009-05-27 16:25:15 UTC (rev 7144) @@ -21,6 +21,7 @@ import matplotlib.lines as mlines import matplotlib.mlab as mlab import matplotlib.patches as mpatches +import matplotlib.spines as mspines import matplotlib.quiver as mquiver import matplotlib.scale as mscale import matplotlib.table as mtable @@ -526,6 +527,8 @@ self.set_axes_locator(kwargs.get("axes_locator", None)) + self.spines = self._gen_axes_spines() + # this call may differ for non-sep axes, eg polar self._init_axis() @@ -576,7 +579,11 @@ def _init_axis(self): "move this out of __init__ because non-separable axes don't use it" self.xaxis = maxis.XAxis(self) + self.spines['bottom'].register_axis(self.xaxis) + self.spines['top'].register_axis(self.xaxis) self.yaxis = maxis.YAxis(self) + self.spines['left'].register_axis(self.yaxis) + self.spines['right'].register_axis(self.yaxis) self._update_transScale() def set_figure(self, fig): @@ -634,7 +641,7 @@ self._yaxis_transform = mtransforms.blended_transform_factory( self.transAxes, self.transData) - def get_xaxis_transform(self): + def get_xaxis_transform(self,which=None): """ Get the transformation used for drawing x-axis labels, ticks and gridlines. The x-direction is in data coordinates and the @@ -646,7 +653,16 @@ overridden by new kinds of projections that may need to place axis elements in different locations. """ - return self._xaxis_transform + if which=='grid': + return self._xaxis_transform + elif which=='tick1': + # for cartesian projection, this is bottom spine + return self.spines['bottom'].get_spine_transform() + elif which=='tick2': + # for cartesian projection, this is top spine + return self.spines['top'].get_spine_transform() + else: + raise ValueError('unknown value for which') def get_xaxis_text1_transform(self, pad_points): """ @@ -667,7 +683,7 @@ overridden by new kinds of projections that may need to place axis elements in different locations. """ - return (self._xaxis_transform + + return (self.get_xaxis_transform(which='tick1') + mtransforms.ScaledTranslation(0, -1 * pad_points / 72.0, self.figure.dpi_scale_trans), "top", "center") @@ -691,12 +707,12 @@ overridden by new kinds of projections that may need to place axis elements in different locations. """ - return (self._xaxis_transform + + return (self.get_xaxis_transform(which='tick2') + mtransforms.ScaledTranslation(0, pad_points / 72.0, self.figure.dpi_scale_trans), "bottom", "center") - def get_yaxis_transform(self): + def get_yaxis_transform(self,which=None): """ Get the transformation used for drawing y-axis labels, ticks and gridlines. The x-direction is in axis coordinates and the @@ -708,7 +724,16 @@ overridden by new kinds of projections that may need to place axis elements in different locations. """ - return self._yaxis_transform + if which=='grid': + return self._yaxis_transform + elif which=='tick1': + # for cartesian projection, this is bottom spine + return self.spines['left'].get_spine_transform() + elif which=='tick2': + # for cartesian projection, this is top spine + return self.spines['right'].get_spine_transform() + else: + raise ValueError('unknown value for which') def get_yaxis_text1_transform(self, pad_points): """ @@ -729,7 +754,7 @@ overridden by new kinds of projections that may need to place axis elements in different locations. """ - return (self._yaxis_transform + + return (self.get_yaxis_transform(which='tick1') + mtransforms.ScaledTranslation(-1 * pad_points / 72.0, 0, self.figure.dpi_scale_trans), "center", "right") @@ -754,7 +779,7 @@ overridden by new kinds of projections that may need to place axis elements in different locations. """ - return (self._yaxis_transform + + return (self.get_yaxis_transform(which='tick2') + mtransforms.ScaledTranslation(pad_points / 72.0, 0, self.figure.dpi_scale_trans), "center", "left") @@ -853,6 +878,29 @@ """ return mpatches.Rectangle((0.0, 0.0), 1.0, 1.0) + def _gen_axes_spines(self, locations=None, offset=0.0, units='inches'): + """ + Returns a dict whose keys are spine names and values are + Line2D or Patch instances. Each element is used to draw a + spine of the axes. + + In the standard axes, this is a single line segment, but in + other projections it may not be. + + .. note:: + Intended to be overridden by new projection types. + """ + return { + 'left':mspines.Spine(self,'left', + mlines.Line2D((0.0, 0.0), (0.0, 1.0))), + 'right':mspines.Spine(self,'right', + mlines.Line2D((1.0, 1.0), (0.0, 1.0))), + 'bottom':mspines.Spine(self,'bottom', + mlines.Line2D((0.0, 1.0), (0.0, 0.0))), + 'top':mspines.Spine(self,'top', + mlines.Line2D((0.0, 1.0), (1.0, 1.0))), + } + def cla(self): 'Clear the current axes' # Note: this is called by Axes.__init__() @@ -928,17 +976,6 @@ self.patch.set_linewidth(0) self.patch.set_transform(self.transAxes) - # the frame draws the border around the axes and we want this - # above. this is a place holder for a more sophisticated - # artist that might just draw a left, bottom frame, or a - # centered frame, etc the axesFrame name is deprecated - self.frame = self.axesFrame = self._gen_axes_patch() - self.frame.set_figure(self.figure) - self.frame.set_facecolor('none') - self.frame.set_edgecolor(rcParams['axes.edgecolor']) - self.frame.set_linewidth(rcParams['axes.linewidth']) - self.frame.set_transform(self.transAxes) - self.frame.set_zorder(2.5) self.axison = True self.xaxis.set_clip_path(self.patch) @@ -947,6 +984,10 @@ self._shared_x_axes.clean() self._shared_y_axes.clean() + def get_frame(self): + raise AttributeError('Axes.frame was removed in favor of Axes.spines') + frame = property(get_frame) + def clear(self): 'clear the axes' self.cla() @@ -1724,7 +1765,7 @@ # decouple these so the patch can be in the background and the # frame in the foreground. if self.axison and self._frameon: - artists.append(self.frame) + artists.extend(self.spines.itervalues()) dsu = [ (a.zorder, i, a) for i, a in enumerate(artists) @@ -2645,7 +2686,7 @@ children.extend(self.collections) children.append(self.title) children.append(self.patch) - children.append(self.frame) + children.extend(self.spines.itervalues()) return children def contains(self,mouseevent): Modified: trunk/matplotlib/lib/matplotlib/axis.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axis.py 2009-05-27 16:24:53 UTC (rev 7143) +++ trunk/matplotlib/lib/matplotlib/axis.py 2009-05-27 16:25:15 UTC (rev 7144) @@ -282,7 +282,7 @@ marker = self._xtickmarkers[0], markersize=self._size, ) - l.set_transform(self.axes.get_xaxis_transform()) + l.set_transform(self.axes.get_xaxis_transform(which='tick1')) self._set_artist_props(l) return l @@ -296,7 +296,7 @@ markersize=self._size, ) - l.set_transform(self.axes.get_xaxis_transform()) + l.set_transform(self.axes.get_xaxis_transform(which='tick2')) self._set_artist_props(l) return l @@ -308,7 +308,7 @@ linestyle=rcParams['grid.linestyle'], linewidth=rcParams['grid.linewidth'], ) - l.set_transform(self.axes.get_xaxis_transform()) + l.set_transform(self.axes.get_xaxis_transform(which='grid')) l.get_path()._interpolation_steps = GRIDLINE_INTERPOLATION_STEPS self._set_artist_props(l) @@ -412,7 +412,7 @@ linestyle = 'None', markersize=self._size, ) - l.set_transform(self.axes.get_yaxis_transform()) + l.set_transform(self.axes.get_yaxis_transform(which='tick1')) self._set_artist_props(l) return l @@ -425,7 +425,7 @@ markersize=self._size, ) - l.set_transform(self.axes.get_yaxis_transform()) + l.set_transform(self.axes.get_yaxis_transform(which='tick2')) self._set_artist_props(l) return l @@ -438,7 +438,7 @@ linewidth=rcParams['grid.linewidth'], ) - l.set_transform(self.axes.get_yaxis_transform()) + l.set_transform(self.axes.get_yaxis_transform(which='grid')) l.get_path()._interpolation_steps = GRIDLINE_INTERPOLATION_STEPS self._set_artist_props(l) return l Modified: trunk/matplotlib/lib/matplotlib/projections/geo.py =================================================================== --- trunk/matplotlib/lib/matplotlib/projections/geo.py 2009-05-27 16:24:53 UTC (rev 7143) +++ trunk/matplotlib/lib/matplotlib/projections/geo.py 2009-05-27 16:25:15 UTC (rev 7144) @@ -10,6 +10,8 @@ from matplotlib import cbook from matplotlib.patches import Circle from matplotlib.path import Path +import matplotlib.spines as mspines +import matplotlib.axis as maxis from matplotlib.ticker import Formatter, Locator, NullLocator, FixedLocator, NullFormatter from matplotlib.transforms import Affine2D, Affine2DBase, Bbox, \ BboxTransformTo, IdentityTransform, Transform, TransformWrapper @@ -36,6 +38,14 @@ RESOLUTION = 75 + def _init_axis(self): + self.xaxis = maxis.XAxis(self) + self.yaxis = maxis.YAxis(self) + # Do not register xaxis or yaxis with spines -- as done in + # Axes._init_axis() -- until GeoAxes.xaxis.cla() works. + # self.spines['geo'].register_axis(self.yaxis) + self._update_transScale() + def cla(self): Axes.cla(self) @@ -111,7 +121,8 @@ .scale(0.5 / xscale, 0.5 / yscale) \ .translate(0.5, 0.5) - def get_xaxis_transform(self): + def get_xaxis_transform(self,which=None): + assert which in ['tick1','tick2','grid'] return self._xaxis_transform def get_xaxis_text1_transform(self, pad): @@ -120,7 +131,8 @@ def get_xaxis_text2_transform(self, pad): return self._xaxis_text2_transform, 'top', 'center' - def get_yaxis_transform(self): + def get_yaxis_transform(self,which=None): + assert which in ['tick1','tick2','grid'] return self._yaxis_transform def get_yaxis_text1_transform(self, pad): @@ -132,6 +144,9 @@ def _gen_axes_patch(self): return Circle((0.5, 0.5), 0.5) + def _gen_axes_spines(self): + return {'geo':mspines.Spine(self,'geo',Circle((0.5, 0.5), 0.5))} + def set_yscale(self, *args, **kwargs): if args[0] != 'linear': raise NotImplementedError Modified: trunk/matplotlib/lib/matplotlib/projections/polar.py =================================================================== --- trunk/matplotlib/lib/matplotlib/projections/polar.py 2009-05-27 16:24:53 UTC (rev 7143) +++ trunk/matplotlib/lib/matplotlib/projections/polar.py 2009-05-27 16:25:15 UTC (rev 7144) @@ -7,12 +7,14 @@ rcParams = matplotlib.rcParams from matplotlib.artist import kwdocd from matplotlib.axes import Axes +import matplotlib.axis as maxis from matplotlib import cbook from matplotlib.patches import Circle from matplotlib.path import Path from matplotlib.ticker import Formatter, Locator from matplotlib.transforms import Affine2D, Affine2DBase, Bbox, \ BboxTransformTo, IdentityTransform, Transform, TransformWrapper +import matplotlib.spines as mspines class PolarAxes(Axes): """ @@ -202,6 +204,16 @@ self.xaxis.set_ticks_position('none') self.yaxis.set_ticks_position('none') + def _init_axis(self): + "move this out of __init__ because non-separable axes don't use it" + self.xaxis = maxis.XAxis(self) + self.yaxis = maxis.YAxis(self) + # Calling polar_axes.xaxis.cla() or polar_axes.xaxis.cla() + # results in weird artifacts. Therefore we disable this for + # now. + # self.spines['polar'].register_axis(self.yaxis) + self._update_transScale() + def _set_lim_and_transforms(self): self.transAxes = BboxTransformTo(self.bbox) @@ -258,7 +270,8 @@ self._yaxis_transform ) - def get_xaxis_transform(self): + def get_xaxis_transform(self,which=None): + assert which in ['tick1','tick2','grid'] return self._xaxis_transform def get_xaxis_text1_transform(self, pad): @@ -267,7 +280,8 @@ def get_xaxis_text2_transform(self, pad): return self._xaxis_text2_transform, 'center', 'center' - def get_yaxis_transform(self): + def get_yaxis_transform(self,which=None): + assert which in ['tick1','tick2','grid'] return self._yaxis_transform def get_yaxis_text1_transform(self, pad): @@ -279,6 +293,9 @@ def _gen_axes_patch(self): return Circle((0.5, 0.5), 0.5) + def _gen_axes_spines(self): + return {'polar':mspines.Spine(self,'polar',Circle((0.5, 0.5), 0.5))} + def set_rmax(self, rmax): self.viewLim.y0 = 0 self.viewLim.y1 = rmax Added: trunk/matplotlib/lib/matplotlib/spines.py =================================================================== --- trunk/matplotlib/lib/matplotlib/spines.py (rev 0) +++ trunk/matplotlib/lib/matplotlib/spines.py 2009-05-27 16:25:15 UTC (rev 7144) @@ -0,0 +1,232 @@ +from __future__ import division + +import matplotlib +rcParams = matplotlib.rcParams + +import matplotlib.artist as martist +from matplotlib.artist import allow_rasterization +import matplotlib.transforms as mtransforms +import matplotlib.lines as mlines +import matplotlib.patches as mpatches +import warnings + +class Spine(martist.Artist): + """an axis spine -- the line noting the data area boundaries + + Spines are the lines connecting the axis tick marks and noting the + boundaries of the data area. They can be placed at arbitrary + positions. See function:`~matplotlib.spines.Spine.set_position` + for more information. + + The default position is ``('outward',0)``. + """ + def __str__(self): + return "Spine" + + def __init__(self,axes,spine_type,artist): + """ + - *axes* : the Axes instance containing the spine + - *spine_type* : a string specifying the spine type + - *artist* : the artist instance used to draw the spine + """ + martist.Artist.__init__(self) + self.axes = axes + self.set_figure(self.axes.figure) + self.spine_type = spine_type + self.artist = artist + self.color = rcParams['axes.edgecolor'] + self.axis = None + + if isinstance(self.artist,mlines.Line2D): + self.artist.set_color(self.color) + self.artist.set_linewidth(rcParams['axes.linewidth']) + elif isinstance(self.artist,mpatches.Patch): + self.artist.set_facecolor('none') + self.artist.set_edgecolor(self.color) + self.artist.set_linewidth(rcParams['axes.linewidth']) + self.artist.set_zorder(2.5) + self.artist.set_transform(self.axes.transAxes) # default transform + + # Defer initial position determination. (Not much support for + # non-rectangular axes is currently implemented, and this lets + # them pass through the spines machinery without errors.) + self._position = None + + def _ensure_position_is_set(self): + if self._position is None: + # default position + self._position = ('outward',0.0) # in points + self.set_position(self._position) + + def register_axis(self,axis): + """register an axis + + An axis should be registered with its corresponding spine from + the Axes instance. This allows the spine to clear any axis + properties when needed. + """ + self.axis = axis + if self.axis is not None: + self.axis.cla() + + @allow_rasterization + def draw(self,renderer): + "draw everything that belongs to the spine" + if self.color=='none': + # don't draw invisible spines + return + self.artist.draw(renderer) + + def _calc_offset_transform(self): + """calculate the offset transform performed by the spine""" + self._ensure_position_is_set() + position = self._position + if isinstance(position,basestring): + if position=='center': + position = ('axes',0.5) + elif position=='zero': + position = ('data',0) + assert len(position)==2, "position should be 2-tuple" + position_type, amount = position + assert position_type in ('axes','outward','data') + if position_type=='outward': + if amount == 0: + # short circuit commonest case + self._spine_transform = ('identity',mtransforms.IdentityTransform()) + elif self.spine_type in ['left','right','top','bottom']: + offset_vec = {'left':(-1,0), + 'right':(1,0), + 'bottom':(0,-1), + 'top':(0,1), + }[self.spine_type] + # calculate x and y offset in dots + offset_x = amount*offset_vec[0]/ 72.0 + offset_y = amount*offset_vec[1]/ 72.0 + self._spine_transform = ('post', + mtransforms.ScaledTranslation(offset_x,offset_y, + self.figure.dpi_scale_trans)) + else: + warnings.warn('unknown spine type "%s": no spine ' + 'offset performed'%self.spine_type) + self._spine_transform = ('identity',mtransforms.IdentityTransform()) + elif position_type=='axes': + if self.spine_type in ('left','right'): + self._spine_transform = ('pre', + mtransforms.Affine2D().translate(amount, 0.0)) + elif self.spine_type in ('bottom','top'): + self._spine_transform = ('pre', + mtransforms.Affine2D().translate(0.0, amount)) + else: + warnings.warn('unknown spine type "%s": no spine ' + 'offset performed'%self.spine_type) + self._spine_transform = ('identity',mtransforms.IdentityTransform()) + elif position_type=='data': + if self.spine_type in ('left','right'): + self._spine_transform = ('data', + mtransforms.Affine2D().translate(amount,0)) + elif self.spine_type in ('bottom','top'): + self._spine_transform = ('data', + mtransforms.Affine2D().translate(0,amount)) + else: + warnings.warn('unknown spine type "%s": no spine ' + 'offset performed'%self.spine_type) + self._spine_transform = ('identity',mtransforms.IdentityTransform()) + + def set_position(self,position): + """set the position of the spine + + Spine position is specified by a 2 tuple of (position type, + amount). The position types are: + + * 'outward' : place the spine out from the data area by the + specified number of points. (Negative values specify placing the + spine inward.) + + * 'axes' : place the spine at the specified Axes coordinate (from + 0.0-1.0). + + * 'data' : place the spine at the specified data coordinate. + + Additionally, shorthand notations define a special positions: + + * 'center' -> ('axes',0.5) + * 'zero' -> ('data', 0.0) + + """ + if position in ('center','zero'): + # special positions + pass + else: + assert len(position)==2, "position should be 'center' or 2-tuple" + assert position[0] in ['outward','axes','data'] + self._position = position + self._calc_offset_transform() + + t = self.get_spine_transform() + if self.spine_type in ['left','right']: + t2 = mtransforms.blended_transform_factory(t, + self.axes.transAxes) + elif self.spine_type in ['bottom','top']: + t2 = mtransforms.blended_transform_factory(self.axes.transAxes, + t) + self.artist.set_transform(t2) + + if self.axis is not None: + self.axis.cla() + + def get_position(self): + """get the spine position""" + self._ensure_position_is_set() + return self._position + + def get_spine_transform(self): + """get the spine transform""" + self._ensure_position_is_set() + what, how = self._spine_transform + + if what == 'data': + # special case data based spine locations + if self.spine_type in ['left','right']: + data_xform = self.axes.transScale + \ + (how+self.axes.transLimits + self.axes.transAxes) + result = mtransforms.blended_transform_factory( + data_xform,self.axes.transData) + elif self.spine_type in ['top','bottom']: + data_xform = self.axes.transScale + \ + (how+self.axes.transLimits + self.axes.transAxes) + result = mtransforms.blended_transform_factory( + self.axes.transData,data_xform) + else: + raise ValueError('unknown spine spine_type: %s'%self.spine_type) + return result + + if self.spine_type in ['left','right']: + base_transform = self.axes.get_yaxis_transform(which='grid') + elif self.spine_type in ['top','bottom']: + base_transform = self.axes.get_xaxis_transform(which='grid') + else: + raise ValueError('unknown spine spine_type: %s'%self.spine_type) + + if what=='identity': + return base_transform + elif what=='post': + return base_transform+how + elif what=='pre': + return how+base_transform + else: + raise ValueError("unknown spine_transform type: %s"%what) + + def set_color(self,value): + """set the color of the spine artist + + Note: a value of 'none' will cause the artist not to be drawn. + """ + self.color = value + if isinstance(self.artist,mlines.Line2D): + self.artist.set_color(self.color) + elif isinstance(self.artist,mpatches.Patch): + self.artist.set_edgecolor(self.color) + + def get_color(self): + """get the color of the spine artist""" + return self.color This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <as...@us...> - 2009-05-27 16:25:39
|
Revision: 7145 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7145&view=rev Author: astraw Date: 2009-05-27 16:25:33 +0000 (Wed, 27 May 2009) Log Message: ----------- make default argument to Axes.get_xaxis_transform() not raise error I made this a separate commit from the previous one because it may be useful to see the errors that arise if get_xaxis_transform() or get_yaxis_transform() are called with no arguments. This would allow one to figure out which code paths are calling these methods and fix them if needed rather than silently partially succeeding. Modified Paths: -------------- trunk/matplotlib/examples/api/custom_projection_example.py trunk/matplotlib/lib/matplotlib/axes.py trunk/matplotlib/lib/matplotlib/projections/geo.py trunk/matplotlib/lib/matplotlib/projections/polar.py Modified: trunk/matplotlib/examples/api/custom_projection_example.py =================================================================== --- trunk/matplotlib/examples/api/custom_projection_example.py 2009-05-27 16:25:15 UTC (rev 7144) +++ trunk/matplotlib/examples/api/custom_projection_example.py 2009-05-27 16:25:33 UTC (rev 7145) @@ -173,7 +173,7 @@ yaxis_text_base + \ Affine2D().translate(8.0, 0.0) - def get_xaxis_transform(self,which=None): + def get_xaxis_transform(self,which='grid'): """ Override this method to provide a transformation for the x-axis grid and ticks. @@ -199,7 +199,7 @@ """ return self._xaxis_text2_transform, 'top', 'center' - def get_yaxis_transform(self,which=None): + def get_yaxis_transform(self,which='grid'): """ Override this method to provide a transformation for the y-axis grid and ticks. Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2009-05-27 16:25:15 UTC (rev 7144) +++ trunk/matplotlib/lib/matplotlib/axes.py 2009-05-27 16:25:33 UTC (rev 7145) @@ -641,7 +641,7 @@ self._yaxis_transform = mtransforms.blended_transform_factory( self.transAxes, self.transData) - def get_xaxis_transform(self,which=None): + def get_xaxis_transform(self,which='grid'): """ Get the transformation used for drawing x-axis labels, ticks and gridlines. The x-direction is in data coordinates and the @@ -712,7 +712,7 @@ self.figure.dpi_scale_trans), "bottom", "center") - def get_yaxis_transform(self,which=None): + def get_yaxis_transform(self,which='grid'): """ Get the transformation used for drawing y-axis labels, ticks and gridlines. The x-direction is in axis coordinates and the Modified: trunk/matplotlib/lib/matplotlib/projections/geo.py =================================================================== --- trunk/matplotlib/lib/matplotlib/projections/geo.py 2009-05-27 16:25:15 UTC (rev 7144) +++ trunk/matplotlib/lib/matplotlib/projections/geo.py 2009-05-27 16:25:33 UTC (rev 7145) @@ -121,7 +121,7 @@ .scale(0.5 / xscale, 0.5 / yscale) \ .translate(0.5, 0.5) - def get_xaxis_transform(self,which=None): + def get_xaxis_transform(self,which='grid'): assert which in ['tick1','tick2','grid'] return self._xaxis_transform @@ -131,7 +131,7 @@ def get_xaxis_text2_transform(self, pad): return self._xaxis_text2_transform, 'top', 'center' - def get_yaxis_transform(self,which=None): + def get_yaxis_transform(self,which='grid'): assert which in ['tick1','tick2','grid'] return self._yaxis_transform Modified: trunk/matplotlib/lib/matplotlib/projections/polar.py =================================================================== --- trunk/matplotlib/lib/matplotlib/projections/polar.py 2009-05-27 16:25:15 UTC (rev 7144) +++ trunk/matplotlib/lib/matplotlib/projections/polar.py 2009-05-27 16:25:33 UTC (rev 7145) @@ -270,7 +270,7 @@ self._yaxis_transform ) - def get_xaxis_transform(self,which=None): + def get_xaxis_transform(self,which='grid'): assert which in ['tick1','tick2','grid'] return self._xaxis_transform @@ -280,7 +280,7 @@ def get_xaxis_text2_transform(self, pad): return self._xaxis_text2_transform, 'center', 'center' - def get_yaxis_transform(self,which=None): + def get_yaxis_transform(self,which='grid'): assert which in ['tick1','tick2','grid'] return self._yaxis_transform This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2009-05-28 11:54:41
|
Revision: 7150 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7150&view=rev Author: mdboom Date: 2009-05-28 11:54:35 +0000 (Thu, 28 May 2009) Log Message: ----------- Fix some compiler warnings Modified Paths: -------------- trunk/matplotlib/agg24/include/agg_conv_curve.h trunk/matplotlib/src/_png.cpp Modified: trunk/matplotlib/agg24/include/agg_conv_curve.h =================================================================== --- trunk/matplotlib/agg24/include/agg_conv_curve.h 2009-05-28 11:54:18 UTC (rev 7149) +++ trunk/matplotlib/agg24/include/agg_conv_curve.h 2009-05-28 11:54:35 UTC (rev 7150) @@ -2,8 +2,8 @@ // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // -// Permission to copy, use, modify, sell and distribute this software -// is granted provided this copyright notice appears in all copies. +// Permission to copy, use, modify, sell and distribute this software +// is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // @@ -28,31 +28,31 @@ //---------------------------------------------------------------conv_curve - // Curve converter class. Any path storage can have Bezier curves defined - // by their control points. There're two types of curves supported: curve3 + // Curve converter class. Any path storage can have Bezier curves defined + // by their control points. There're two types of curves supported: curve3 // and curve4. Curve3 is a conic Bezier curve with 2 endpoints and 1 control // point. Curve4 has 2 control points (4 points in total) and can be used - // to interpolate more complicated curves. Curve4, unlike curve3 can be used - // to approximate arcs, both circular and elliptical. Curves are approximated - // with straight lines and one of the approaches is just to store the whole - // sequence of vertices that approximate our curve. It takes additional - // memory, and at the same time the consecutive vertices can be calculated - // on demand. + // to interpolate more complicated curves. Curve4, unlike curve3 can be used + // to approximate arcs, both circular and elliptical. Curves are approximated + // with straight lines and one of the approaches is just to store the whole + // sequence of vertices that approximate our curve. It takes additional + // memory, and at the same time the consecutive vertices can be calculated + // on demand. // // Initially, path storages are not suppose to keep all the vertices of the // curves (although, nothing prevents us from doing so). Instead, path_storage // keeps only vertices, needed to calculate a curve on demand. Those vertices - // are marked with special commands. So, if the path_storage contains curves - // (which are not real curves yet), and we render this storage directly, - // all we will see is only 2 or 3 straight line segments (for curve3 and - // curve4 respectively). If we need to see real curves drawn we need to - // include this class into the conversion pipeline. + // are marked with special commands. So, if the path_storage contains curves + // (which are not real curves yet), and we render this storage directly, + // all we will see is only 2 or 3 straight line segments (for curve3 and + // curve4 respectively). If we need to see real curves drawn we need to + // include this class into the conversion pipeline. // - // Class conv_curve recognizes commands path_cmd_curve3 and path_cmd_curve4 - // and converts these vertices into a move_to/line_to sequence. + // Class conv_curve recognizes commands path_cmd_curve3 and path_cmd_curve4 + // and converts these vertices into a move_to/line_to sequence. //----------------------------------------------------------------------- - template<class VertexSource, - class Curve3=curve3, + template<class VertexSource, + class Curve3=curve3, class Curve4=curve4> class conv_curve { public: @@ -64,51 +64,51 @@ m_source(&source), m_last_x(0.0), m_last_y(0.0) {} void attach(VertexSource& source) { m_source = &source; } - void approximation_method(curve_approximation_method_e v) - { + void approximation_method(curve_approximation_method_e v) + { m_curve3.approximation_method(v); m_curve4.approximation_method(v); } - curve_approximation_method_e approximation_method() const - { + curve_approximation_method_e approximation_method() const + { return m_curve4.approximation_method(); } - void approximation_scale(double s) - { - m_curve3.approximation_scale(s); - m_curve4.approximation_scale(s); + void approximation_scale(double s) + { + m_curve3.approximation_scale(s); + m_curve4.approximation_scale(s); } - double approximation_scale() const - { - return m_curve4.approximation_scale(); + double approximation_scale() const + { + return m_curve4.approximation_scale(); } - void angle_tolerance(double v) - { - m_curve3.angle_tolerance(v); - m_curve4.angle_tolerance(v); + void angle_tolerance(double v) + { + m_curve3.angle_tolerance(v); + m_curve4.angle_tolerance(v); } - double angle_tolerance() const - { - return m_curve4.angle_tolerance(); + double angle_tolerance() const + { + return m_curve4.angle_tolerance(); } - void cusp_limit(double v) - { - m_curve3.cusp_limit(v); - m_curve4.cusp_limit(v); + void cusp_limit(double v) + { + m_curve3.cusp_limit(v); + m_curve4.cusp_limit(v); } - double cusp_limit() const - { - return m_curve4.cusp_limit(); + double cusp_limit() const + { + return m_curve4.cusp_limit(); } - void rewind(unsigned path_id); + void rewind(unsigned path_id); unsigned vertex(double* x, double* y); private: @@ -154,10 +154,10 @@ return path_cmd_line_to; } - double ct2_x; - double ct2_y; - double end_x; - double end_y; + double ct2_x = 0.0; + double ct2_y = 0.0; + double end_x = 0.0; + double end_y = 0.0; unsigned cmd = m_source->vertex(x, y); switch(cmd) @@ -165,8 +165,8 @@ case path_cmd_curve3: m_source->vertex(&end_x, &end_y); - m_curve3.init(m_last_x, m_last_y, - *x, *y, + m_curve3.init(m_last_x, m_last_y, + *x, *y, end_x, end_y); m_curve3.vertex(x, y); // First call returns path_cmd_move_to @@ -178,9 +178,9 @@ m_source->vertex(&ct2_x, &ct2_y); m_source->vertex(&end_x, &end_y); - m_curve4.init(m_last_x, m_last_y, - *x, *y, - ct2_x, ct2_y, + m_curve4.init(m_last_x, m_last_y, + *x, *y, + ct2_x, ct2_y, end_x, end_y); m_curve4.vertex(x, y); // First call returns path_cmd_move_to Modified: trunk/matplotlib/src/_png.cpp =================================================================== --- trunk/matplotlib/src/_png.cpp 2009-05-28 11:54:18 UTC (rev 7149) +++ trunk/matplotlib/src/_png.cpp 2009-05-28 11:54:35 UTC (rev 7150) @@ -272,11 +272,11 @@ size_t offset = y*A->strides[0] + x*A->strides[1]; if (bit_depth == 16) { png_uint_16* ptr = &reinterpret_cast<png_uint_16*> (row)[x * dimensions[2]]; - for (png_uint_32 p = 0; p < dimensions[2]; p++) + for (png_uint_32 p = 0; p < (png_uint_32)dimensions[2]; p++) *(float*)(A->data + offset + p*A->strides[2]) = (float)(ptr[p]) / max_value; } else { png_byte* ptr = &(row[x * dimensions[2]]); - for (png_uint_32 p = 0; p < dimensions[2]; p++) + for (png_uint_32 p = 0; p < (png_uint_32)dimensions[2]; p++) { *(float*)(A->data + offset + p*A->strides[2]) = (float)(ptr[p]) / max_value; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <he...@us...> - 2009-05-28 15:59:18
|
Revision: 7154 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7154&view=rev Author: heeres Date: 2009-05-28 15:59:12 +0000 (Thu, 28 May 2009) Log Message: ----------- mplot3d: add examples, fix NaN bug Modified Paths: -------------- trunk/matplotlib/lib/mpl_toolkits/mplot3d/__init__.py trunk/matplotlib/lib/mpl_toolkits/mplot3d/axes3d.py Added Paths: ----------- trunk/matplotlib/examples/mplot3d/contour.py trunk/matplotlib/examples/mplot3d/contourf.py trunk/matplotlib/examples/mplot3d/polys.py trunk/matplotlib/examples/mplot3d/scatter.py trunk/matplotlib/examples/mplot3d/surface.py trunk/matplotlib/examples/mplot3d/wire.py Added: trunk/matplotlib/examples/mplot3d/contour.py =================================================================== --- trunk/matplotlib/examples/mplot3d/contour.py (rev 0) +++ trunk/matplotlib/examples/mplot3d/contour.py 2009-05-28 15:59:12 UTC (rev 7154) @@ -0,0 +1,12 @@ +from mpl_toolkits.mplot3d import axes3d +import pylab +import random + +fig = pylab.figure() +ax = axes3d.Axes3D(fig) +X, Y, Z = axes3d.get_test_data(0.05) +cset = ax.contour3D(X, Y, Z) +ax.clabel(cset, fontsize=9, inline=1) + +pylab.show() + Added: trunk/matplotlib/examples/mplot3d/contourf.py =================================================================== --- trunk/matplotlib/examples/mplot3d/contourf.py (rev 0) +++ trunk/matplotlib/examples/mplot3d/contourf.py 2009-05-28 15:59:12 UTC (rev 7154) @@ -0,0 +1,12 @@ +from mpl_toolkits.mplot3d import axes3d +import pylab +import random + +fig = pylab.figure() +ax = axes3d.Axes3D(fig) +X, Y, Z = axes3d.get_test_data(0.05) +cset = ax.contourf3D(X, Y, Z) +ax.clabel(cset, fontsize=9, inline=1) + +pylab.show() + Added: trunk/matplotlib/examples/mplot3d/polys.py =================================================================== --- trunk/matplotlib/examples/mplot3d/polys.py (rev 0) +++ trunk/matplotlib/examples/mplot3d/polys.py 2009-05-28 15:59:12 UTC (rev 7154) @@ -0,0 +1,31 @@ +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) + +cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.6) + +xs = np.arange(0, 10, 0.4) +verts = [] +zs = [0.0, 1.0, 2.0, 3.0] +for z in zs: + ys = [random.random() for x in xs] + ys[0], ys[-1] = 0, 0 + verts.append(zip(xs, ys)) + +poly = PolyCollection(verts, facecolors = [cc('r'), cc('g'), cc('b'), + cc('y')]) +poly.set_alpha(0.7) +ax.add_collection(poly, zs=zs, dir='y') + +ax.set_xlim(0, 10) +ax.set_ylim(-1, 4) +ax.set_zlim(0, 1) + +pylab.show() + Added: trunk/matplotlib/examples/mplot3d/scatter.py =================================================================== --- trunk/matplotlib/examples/mplot3d/scatter.py (rev 0) +++ trunk/matplotlib/examples/mplot3d/scatter.py 2009-05-28 15:59:12 UTC (rev 7154) @@ -0,0 +1,21 @@ +from mpl_toolkits.mplot3d import Axes3D +import pylab +import random + +fig = pylab.figure() +ax = Axes3D(fig) +n = 100 +for c, zl, zh in [('r', -50, -25), ('b', -30, -5)]: + xs, ys, zs = zip(* + [(random.randrange(23, 32), + random.randrange(100), + random.randrange(zl, zh) + ) for i in range(n)]) + ax.scatter3D(xs, ys, zs, c=c) + +ax.set_xlabel('X Label') +ax.set_ylabel('Y Label') +ax.set_zlabel('Z Label') + +pylab.show() + Added: trunk/matplotlib/examples/mplot3d/surface.py =================================================================== --- trunk/matplotlib/examples/mplot3d/surface.py (rev 0) +++ trunk/matplotlib/examples/mplot3d/surface.py 2009-05-28 15:59:12 UTC (rev 7154) @@ -0,0 +1,16 @@ +from mpl_toolkits.mplot3d import Axes3D +import pylab +import random +import numpy as np + +fig = pylab.figure() +ax = Axes3D(fig) +X = np.arange(-5, 5, 0.5) +Y = np.arange(-5, 5, 0.5) +X, Y = np.meshgrid(X, Y) +R = np.sqrt(X**2 + Y**2) +Z = np.sin(R) +ax.plot_surface(X, Y, Z, rstride=1, cstride=1, color='forestgreen') + +pylab.show() + Added: trunk/matplotlib/examples/mplot3d/wire.py =================================================================== --- trunk/matplotlib/examples/mplot3d/wire.py (rev 0) +++ trunk/matplotlib/examples/mplot3d/wire.py 2009-05-28 15:59:12 UTC (rev 7154) @@ -0,0 +1,12 @@ +from mpl_toolkits.mplot3d import axes3d +import pylab +import random +import numpy as np + +fig = pylab.figure() +ax = axes3d.Axes3D(fig) +X, Y, Z = axes3d.get_test_data(0.05) +ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10) + +pylab.show() + Modified: trunk/matplotlib/lib/mpl_toolkits/mplot3d/__init__.py =================================================================== --- trunk/matplotlib/lib/mpl_toolkits/mplot3d/__init__.py 2009-05-28 14:49:14 UTC (rev 7153) +++ trunk/matplotlib/lib/mpl_toolkits/mplot3d/__init__.py 2009-05-28 15:59:12 UTC (rev 7154) @@ -0,0 +1 @@ +from axes3d import Axes3D Modified: trunk/matplotlib/lib/mpl_toolkits/mplot3d/axes3d.py =================================================================== --- trunk/matplotlib/lib/mpl_toolkits/mplot3d/axes3d.py 2009-05-28 14:49:14 UTC (rev 7153) +++ trunk/matplotlib/lib/mpl_toolkits/mplot3d/axes3d.py 2009-05-28 15:59:12 UTC (rev 7154) @@ -539,6 +539,9 @@ rstride = kwargs.pop('rstride', 10) cstride = kwargs.pop('cstride', 10) + color = kwargs.pop('color', 'b') + color = np.array(colorConverter.to_rgba(color)) + polys = [] boxes = [] for rs in np.arange(0,rows-1,rstride): @@ -567,8 +570,10 @@ shade.append(np.dot(n,[-1,-1,0.5])) lines.append((box[0],n+box[0])) - color = np.array([0,0,1,1]) - norm = Normalize(min(shade),max(shade)) + shade = np.array(shade) + mask = ~np.isnan(shade) + norm = Normalize(min(shade[mask]), max(shade[mask])) + colors = [color * (0.5+norm(v)*0.5) for v in shade] for c in colors: c[3] = 1 polyc = art3d.Poly3DCollection(polys, facecolors=colors, *args, **kwargs) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ds...@us...> - 2009-05-28 16:11:21
|
Revision: 7155 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7155&view=rev Author: dsdale Date: 2009-05-28 16:11:16 +0000 (Thu, 28 May 2009) Log Message: ----------- handle scroll wheel events in Qt4 backend Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/backends/backend_qt4.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-05-28 15:59:12 UTC (rev 7154) +++ trunk/matplotlib/CHANGELOG 2009-05-28 16:11:16 UTC (rev 7155) @@ -1,3 +1,6 @@ +2009-05-28 Applied fbianco's patch to handle scroll wheel events in + the qt4 backend - DSD + 2009-05-26 Add support for "axis spines" to have arbitrary location. -ADS 2009-05-20 Add an empty matplotlibrc to the tests/ directory so that running Modified: trunk/matplotlib/lib/matplotlib/backends/backend_qt4.py =================================================================== --- trunk/matplotlib/lib/matplotlib/backends/backend_qt4.py 2009-05-28 15:59:12 UTC (rev 7154) +++ trunk/matplotlib/lib/matplotlib/backends/backend_qt4.py 2009-05-28 16:11:16 UTC (rev 7155) @@ -136,6 +136,16 @@ FigureCanvasBase.button_release_event( self, x, y, button ) if DEBUG: print 'button released' + def wheelEvent( self, event ): + x = event.x() + # flipy so y=0 is bottom of canvas + y = self.figure.bbox.height - event.y() + # from QWheelEvent::delta doc + steps = event.delta()/120 + if (event.orientation() == Qt.Qt.Vertical): + FigureCanvasBase.scroll_event( self, x, y, steps) + if DEBUG: print 'scroll event : delta = %i, steps = %i ' % (event.delta(),steps) + def keyPressEvent( self, event ): key = self._get_key( event ) FigureCanvasBase.key_press_event( self, key ) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2009-05-29 02:30:57
|
Revision: 7160 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7160&view=rev Author: jdh2358 Date: 2009-05-29 02:08:15 +0000 (Fri, 29 May 2009) Log Message: ----------- added spine autodocs Modified Paths: -------------- trunk/matplotlib/doc/api/index.rst trunk/matplotlib/examples/pylab_examples/axhspan_demo.py Added Paths: ----------- trunk/matplotlib/doc/api/spine_api.rst Modified: trunk/matplotlib/doc/api/index.rst =================================================================== --- trunk/matplotlib/doc/api/index.rst 2009-05-28 18:02:49 UTC (rev 7159) +++ trunk/matplotlib/doc/api/index.rst 2009-05-29 02:08:15 UTC (rev 7160) @@ -30,5 +30,6 @@ mlab_api.rst path_api.rst pyplot_api.rst + spine_api.rst ticker_api.rst index_backend_api.rst Added: trunk/matplotlib/doc/api/spine_api.rst =================================================================== --- trunk/matplotlib/doc/api/spine_api.rst (rev 0) +++ trunk/matplotlib/doc/api/spine_api.rst 2009-05-29 02:08:15 UTC (rev 7160) @@ -0,0 +1,12 @@ +***************** +matplotlib spine +***************** + + +:mod:`matplotlib.spine` +====================== + +.. automodule:: matplotlib.spine + :members: + :undoc-members: + :show-inheritance: Modified: trunk/matplotlib/examples/pylab_examples/axhspan_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/axhspan_demo.py 2009-05-28 18:02:49 UTC (rev 7159) +++ trunk/matplotlib/examples/pylab_examples/axhspan_demo.py 2009-05-29 02:08:15 UTC (rev 7160) @@ -11,7 +11,7 @@ # draw a default hline at y=1 that spans the xrange l = plt.axhline(y=1) -# draw a default vline at x=1 that spans the xrange +# draw a default vline at x=1 that spans the yrange l = plt.axvline(x=1) # draw a thick blue vline at x=0 that spans the the upper quadrant of This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lee...@us...> - 2009-05-29 03:52:40
|
Revision: 7162 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7162&view=rev Author: leejjoon Date: 2009-05-29 03:52:32 +0000 (Fri, 29 May 2009) Log Message: ----------- Fix axes_grid toolkit to work with the spine patch Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/mpl_toolkits/axes_grid/axislines.py trunk/matplotlib/lib/mpl_toolkits/axes_grid/parasite_axes.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-05-29 02:33:06 UTC (rev 7161) +++ trunk/matplotlib/CHANGELOG 2009-05-29 03:52:32 UTC (rev 7162) @@ -1,4 +1,6 @@ -2009-05-28 Applied fbianco's patch to handle scroll wheel events in +2009-05-28 Fix axes_grid toolkit to work with spine patch by ADS. - JJL + +2009-05-28 Applied fbianco's patch to handle scroll wheel events in the qt4 backend - DSD 2009-05-26 Add support for "axis spines" to have arbitrary location. -ADS Modified: trunk/matplotlib/lib/mpl_toolkits/axes_grid/axislines.py =================================================================== --- trunk/matplotlib/lib/mpl_toolkits/axes_grid/axislines.py 2009-05-29 02:33:06 UTC (rev 7161) +++ trunk/matplotlib/lib/mpl_toolkits/axes_grid/axislines.py 2009-05-29 03:52:32 UTC (rev 7162) @@ -1249,12 +1249,16 @@ b = not self._axisline_on if b: self._axisline_on = True - self.frame.set_visible(False) + #self.frame.set_visible(False) + for s in self.spines.values(): + s.artist.set_visible(False) self.xaxis.set_visible(False) self.yaxis.set_visible(False) else: self._axisline_on = False - self.frame.set_visible(True) + #self.frame.set_visible(True) + for s in self.spines.values(): + s.artist.set_visible(True) self.xaxis.set_visible(True) self.yaxis.set_visible(True) Modified: trunk/matplotlib/lib/mpl_toolkits/axes_grid/parasite_axes.py =================================================================== --- trunk/matplotlib/lib/mpl_toolkits/axes_grid/parasite_axes.py 2009-05-29 02:33:06 UTC (rev 7161) +++ trunk/matplotlib/lib/mpl_toolkits/axes_grid/parasite_axes.py 2009-05-29 03:52:32 UTC (rev 7162) @@ -48,14 +48,15 @@ class ParasiteAxesAuxTrans(ParasiteAxes): - def __init__(self, parent_axes, aux_transform, viewlim_mode=None): + def __init__(self, parent_axes, aux_transform, viewlim_mode=None, + **kwargs): self.transAux = aux_transform #self._viewlim_mode = viewlim_mode self.set_viewlim_mode(viewlim_mode) - super(ParasiteAxesAuxTrans, self).__init__(parent_axes) + super(ParasiteAxesAuxTrans, self).__init__(parent_axes, **kwargs) def _set_lim_and_transforms(self): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ds...@us...> - 2009-05-29 21:46:20
|
Revision: 7165 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7165&view=rev Author: dsdale Date: 2009-05-29 21:45:55 +0000 (Fri, 29 May 2009) Log Message: ----------- improve the animation_blit_qt4 example Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/examples/animation/animation_blit_qt4.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-05-29 18:24:46 UTC (rev 7164) +++ trunk/matplotlib/CHANGELOG 2009-05-29 21:45:55 UTC (rev 7165) @@ -1,3 +1,7 @@ +2009-05-29 Improved the animation_blit_qt4 example, which was a mix + of the object-oriented and pylab interfaces. It is now + strictly object-oriented - DSD + 2009-05-28 Fix axes_grid toolkit to work with spine patch by ADS. - JJL 2009-05-28 Applied fbianco's patch to handle scroll wheel events in Modified: trunk/matplotlib/examples/animation/animation_blit_qt4.py =================================================================== --- trunk/matplotlib/examples/animation/animation_blit_qt4.py 2009-05-29 18:24:46 UTC (rev 7164) +++ trunk/matplotlib/examples/animation/animation_blit_qt4.py 2009-05-29 21:45:55 UTC (rev 7165) @@ -1,68 +1,75 @@ # For detailed comments on animation and the techniqes used here, see # the wiki entry http://www.scipy.org/Cookbook/Matplotlib/Animations -import os, sys -import matplotlib -matplotlib.use('Qt4Agg') # qt4 example +import os +import sys +#import matplotlib +#matplotlib.use('Qt4Agg') +from matplotlib.figure import Figure +from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas + from PyQt4 import QtCore, QtGui ITERS = 1000 -import pylab as p -import numpy as npy +import numpy as np import time -class BlitQT(QtCore.QObject): +class BlitQT(FigureCanvas): + def __init__(self): - self.ax = p.subplot(111) - self.canvas = self.ax.figure.canvas + FigureCanvas.__init__(self, Figure()) - # By making this a child of the canvas we make sure that it is - # destroyed first and avoids a possible exception when the user clicks - # on the window's close box. - QtCore.QObject.__init__(self, self.canvas) + self.ax = self.figure.add_subplot(111) + self.ax.grid() + self.draw() + self.old_size = self.ax.bbox.width, self.ax.bbox.height + self.ax_background = self.copy_from_bbox(self.ax.bbox) self.cnt = 0 - # create the initial line - self.x = npy.arange(0,2*npy.pi,0.01) - self.line, = p.plot(self.x, npy.sin(self.x), animated=True, lw=2) + self.x = np.arange(0,2*np.pi,0.01) + self.sin_line, = self.ax.plot(self.x, np.sin(self.x), animated=True) + self.cos_line, = self.ax.plot(self.x, np.cos(self.x), animated=True) + self.draw() - self.background = None - self.old_size = 0, 0 + self.tstart = time.time() + self.startTimer(10) def timerEvent(self, evt): - # See if the size has changed since last time round. current_size = self.ax.bbox.width, self.ax.bbox.height - if self.old_size != current_size: self.old_size = current_size - self.background = self.canvas.copy_from_bbox(self.ax.bbox) + self.ax.clear() + self.ax.grid() + self.draw() + self.ax_background = self.copy_from_bbox(self.ax.bbox) - # restore the clean slate background - self.canvas.restore_region(self.background) + self.restore_region(self.ax_background, bbox=self.ax.bbox) + # update the data - self.line.set_ydata(npy.sin(self.x+self.cnt/10.0)) + self.sin_line.set_ydata(np.sin(self.x+self.cnt/10.0)) + self.cos_line.set_ydata(np.cos(self.x+self.cnt/10.0)) # just draw the animated artist - self.ax.draw_artist(self.line) + self.ax.draw_artist(self.sin_line) + self.ax.draw_artist(self.cos_line) # just redraw the axes rectangle - self.canvas.blit(self.ax.bbox) + self.blit(self.ax.bbox) + if self.cnt == 0: + # TODO: this shouldn't be necessary, but if it is excluded the + # canvas outside the axes is not initially painted. + self.draw() if self.cnt==ITERS: # print the timing info and quit print 'FPS:' , ITERS/(time.time()-self.tstart) sys.exit() - else: self.cnt += 1 -p.subplots_adjust(left=0.3, bottom=0.3) # check for flipy bugs -p.grid() # to ensure proper background restore +app = QtGui.QApplication(sys.argv) +widget = BlitQT() +widget.show() -app = BlitQT() -# for profiling -app.tstart = time.time() -app.startTimer(0) - -p.show() +sys.exit(app.exec_()) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <as...@us...> - 2009-06-01 21:41:46
|
Revision: 7168 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7168&view=rev Author: astraw Date: 2009-06-01 21:41:21 +0000 (Mon, 01 Jun 2009) Log Message: ----------- add cla() support for spines Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/axes.py trunk/matplotlib/lib/matplotlib/spines.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-06-01 17:19:05 UTC (rev 7167) +++ trunk/matplotlib/CHANGELOG 2009-06-01 21:41:21 UTC (rev 7168) @@ -1,3 +1,5 @@ +2009-06-01 cla() support for spines - ADS + 2009-06-01 Removed support for gtk < 2.4. - EF 2009-05-29 Improved the animation_blit_qt4 example, which was a mix Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2009-06-01 17:19:05 UTC (rev 7167) +++ trunk/matplotlib/lib/matplotlib/axes.py 2009-06-01 21:41:21 UTC (rev 7168) @@ -906,6 +906,8 @@ # Note: this is called by Axes.__init__() self.xaxis.cla() self.yaxis.cla() + for name,spine in self.spines.iteritems(): + spine.cla() self.ignore_existing_data_limits = True self.callbacks = cbook.CallbackRegistry(('xlim_changed', Modified: trunk/matplotlib/lib/matplotlib/spines.py =================================================================== --- trunk/matplotlib/lib/matplotlib/spines.py 2009-06-01 17:19:05 UTC (rev 7167) +++ trunk/matplotlib/lib/matplotlib/spines.py 2009-06-01 21:41:21 UTC (rev 7168) @@ -69,6 +69,12 @@ if self.axis is not None: self.axis.cla() + def cla(self): + 'Clear the current spine' + self._position = None # clear position + if self.axis is not None: + self.axis.cla() + @allow_rasterization def draw(self,renderer): "draw everything that belongs to the spine" This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <as...@us...> - 2009-06-01 21:41:48
|
Revision: 7170 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7170&view=rev Author: astraw Date: 2009-06-01 21:41:46 +0000 (Mon, 01 Jun 2009) Log Message: ----------- Spine is now derived from Patch Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/examples/api/custom_projection_example.py trunk/matplotlib/examples/pylab_examples/spine_placement_demo.py trunk/matplotlib/lib/matplotlib/axes.py trunk/matplotlib/lib/matplotlib/projections/geo.py trunk/matplotlib/lib/matplotlib/projections/polar.py trunk/matplotlib/lib/matplotlib/spines.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-06-01 21:41:31 UTC (rev 7169) +++ trunk/matplotlib/CHANGELOG 2009-06-01 21:41:46 UTC (rev 7170) @@ -1,3 +1,5 @@ +2009-06-01 Spine is now derived from Patch - ADS + 2009-06-01 use cbook.is_string_like() instead of isinstance() for spines - ADS 2009-06-01 cla() support for spines - ADS Modified: trunk/matplotlib/examples/api/custom_projection_example.py =================================================================== --- trunk/matplotlib/examples/api/custom_projection_example.py 2009-06-01 21:41:31 UTC (rev 7169) +++ trunk/matplotlib/examples/api/custom_projection_example.py 2009-06-01 21:41:46 UTC (rev 7170) @@ -237,7 +237,8 @@ return Circle((0.5, 0.5), 0.5) def _gen_axes_spines(self): - return {'hammer':mspines.Spine(self,'hammer',Circle((0.5, 0.5), 0.5))} + return {'hammer':mspines.Spine.circular_spine(self, + (0.5, 0.5), 0.5)} # Prevent the user from applying scales to one or both of the # axes. In this particular case, scaling the axes wouldn't make Modified: trunk/matplotlib/examples/pylab_examples/spine_placement_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/spine_placement_demo.py 2009-06-01 21:41:31 UTC (rev 7169) +++ trunk/matplotlib/examples/pylab_examples/spine_placement_demo.py 2009-06-01 21:41:46 UTC (rev 7170) @@ -12,7 +12,7 @@ if loc in ['left','bottom']: spine.set_position(('outward',10)) # outward by 10 points elif loc in ['right','top']: - spine.set_color('none') # don't draw spine + spine.set_edgecolor('none') # don't draw spine else: raise ValueError('unknown spine location: %s'%loc) @@ -34,9 +34,9 @@ ax.set_title('centered spines') ax.plot(x,y) ax.spines['left'].set_position('center') -ax.spines['right'].set_color('none') +ax.spines['right'].set_edgecolor('none') ax.spines['bottom'].set_position('center') -ax.spines['top'].set_color('none') +ax.spines['top'].set_edgecolor('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') @@ -44,9 +44,9 @@ ax.set_title('zeroed spines') ax.plot(x,y) ax.spines['left'].set_position('zero') -ax.spines['right'].set_color('none') +ax.spines['right'].set_edgecolor('none') ax.spines['bottom'].set_position('zero') -ax.spines['top'].set_color('none') +ax.spines['top'].set_edgecolor('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') @@ -54,9 +54,9 @@ ax.set_title('spines at axes (0.6, 0.1)') ax.plot(x,y) ax.spines['left'].set_position(('axes',0.6)) -ax.spines['right'].set_color('none') +ax.spines['right'].set_edgecolor('none') ax.spines['bottom'].set_position(('axes',0.1)) -ax.spines['top'].set_color('none') +ax.spines['top'].set_edgecolor('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') @@ -64,9 +64,9 @@ ax.set_title('spines at data (1,2)') ax.plot(x,y) ax.spines['left'].set_position(('data',1)) -ax.spines['right'].set_color('none') +ax.spines['right'].set_edgecolor('none') ax.spines['bottom'].set_position(('data',2)) -ax.spines['top'].set_color('none') +ax.spines['top'].set_edgecolor('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') @@ -77,7 +77,7 @@ if loc in spines: spine.set_position(('outward',10)) # outward by 10 points else: - spine.set_color('none') # don't draw spine + spine.set_edgecolor('none') # don't draw spine # turn off ticks where there is no spine if 'left' in spines: Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2009-06-01 21:41:31 UTC (rev 7169) +++ trunk/matplotlib/lib/matplotlib/axes.py 2009-06-01 21:41:46 UTC (rev 7170) @@ -891,14 +891,10 @@ Intended to be overridden by new projection types. """ return { - 'left':mspines.Spine(self,'left', - mlines.Line2D((0.0, 0.0), (0.0, 1.0))), - 'right':mspines.Spine(self,'right', - mlines.Line2D((1.0, 1.0), (0.0, 1.0))), - 'bottom':mspines.Spine(self,'bottom', - mlines.Line2D((0.0, 1.0), (0.0, 0.0))), - 'top':mspines.Spine(self,'top', - mlines.Line2D((0.0, 1.0), (1.0, 1.0))), + 'left':mspines.Spine.linear_spine(self,'left'), + 'right':mspines.Spine.linear_spine(self,'right'), + 'bottom':mspines.Spine.linear_spine(self,'bottom'), + 'top':mspines.Spine.linear_spine(self,'top'), } def cla(self): Modified: trunk/matplotlib/lib/matplotlib/projections/geo.py =================================================================== --- trunk/matplotlib/lib/matplotlib/projections/geo.py 2009-06-01 21:41:31 UTC (rev 7169) +++ trunk/matplotlib/lib/matplotlib/projections/geo.py 2009-06-01 21:41:46 UTC (rev 7170) @@ -145,7 +145,8 @@ return Circle((0.5, 0.5), 0.5) def _gen_axes_spines(self): - return {'geo':mspines.Spine(self,'geo',Circle((0.5, 0.5), 0.5))} + return {'geo':mspines.Spine.circular_spine(self, + (0.5, 0.5), 0.5)} def set_yscale(self, *args, **kwargs): if args[0] != 'linear': Modified: trunk/matplotlib/lib/matplotlib/projections/polar.py =================================================================== --- trunk/matplotlib/lib/matplotlib/projections/polar.py 2009-06-01 21:41:31 UTC (rev 7169) +++ trunk/matplotlib/lib/matplotlib/projections/polar.py 2009-06-01 21:41:46 UTC (rev 7170) @@ -294,7 +294,8 @@ return Circle((0.5, 0.5), 0.5) def _gen_axes_spines(self): - return {'polar':mspines.Spine(self,'polar',Circle((0.5, 0.5), 0.5))} + return {'polar':mspines.Spine.circular_spine(self, + (0.5, 0.5), 0.5)} def set_rmax(self, rmax): self.viewLim.y0 = 0 Modified: trunk/matplotlib/lib/matplotlib/spines.py =================================================================== --- trunk/matplotlib/lib/matplotlib/spines.py 2009-06-01 21:41:31 UTC (rev 7169) +++ trunk/matplotlib/lib/matplotlib/spines.py 2009-06-01 21:41:46 UTC (rev 7170) @@ -8,10 +8,11 @@ import matplotlib.transforms as mtransforms import matplotlib.lines as mlines import matplotlib.patches as mpatches +import matplotlib.path as mpath import matplotlib.cbook as cbook import warnings -class Spine(martist.Artist): +class Spine(mpatches.Patch): """an axis spine -- the line noting the data area boundaries Spines are the lines connecting the axis tick marks and noting the @@ -20,39 +21,98 @@ for more information. The default position is ``('outward',0)``. + + Spines are subclasses of class:`~matplotlib.patches.Patch`, and + inherit much of their behavior. + + Spines draw a line or a circle, depending if + function:`~matplotlib.spines.Spine.set_patch_line` or + function:`~matplotlib.spines.Spine.set_patch_circle` has been + called. Line-like is the default. + """ def __str__(self): return "Spine" - def __init__(self,axes,spine_type,artist): + def __init__(self,axes,spine_type,path,**kwargs): """ - *axes* : the Axes instance containing the spine - *spine_type* : a string specifying the spine type - - *artist* : the artist instance used to draw the spine + - *path* : the path instance used to draw the spine + + Valid kwargs are: + %(Patch)s """ - martist.Artist.__init__(self) + super(Spine,self).__init__(**kwargs) self.axes = axes self.set_figure(self.axes.figure) self.spine_type = spine_type - self.artist = artist - self.color = rcParams['axes.edgecolor'] + self.set_facecolor('none') + self.set_edgecolor( rcParams['axes.edgecolor'] ) + self.set_linewidth(rcParams['axes.linewidth']) self.axis = None - if isinstance(self.artist,mlines.Line2D): - self.artist.set_color(self.color) - self.artist.set_linewidth(rcParams['axes.linewidth']) - elif isinstance(self.artist,mpatches.Patch): - self.artist.set_facecolor('none') - self.artist.set_edgecolor(self.color) - self.artist.set_linewidth(rcParams['axes.linewidth']) - self.artist.set_zorder(2.5) - self.artist.set_transform(self.axes.transAxes) # default transform + self.set_zorder(2.5) + self.set_transform(self.axes.transAxes) # default transform # Defer initial position determination. (Not much support for # non-rectangular axes is currently implemented, and this lets # them pass through the spines machinery without errors.) self._position = None + assert isinstance(path,matplotlib.path.Path) + self._path = path + # To support drawing both linear and circular spines, this + # class implements Patch behavior two ways. If + # self._patch_type == 'line', behave like a mpatches.PathPatch + # instance. If self._patch_type == 'circle', behave like a + # mpatches.Ellipse instance. + self._patch_type = 'line' + + # Behavior copied from mpatches.Ellipse: + # Note: This cannot be calculated until this is added to an Axes + self._patch_transform = mtransforms.IdentityTransform() + __init__.__doc__ = cbook.dedent(__init__.__doc__) % martist.kwdocd + + def set_patch_circle(self,center,radius): + """set the spine to be circular""" + self._patch_type = 'circle' + self._center = center + self._width = radius*2 + self._height = radius*2 + self._angle = 0 + + def set_patch_line(self): + """set the spine to be linear""" + self._patch_type = 'line' + + # Behavior copied from mpatches.Ellipse: + def _recompute_transform(self): + """NOTE: This cannot be called until after this has been added + to an Axes, otherwise unit conversion will fail. This + maxes it very important to call the accessor method and + not directly access the transformation member variable. + """ + assert self._patch_type == 'circle' + center = (self.convert_xunits(self._center[0]), + self.convert_yunits(self._center[1])) + width = self.convert_xunits(self._width) + height = self.convert_yunits(self._height) + self._patch_transform = mtransforms.Affine2D() \ + .scale(width * 0.5, height * 0.5) \ + .rotate_deg(self._angle) \ + .translate(*center) + + def get_patch_transform(self): + if self._patch_type == 'circle': + self._recompute_transform() + return self._patch_transform + else: + return super(Spine,self).get_patch_transform() + + def get_path(self): + return self._path + def _ensure_position_is_set(self): if self._position is None: # default position @@ -76,14 +136,6 @@ if self.axis is not None: self.axis.cla() - @allow_rasterization - def draw(self,renderer): - "draw everything that belongs to the spine" - if self.color=='none': - # don't draw invisible spines - return - self.artist.draw(renderer) - def _calc_offset_transform(self): """calculate the offset transform performed by the spine""" self._ensure_position_is_set() @@ -176,7 +228,7 @@ elif self.spine_type in ['bottom','top']: t2 = mtransforms.blended_transform_factory(self.axes.transAxes, t) - self.artist.set_transform(t2) + self.set_transform(t2) if self.axis is not None: self.axis.cla() @@ -223,17 +275,31 @@ else: raise ValueError("unknown spine_transform type: %s"%what) - def set_color(self,value): - """set the color of the spine artist + @classmethod + def linear_spine(cls, axes, spine_type, **kwargs): + """ + (staticmethod) Returns a linear :class:`Spine`. + """ + if spine_type=='left': + path = mpath.Path([(0.0, 0.0), (0.0, 1.0)]) + elif spine_type=='right': + path = mpath.Path([(1.0, 0.0), (1.0, 1.0)]) + elif spine_type=='bottom': + path = mpath.Path([(0.0, 0.0), (1.0, 0.0)]) + elif spine_type=='top': + path = mpath.Path([(0.0, 1.0), (1.0, 1.0)]) + else: + raise ValueError('unable to make path for spine "%s"'%spine_type) + result = cls(axes,spine_type,path,**kwargs) + return result - Note: a value of 'none' will cause the artist not to be drawn. + @classmethod + def circular_spine(cls,axes,center,radius,**kwargs): """ - self.color = value - if isinstance(self.artist,mlines.Line2D): - self.artist.set_color(self.color) - elif isinstance(self.artist,mpatches.Patch): - self.artist.set_edgecolor(self.color) - - def get_color(self): - """get the color of the spine artist""" - return self.color + (staticmethod) Returns a circular :class:`Spine`. + """ + path = mpath.Path.unit_circle() + spine_type = 'circle' + result = cls(axes,spine_type,path,**kwargs) + result.set_patch_circle(center,radius) + return result This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <as...@us...> - 2009-06-01 21:42:01
|
Revision: 7169 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7169&view=rev Author: astraw Date: 2009-06-01 21:41:31 +0000 (Mon, 01 Jun 2009) Log Message: ----------- use cbook.is_string_like() instead of isinstance() for spines Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/spines.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2009-06-01 21:41:21 UTC (rev 7168) +++ trunk/matplotlib/CHANGELOG 2009-06-01 21:41:31 UTC (rev 7169) @@ -1,3 +1,5 @@ +2009-06-01 use cbook.is_string_like() instead of isinstance() for spines - ADS + 2009-06-01 cla() support for spines - ADS 2009-06-01 Removed support for gtk < 2.4. - EF Modified: trunk/matplotlib/lib/matplotlib/spines.py =================================================================== --- trunk/matplotlib/lib/matplotlib/spines.py 2009-06-01 21:41:21 UTC (rev 7168) +++ trunk/matplotlib/lib/matplotlib/spines.py 2009-06-01 21:41:31 UTC (rev 7169) @@ -8,6 +8,7 @@ import matplotlib.transforms as mtransforms import matplotlib.lines as mlines import matplotlib.patches as mpatches +import matplotlib.cbook as cbook import warnings class Spine(martist.Artist): @@ -87,7 +88,7 @@ """calculate the offset transform performed by the spine""" self._ensure_position_is_set() position = self._position - if isinstance(position,basestring): + if cbook.is_string_like(position): if position=='center': position = ('axes',0.5) elif position=='zero': This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <as...@us...> - 2009-06-01 22:39:54
|
Revision: 7172 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7172&view=rev Author: astraw Date: 2009-06-01 22:39:49 +0000 (Mon, 01 Jun 2009) Log Message: ----------- Add set_color() convenience method to Spine class Modified Paths: -------------- trunk/matplotlib/examples/pylab_examples/spine_placement_demo.py trunk/matplotlib/lib/matplotlib/spines.py Modified: trunk/matplotlib/examples/pylab_examples/spine_placement_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/spine_placement_demo.py 2009-06-01 22:20:26 UTC (rev 7171) +++ trunk/matplotlib/examples/pylab_examples/spine_placement_demo.py 2009-06-01 22:39:49 UTC (rev 7172) @@ -12,7 +12,7 @@ if loc in ['left','bottom']: spine.set_position(('outward',10)) # outward by 10 points elif loc in ['right','top']: - spine.set_edgecolor('none') # don't draw spine + spine.set_color('none') # don't draw spine else: raise ValueError('unknown spine location: %s'%loc) @@ -34,9 +34,9 @@ ax.set_title('centered spines') ax.plot(x,y) ax.spines['left'].set_position('center') -ax.spines['right'].set_edgecolor('none') +ax.spines['right'].set_color('none') ax.spines['bottom'].set_position('center') -ax.spines['top'].set_edgecolor('none') +ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') @@ -44,9 +44,9 @@ ax.set_title('zeroed spines') ax.plot(x,y) ax.spines['left'].set_position('zero') -ax.spines['right'].set_edgecolor('none') +ax.spines['right'].set_color('none') ax.spines['bottom'].set_position('zero') -ax.spines['top'].set_edgecolor('none') +ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') @@ -54,9 +54,9 @@ ax.set_title('spines at axes (0.6, 0.1)') ax.plot(x,y) ax.spines['left'].set_position(('axes',0.6)) -ax.spines['right'].set_edgecolor('none') +ax.spines['right'].set_color('none') ax.spines['bottom'].set_position(('axes',0.1)) -ax.spines['top'].set_edgecolor('none') +ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') @@ -64,9 +64,9 @@ ax.set_title('spines at data (1,2)') ax.plot(x,y) ax.spines['left'].set_position(('data',1)) -ax.spines['right'].set_edgecolor('none') +ax.spines['right'].set_color('none') ax.spines['bottom'].set_position(('data',2)) -ax.spines['top'].set_edgecolor('none') +ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') @@ -77,7 +77,7 @@ if loc in spines: spine.set_position(('outward',10)) # outward by 10 points else: - spine.set_edgecolor('none') # don't draw spine + spine.set_color('none') # don't draw spine # turn off ticks where there is no spine if 'left' in spines: Modified: trunk/matplotlib/lib/matplotlib/spines.py =================================================================== --- trunk/matplotlib/lib/matplotlib/spines.py 2009-06-01 22:20:26 UTC (rev 7171) +++ trunk/matplotlib/lib/matplotlib/spines.py 2009-06-01 22:39:49 UTC (rev 7172) @@ -303,3 +303,18 @@ result = cls(axes,spine_type,path,**kwargs) result.set_patch_circle(center,radius) return result + + def set_color(self, c): + """ + Set the edgecolor. + + ACCEPTS: matplotlib color arg or sequence of rgba tuples + + .. seealso:: + + :meth:`set_facecolor`, :meth:`set_edgecolor` + For setting the edge or face color individually. + """ + # The facecolor of a spine is always 'none' by default -- let + # the user change it manually if desired. + self.set_edgecolor(c) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |