You can subscribe to this list here.
| 2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
(115) |
Aug
(120) |
Sep
(137) |
Oct
(170) |
Nov
(461) |
Dec
(263) |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2008 |
Jan
(120) |
Feb
(74) |
Mar
(35) |
Apr
(74) |
May
(245) |
Jun
(356) |
Jul
(240) |
Aug
(115) |
Sep
(78) |
Oct
(225) |
Nov
(98) |
Dec
(271) |
| 2009 |
Jan
(132) |
Feb
(84) |
Mar
(74) |
Apr
(56) |
May
(90) |
Jun
(79) |
Jul
(83) |
Aug
(296) |
Sep
(214) |
Oct
(76) |
Nov
(82) |
Dec
(66) |
| 2010 |
Jan
(46) |
Feb
(58) |
Mar
(51) |
Apr
(77) |
May
(58) |
Jun
(126) |
Jul
(128) |
Aug
(64) |
Sep
(50) |
Oct
(44) |
Nov
(48) |
Dec
(54) |
| 2011 |
Jan
(68) |
Feb
(52) |
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(1) |
| 2018 |
Jan
|
Feb
|
Mar
|
Apr
|
May
(1) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
|
From: <jd...@us...> - 2009-08-20 23:11:53
|
Revision: 7511
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7511&view=rev
Author: jdh2358
Date: 2009-08-20 23:11:44 +0000 (Thu, 20 Aug 2009)
Log Message:
-----------
make autodateformatter customizable
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/examples/pylab_examples/demo_ribbon_box.py
trunk/matplotlib/lib/matplotlib/dates.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2009-08-20 16:19:22 UTC (rev 7510)
+++ trunk/matplotlib/CHANGELOG 2009-08-20 23:11:44 UTC (rev 7511)
@@ -1,3 +1,6 @@
+2009-08-20 Added scaled dict to AutoDateFormatter for customized
+ scales - JDH
+
2009-08-15 Pyplot interface: the current image is now tracked at the
figure and axes level, addressing tracker item 1656374. - EF
Modified: trunk/matplotlib/examples/pylab_examples/demo_ribbon_box.py
===================================================================
--- trunk/matplotlib/examples/pylab_examples/demo_ribbon_box.py 2009-08-20 16:19:22 UTC (rev 7510)
+++ trunk/matplotlib/examples/pylab_examples/demo_ribbon_box.py 2009-08-20 23:11:44 UTC (rev 7511)
@@ -136,5 +136,6 @@
ax.set_xlim(years[0]-0.5, years[-1]+0.5)
ax.set_ylim(0, 10000)
+ fig.savefig('ribbon_box.png')
plt.show()
Modified: trunk/matplotlib/lib/matplotlib/dates.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/dates.py 2009-08-20 16:19:22 UTC (rev 7510)
+++ trunk/matplotlib/lib/matplotlib/dates.py 2009-08-20 23:11:44 UTC (rev 7511)
@@ -378,6 +378,28 @@
"""
This class attempts to figure out the best format to use. This is
most useful when used with the :class:`AutoDateLocator`.
+
+
+ The AutoDateFormatter has a scale dictionary that maps the scale
+ of the tick (the distance in days between one major tick) and a
+ format string. The default looks like this::
+
+ self.scaled = {
+ 365.0 : '%Y',
+ 30. : '%b %Y',
+ 1.0 : '%b %d %Y',
+ 1./24. : '%H:%M:%D',
+ }
+
+
+ The algorithm picks the key in the dictionary that is >= the
+ current scale and uses that format string. You can customize this
+ dictionary by doing::
+
+
+ formatter = AutoDateFormatter()
+ formatter.scaled[1/(24.*60.)] = '%M:%S' # only show min and sec
+
"""
# This can be improved by providing some user-level direction on
@@ -392,28 +414,29 @@
# possibility...
def __init__(self, locator, tz=None):
+ """
+ """
self._locator = locator
- self._formatter = DateFormatter("%b %d %Y %H:%M:%S %Z", tz)
self._tz = tz
+ self._formatter = DateFormatter("%b %d %Y %H:%M:%D", tz)
+ self.scaled = {
+ 365.0 : '%Y',
+ 30. : '%b %Y',
+ 1.0 : '%b %d %Y',
+ 1./24. : '%H:%M:%S',
+ }
def __call__(self, x, pos=0):
scale = float( self._locator._get_unit() )
- if ( scale == 365.0 ):
- self._formatter = DateFormatter("%Y", self._tz)
- elif ( scale == 30.0 ):
- self._formatter = DateFormatter("%b %Y", self._tz)
- elif ( (scale == 1.0) or (scale == 7.0) ):
- self._formatter = DateFormatter("%b %d %Y", self._tz)
- elif ( scale == (1.0/24.0) ):
- self._formatter = DateFormatter("%H:%M:%S %Z", self._tz)
- elif ( scale == (1.0/(24*60)) ):
- self._formatter = DateFormatter("%H:%M:%S %Z", self._tz)
- elif ( scale == (1.0/(24*3600)) ):
- self._formatter = DateFormatter("%H:%M:%S %Z", self._tz)
- else:
- self._formatter = DateFormatter("%b %d %Y %H:%M:%S %Z", self._tz)
+ keys = self.scaled.keys()
+ keys.sort()
+ for k in keys:
+ if k>=scale:
+ self._formatter = DateFormatter(self.scaled[k])
+ break
+
return self._formatter(x, pos)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jo...@us...> - 2009-08-20 16:19:29
|
Revision: 7510
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7510&view=rev
Author: jouni
Date: 2009-08-20 16:19:22 +0000 (Thu, 20 Aug 2009)
Log Message:
-----------
Use curl instead of wget in release/osx/Makefile; curl comes preinstalled on OS X
Modified Paths:
--------------
trunk/matplotlib/release/osx/Makefile
Modified: trunk/matplotlib/release/osx/Makefile
===================================================================
--- trunk/matplotlib/release/osx/Makefile 2009-08-20 11:44:59 UTC (rev 7509)
+++ trunk/matplotlib/release/osx/Makefile 2009-08-20 16:19:22 UTC (rev 7510)
@@ -29,12 +29,12 @@
matplotlib-${MPLVERSION} *~
fetch:
- wget http://www.zlib.net/zlib-${ZLIBVERSION}.tar.gz &&\
- wget http://internap.dl.sourceforge.net/sourceforge/libpng/libpng-${PNGVERSION}.tar.bz2 &&\
- wget http://download.savannah.gnu.org/releases/freetype/freetype-${FREETYPEVERSION}.tar.bz2&&\
- wget http://pypi.python.org/packages/source/b/bdist_mpkg/bdist_mpkg-${BDISTMPKGVERSION}.tar.gz&&\
+ curl -LO http://www.zlib.net/zlib-${ZLIBVERSION}.tar.gz &&\
+ curl -LO http://internap.dl.sourceforge.net/sourceforge/libpng/libpng-${PNGVERSION}.tar.bz2 &&\
+ curl -LO http://download.savannah.gnu.org/releases/freetype/freetype-${FREETYPEVERSION}.tar.bz2&&\
+ curl -LO http://pypi.python.org/packages/source/b/bdist_mpkg/bdist_mpkg-${BDISTMPKGVERSION}.tar.gz&&\
tar xvfz bdist_mpkg-${BDISTMPKGVERSION}.tar.gz &&\
- echo "You need to to install bdist_mpkg-${BDISTMPKGVERSION} now"
+ echo "You need to install bdist_mpkg-${BDISTMPKGVERSION} now"
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2009-08-20 11:45:12
|
Revision: 7509
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7509&view=rev
Author: jswhit
Date: 2009-08-20 11:44:59 +0000 (Thu, 20 Aug 2009)
Log Message:
-----------
fix typo
Modified Paths:
--------------
trunk/toolkits/basemap/doc/users/graticule.rst
Modified: trunk/toolkits/basemap/doc/users/graticule.rst
===================================================================
--- trunk/toolkits/basemap/doc/users/graticule.rst 2009-08-20 06:55:52 UTC (rev 7508)
+++ trunk/toolkits/basemap/doc/users/graticule.rst 2009-08-20 11:44:59 UTC (rev 7509)
@@ -7,7 +7,7 @@
latitude and longitude lines. Basemap does this with the
:func:`~mpl_toolkits.basemap.Basemap.drawparallels` and
:func:`~mpl_toolkits.basemap.Basemap.drawmeridians` instance methods.
-The longitude and latitude lines can be labelled where they
+The longitude and latitude lines can be labelled where they intersect
the map projection boundary. There are four exceptions: meridians
and parallels cannot be labelled on maps with
``proj`` set to ``ortho`` (orthographic) or
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ry...@us...> - 2009-08-20 06:56:00
|
Revision: 7508
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7508&view=rev
Author: ryanmay
Date: 2009-08-20 06:55:52 +0000 (Thu, 20 Aug 2009)
Log Message:
-----------
Replace use of axesFrame (which disappeared with spines patch) with axesPatch.
Modified Paths:
--------------
trunk/matplotlib/examples/event_handling/viewlims.py
Modified: trunk/matplotlib/examples/event_handling/viewlims.py
===================================================================
--- trunk/matplotlib/examples/event_handling/viewlims.py 2009-08-20 06:44:26 UTC (rev 7507)
+++ trunk/matplotlib/examples/event_handling/viewlims.py 2009-08-20 06:55:52 UTC (rev 7508)
@@ -40,7 +40,7 @@
ax.set_autoscale_on(False) # Otherwise, infinite loop
#Get the number of points from the number of pixels in the window
- dims = ax.axesFrame.get_window_extent().bounds
+ dims = ax.axesPatch.get_window_extent().bounds
self.width = int(dims[2] + 0.5)
self.height = int(dims[2] + 0.5)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ry...@us...> - 2009-08-20 06:44:35
|
Revision: 7507
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7507&view=rev
Author: ryanmay
Date: 2009-08-20 06:44:26 +0000 (Thu, 20 Aug 2009)
Log Message:
-----------
Fix problem with call to draw in pong demo. Also make draw use 10 ms timers instead of drawing on idle so that it doesn't peg the CPU.
Modified Paths:
--------------
trunk/matplotlib/examples/event_handling/pipong.py
trunk/matplotlib/examples/event_handling/pong_gtk.py
trunk/matplotlib/examples/event_handling/pong_qt.py
Modified: trunk/matplotlib/examples/event_handling/pipong.py
===================================================================
--- trunk/matplotlib/examples/event_handling/pipong.py 2009-08-19 07:56:33 UTC (rev 7506)
+++ trunk/matplotlib/examples/event_handling/pipong.py 2009-08-20 06:44:26 UTC (rev 7507)
@@ -12,17 +12,17 @@
'e' up 'i'
'd' down 'k'
-press 't' -- close these instructions
+press 't' -- close these instructions
(animation will be much faster)
-press 'a' -- add a puck
-press 'A' -- remove a puck
-press '1' -- slow down all pucks
-press '2' -- speed up all pucks
-press '3' -- slow down distractors
-press '4' -- speed up distractors
+press 'a' -- add a puck
+press 'A' -- remove a puck
+press '1' -- slow down all pucks
+press '2' -- speed up all pucks
+press '3' -- slow down distractors
+press '4' -- speed up distractors
press ' ' -- reset the first puck
-press 'n' -- toggle distractors on/off
-press 'g' -- toggle the game on/off
+press 'n' -- toggle distractors on/off
+press 'g' -- toggle the game on/off
"""
@@ -56,7 +56,7 @@
def _reset(self,pad):
self.x = pad.x + pad.xoffset
if pad.y < 0:
- self.y = pad.y + pad.yoffset
+ self.y = pad.y + pad.yoffset
else:
self.y = pad.y - pad.yoffset
self.vx = pad.x - self.x
@@ -84,7 +84,7 @@
self._reset(pads[1])
return True
if self.y < -1+fudge or self.y > 1-fudge:
- self.vy *= -1.0
+ self.vy *= -1.0
# add some randomness, just to make it interesting
self.vy -= (randn()/300.0 + 1/300.0) * np.sign(self.vy)
self._speedlimit()
@@ -106,7 +106,7 @@
if self.vy < -self.vmax:
self.vy = -self.vmax
-class Game(object):
+class Game(object):
def __init__(self, ax):
# create the initial line
@@ -137,7 +137,7 @@
self.pads = []
self.pads.append( Pad(pA,0,padAy))
self.pads.append( Pad(pB,padBx,padBy,'r'))
- self.pucks =[]
+ self.pucks =[]
self.i = self.ax.annotate(instructions,(.5,0.5),
name='monospace',
verticalalignment='center',
@@ -180,8 +180,8 @@
for puck in self.pucks:
if puck.update(self.pads):
# we only get here if someone scored
- self.pads[0].disp.set_label(" "+ str(self.pads[0].score))
- self.pads[1].disp.set_label(" "+ str(self.pads[1].score))
+ self.pads[0].disp.set_label(" "+ str(self.pads[0].score))
+ self.pads[1].disp.set_label(" "+ str(self.pads[1].score))
self.ax.legend(loc='center')
self.leg = self.ax.get_legend()
#self.leg.draw_frame(False) #don't draw the legend border
@@ -189,7 +189,7 @@
plt.setp(self.leg.get_texts(),fontweight='bold',fontsize='xx-large')
self.leg.get_frame().set_facecolor('0.2')
self.background = None
- self.ax.draw()
+ self.ax.figure.canvas.draw()
return True
puck.disp.set_offsets([puck.x,puck.y])
self.ax.draw_artist(puck.disp)
@@ -229,7 +229,7 @@
self.pads[1].y -= .1
if self.pads[1].y < -1:
self.pads[1].y = -1
-
+
if event.key == 'a':
self.pucks.append(Puck(self.puckdisp,self.pads[randint(2)],self.ax.bbox))
if event.key == 'A' and len(self.pucks):
@@ -242,7 +242,7 @@
if event.key == '2':
for p in self.pucks:
p._faster()
-
+
if event.key == 'n':
self.distract = not self.distract
@@ -254,4 +254,4 @@
self.inst = not self.inst
self.i.set_visible(self.i.get_visible())
if event.key == 'q':
- plt.close()
+ plt.close()
Modified: trunk/matplotlib/examples/event_handling/pong_gtk.py
===================================================================
--- trunk/matplotlib/examples/event_handling/pong_gtk.py 2009-08-19 07:56:33 UTC (rev 7506)
+++ trunk/matplotlib/examples/event_handling/pong_gtk.py 2009-08-20 06:44:26 UTC (rev 7507)
@@ -12,7 +12,7 @@
import numpy as np
import matplotlib.pyplot as plt
-import pipong
+import pipong
from numpy.random import randn, randint
@@ -22,7 +22,8 @@
def start_anim(event):
- gobject.idle_add(animation.draw,animation)
+# gobject.idle_add(animation.draw,animation)
+ gobject.timeout_add(10,animation.draw,animation)
canvas.mpl_disconnect(start_anim.cid)
animation = pipong.Game(ax)
Modified: trunk/matplotlib/examples/event_handling/pong_qt.py
===================================================================
--- trunk/matplotlib/examples/event_handling/pong_qt.py 2009-08-19 07:56:33 UTC (rev 7506)
+++ trunk/matplotlib/examples/event_handling/pong_qt.py 2009-08-20 06:44:26 UTC (rev 7507)
@@ -18,7 +18,7 @@
import matplotlib.pyplot as plt
import numpy as np
import time
-import pipong
+import pipong
from numpy.random import randn, randint
class BlitQT(QObject):
@@ -36,7 +36,7 @@
app = BlitQT()
# for profiling
app.tstart = time.time()
-app.startTimer(0)
+app.startTimer(10)
plt.show()
print 'FPS:' , app.animation.cnt/(time.time()-app.tstart)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: Darren D. <dsd...@gm...> - 2009-08-19 22:35:39
|
Ryan, I don't think these calls should be removed. Would you convert them to asanyarray() instead? That will preserve the masked arrays. Darren > Log Message: > ----------- > Remove calls to np.asarray(). This was breaking the use of masked arrays in calls to set_[x|y]data() and is handled appropriately already by set_data(). > > Modified Paths: > -------------- > branches/v0_99_maint/lib/matplotlib/lines.py > > Modified: branches/v0_99_maint/lib/matplotlib/lines.py > =================================================================== > --- branches/v0_99_maint/lib/matplotlib/lines.py 2009-08-18 22:18:59 UTC (rev 7505) > +++ branches/v0_99_maint/lib/matplotlib/lines.py 2009-08-19 07:56:33 UTC (rev 7506) > @@ -843,7 +843,6 @@ > > ACCEPTS: 1D array > """ > - x = np.asarray(x) > self.set_data(x, self._yorig) > > def set_ydata(self, y): > @@ -852,7 +851,6 @@ > > ACCEPTS: 1D array > """ > - y = np.asarray(y) > self.set_data(self._xorig, y) > > def set_dashes(self, seq): > > > This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. > > ------------------------------------------------------------------------------ > Let Crystal Reports handle the reporting - Free Crystal Reports 2008 30-Day > trial. Simplify your report design, integration and deployment - and focus on > what you do best, core application coding. Discover what's new with > Crystal Reports now. http://p.sf.net/sfu/bobj-july > _______________________________________________ > Matplotlib-checkins mailing list > Mat...@li... > https://lists.sourceforge.net/lists/listinfo/matplotlib-checkins > -- "In our description of nature, the purpose is not to disclose the real essence of the phenomena but only to track down, so far as it is possible, relations between the manifold aspects of our experience" - Niels Bohr "It is a bad habit of physicists to take their most successful abstractions to be real properties of our world." - N. David Mermin "Once we have granted that any physical theory is essentially only a model for the world of experience, we must renounce all hope of finding anything like the correct theory ... simply because the totality of experience is never accessible to us." - Hugh Everett III |
|
From: <ry...@us...> - 2009-08-19 07:56:43
|
Revision: 7506
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7506&view=rev
Author: ryanmay
Date: 2009-08-19 07:56:33 +0000 (Wed, 19 Aug 2009)
Log Message:
-----------
Remove calls to np.asarray(). This was breaking the use of masked arrays in calls to set_[x|y]data() and is handled appropriately already by set_data().
Modified Paths:
--------------
branches/v0_99_maint/lib/matplotlib/lines.py
Modified: branches/v0_99_maint/lib/matplotlib/lines.py
===================================================================
--- branches/v0_99_maint/lib/matplotlib/lines.py 2009-08-18 22:18:59 UTC (rev 7505)
+++ branches/v0_99_maint/lib/matplotlib/lines.py 2009-08-19 07:56:33 UTC (rev 7506)
@@ -843,7 +843,6 @@
ACCEPTS: 1D array
"""
- x = np.asarray(x)
self.set_data(x, self._yorig)
def set_ydata(self, y):
@@ -852,7 +851,6 @@
ACCEPTS: 1D array
"""
- y = np.asarray(y)
self.set_data(self._xorig, y)
def set_dashes(self, seq):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2009-08-18 22:19:12
|
Revision: 7505
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7505&view=rev
Author: efiring
Date: 2009-08-18 22:18:59 +0000 (Tue, 18 Aug 2009)
Log Message:
-----------
Small cleanup of logic in handling drawstyle in Line2D
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/lines.py
Modified: trunk/matplotlib/lib/matplotlib/lines.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/lines.py 2009-08-18 22:13:11 UTC (rev 7504)
+++ trunk/matplotlib/lib/matplotlib/lines.py 2009-08-18 22:18:59 UTC (rev 7505)
@@ -99,6 +99,8 @@
drawStyles = {}
drawStyles.update(_drawStyles_l)
drawStyles.update(_drawStyles_s)
+ # Need a list ordered with long names first:
+ drawStyleKeys = _drawStyles_l.keys() + _drawStyles_s.keys()
markers = _markers = { # hidden names deprecated
'.' : '_draw_point',
@@ -712,15 +714,14 @@
any drawstyle in combination with a linestyle, e.g. 'steps--'.
"""
- # handle long drawstyle names before short ones !
- for ds in flatten([k.keys() for k in (self._drawStyles_l,
- self._drawStyles_s)], is_string_like):
+ for ds in self.drawStyleKeys: # long names are first in the list
if linestyle.startswith(ds):
self.set_drawstyle(ds)
if len(linestyle) > len(ds):
linestyle = linestyle[len(ds):]
else:
linestyle = '-'
+ break
if linestyle not in self._lineStyles:
if linestyle in ls_mapper:
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2009-08-18 22:13:18
|
Revision: 7504
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7504&view=rev
Author: mdboom
Date: 2009-08-18 22:13:11 +0000 (Tue, 18 Aug 2009)
Log Message:
-----------
Fix clipping on collections.
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/collections.py
Modified: trunk/matplotlib/lib/matplotlib/collections.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/collections.py 2009-08-18 21:59:07 UTC (rev 7503)
+++ trunk/matplotlib/lib/matplotlib/collections.py 2009-08-18 22:13:11 UTC (rev 7504)
@@ -208,8 +208,7 @@
transform, transOffset, offsets, paths = self._prepare_points()
gc = renderer.new_gc()
- gc.set_clip_rectangle(self.get_clip_box())
- gc.set_clip_path(self.get_clip_path())
+ self._set_gc_clip(gc)
renderer.draw_path_collection(
gc, transform.frozen(), paths, self.get_transforms(),
@@ -1210,8 +1209,7 @@
transOffset = transOffset.get_affine()
gc = renderer.new_gc()
- gc.set_clip_rectangle(self.get_clip_box())
- gc.set_clip_path(self.get_clip_path())
+ self._set_clip_gc(gc)
if self._shading == 'gouraud':
triangles, colors = self.convert_mesh_to_triangles(
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <pki...@us...> - 2009-08-18 21:59:13
|
Revision: 7503
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7503&view=rev
Author: pkienzle
Date: 2009-08-18 21:59:07 +0000 (Tue, 18 Aug 2009)
Log Message:
-----------
devel docs: minor typo
Modified Paths:
--------------
trunk/matplotlib/doc/devel/documenting_mpl.rst
Modified: trunk/matplotlib/doc/devel/documenting_mpl.rst
===================================================================
--- trunk/matplotlib/doc/devel/documenting_mpl.rst 2009-08-18 14:08:27 UTC (rev 7502)
+++ trunk/matplotlib/doc/devel/documenting_mpl.rst 2009-08-18 21:59:07 UTC (rev 7503)
@@ -286,7 +286,7 @@
.. literalinclude:: ../../lib/matplotlib/mpl-data/matplotlibrc
-On exception to this is when referring to the examples dir. Relative
+One exception to this is when referring to the examples dir. Relative
paths are extremely confusing in the sphinx plot extensions, so
without getting into the dirty details, it is easier to simply include
a symlink to the files at the top doc level directory. This way, API
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2009-08-18 14:08:33
|
Revision: 7502
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7502&view=rev
Author: mdboom
Date: 2009-08-18 14:08:27 +0000 (Tue, 18 Aug 2009)
Log Message:
-----------
Fix some minor typos in the paths tutorial
Modified Paths:
--------------
branches/v0_99_maint/doc/users/path_tutorial.rst
Modified: branches/v0_99_maint/doc/users/path_tutorial.rst
===================================================================
--- branches/v0_99_maint/doc/users/path_tutorial.rst 2009-08-18 14:01:41 UTC (rev 7501)
+++ branches/v0_99_maint/doc/users/path_tutorial.rst 2009-08-18 14:08:27 UTC (rev 7502)
@@ -6,9 +6,9 @@
The object underlying all of the :mod:`matplotlib.patch` objects is
the :class:`~matplotlib.path.Path`, which supports the standard set of
-moveto, lineto, curveto commands to draw simple and compoud outlines
+moveto, lineto, curveto commands to draw simple and compound outlines
consisting of line segments and splines. The ``Path`` is instantiated
-with a (N,2) array of (x,y) vertices, and a N length array of path
+with a (N,2) array of (x,y) vertices, and a N-length array of path
codes. For example to draw the unit rectangle from (0,0) to (1,1), we
could use this code
@@ -53,24 +53,24 @@
``STOP`` 1 (ignored) A marker for the end of the entire path (currently not required and ignored)
``MOVETO`` 1 Pick up the pen and move to the given vertex.
``LINETO`` 1 Draw a line from the current position to the given vertex.
-``CURVE3`` 2 (1 control point, 1 endpoint) Draw a quadratic Bezier curve from the current position, with the given control point, to the given end point.
-``CURVE4`` 3 (2 control points, 1 endpoint) Draw a cubic Bezier curve from the current position, with the given control points, to the given end point.
-``CLOSEPOLY`` 1 (ignored) Draw a line segment to the start point of the current polyline.
+``CURVE3`` 2 (1 control point, 1 endpoint) Draw a quadratic Bézier curve from the current position, with the given control point, to the given end point.
+``CURVE4`` 3 (2 control points, 1 endpoint) Draw a cubic Bézier curve from the current position, with the given control points, to the given end point.
+``CLOSEPOLY`` 1 (point itself is ignored) Draw a line segment to the start point of the current polyline.
============== ================================= ====================================================================================================================
.. path-curves:
-Bezier example
+Bézier example
==============
Some of the path components require multiple vertices to specify them:
-for example CURVE 3 is a `bezier
+for example CURVE 3 is a `bézier
<http://en.wikipedia.org/wiki/B%C3%A9zier_curve>`_ curve with one
control point and one end point, and CURVE4 has three vertices for the
two control points and the end point. The example below shows a
-CURVE4 Bezier spline -- the bezier curve will be contained in the
+CURVE4 Bézier spline -- the bézier curve will be contained in the
convex hul of the start point, the two control points, and the end
point
@@ -175,7 +175,7 @@
verts[3::5,1] = bottom
All that remains is to create the path, attach it to a
-:class:`~matplotlib.patch.PathPatch`, and ad it to our axes::
+:class:`~matplotlib.patch.PathPatch`, and add it to our axes::
barpath = path.Path(verts, codes)
patch = patches.PathPatch(barpath, facecolor='green',
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2009-08-18 14:01:48
|
Revision: 7501
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7501&view=rev
Author: mdboom
Date: 2009-08-18 14:01:41 +0000 (Tue, 18 Aug 2009)
Log Message:
-----------
Fix some minor typos in the transforms tutorial
Modified Paths:
--------------
branches/v0_99_maint/doc/users/transforms_tutorial.rst
Modified: branches/v0_99_maint/doc/users/transforms_tutorial.rst
===================================================================
--- branches/v0_99_maint/doc/users/transforms_tutorial.rst 2009-08-18 14:00:28 UTC (rev 7500)
+++ branches/v0_99_maint/doc/users/transforms_tutorial.rst 2009-08-18 14:01:41 UTC (rev 7501)
@@ -348,7 +348,10 @@
and zoom. There is an efficiency here, because you can pan and zoom
in your axes which affects the affine transformation, but you may not
need to compute the potentially expensive nonlinear scales or
-projections on simple navigation events.
+projections on simple navigation events. It is also possible to
+multiply affine transformation matrices togeter, and then apply them
+to coordinates in one step. This is not true of all possible
+transformations.
Here is how the ``ax.transData`` instance is defined in the basic
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2009-08-18 14:00:37
|
Revision: 7500
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7500&view=rev
Author: mdboom
Date: 2009-08-18 14:00:28 +0000 (Tue, 18 Aug 2009)
Log Message:
-----------
Fix some minor typos in the transforms tutorial
Modified Paths:
--------------
branches/v0_99_maint/doc/users/transforms_tutorial.rst
Modified: branches/v0_99_maint/doc/users/transforms_tutorial.rst
===================================================================
--- branches/v0_99_maint/doc/users/transforms_tutorial.rst 2009-08-18 05:15:21 UTC (rev 7499)
+++ branches/v0_99_maint/doc/users/transforms_tutorial.rst 2009-08-18 14:00:28 UTC (rev 7500)
@@ -34,7 +34,7 @@
`Transformation Object` column -- it already is in display
coordinates. The transformations also know how to invert themselves,
to go from `display` back to the native coordinate system. This is
-particularly useful when processing events frmo the user interface,
+particularly useful when processing events from the user interface,
which typically occur in display space, and you want to know where the
mouse click or key-press occurred in your data coordinate system.
@@ -44,8 +44,8 @@
================
Let's start with the most commonly used coordinate, the `data`
-coordinate system. Whenever, you add data to the axes, matplotlib
-updates the datalimits, most commonly updated in with the
+coordinate system. Whenever you add data to the axes, matplotlib
+updates the datalimits, most commonly updated with the
:meth:`~matplotlib.axes.Axes.set_xlim` and
:meth:`~matplotlib.axes.Axes.set_ylim` methods. For example, in the
figure below, the data limits stretch from 0 to 10 on the x-axis, and
@@ -85,7 +85,7 @@
array([[ 335.175, 247. ],
[ 132.435, 642.2 ]])
-You can use the :meth`~matplotlib.transforms.Transform.inverted`
+You can use the :meth:`~matplotlib.transforms.Transform.inverted`
method to create a transform which will take you from display to data
coordinates:
@@ -152,15 +152,15 @@
================
After the `data` coordinate system, `axes` is probably the second most
-useful coordinate system. Here the point (0,0) is the bottom left
-of your axes or subplot, (0.5, 0.5) is the center, and (1.0,
-1.0) is the top right. You can also refer to points outside the
-range, so (-0.1, 1.1) is to the left and above your axes. This
-coordinate system is extremely useful when making placing text in your
-axes, because you often want a text bubble in a fixed, location, eg
-the upper left of the axes pane, and have that location remain fixed
-when you pan or zoom. Here is a simple example that creates four
-panels and labels them 'A', 'B', 'C', 'D' as you often see in journals.
+useful coordinate system. Here the point (0,0) is the bottom left of
+your axes or subplot, (0.5, 0.5) is the center, and (1.0, 1.0) is the
+top right. You can also refer to points outside the range, so (-0.1,
+1.1) is to the left and above your axes. This coordinate system is
+extremely useful when placing text in your axes, because you often
+want a text bubble in a fixed, location, eg. the upper left of the axes
+pane, and have that location remain fixed when you pan or zoom. Here
+is a simple example that creates four panels and labels them 'A', 'B',
+'C', 'D' as you often see in journals.
.. plot::
:include-source:
@@ -265,7 +265,7 @@
=================================================
One use of transformations is to create a new transformation that is
-offset from another annotation, eg to place one object shited a bit
+offset from another annotation, eg to place one object shifted a bit
relative to another object. Typically you want the shift to be in
some physical dimension, like points or inches rather than in data
coordinates, so that the shift effect is constant at different zoom
@@ -285,12 +285,12 @@
a transformation which scales `xt` and `yt` at transformation time
before applying the offsets. A typical use case is to use the figure
``fig.dpi_scale_trans`` transformation for the `scale_trans` argument,
-to first scale `xty and `yt` specified in points to `display` space
+to first scale `xt` and `yt` specified in points to `display` space
before doing the final offset. The dpi and inches offset is a
common-enough use case that we have a special helper function to
create it in :func:`matplotlib.transforms.offset_copy`, which returns
a new transform with an added offset. But in the example below, we'll
-create the offset trransform ourselves. Note the use of the plus
+create the offset transform ourselves. Note the use of the plus
operator in::
offset = transforms.ScaledTranslation(dx, dy,
@@ -298,7 +298,7 @@
shadow_transform = ax.transData + offset
showing that can chain transformations using the addition operator.
-This code say: first appy the data transformation ``ax.transData`` and
+This code says: first appy the data transformation ``ax.transData`` and
then translate the data by `dx` and `dy` points.
.. plot::
@@ -342,12 +342,12 @@
tutorial is a composite of three different transformations that
comprise the transformation pipeline from `data` -> `display`
coordinates. Michael Droettboom implemented the transformations
-frameowk, taking care to provide a clean API that segregated the
+framework, taking care to provide a clean API that segregated the
nonlinear projections and scales that happen in polar and logarithmic
plots, from the linear affine transformations that happen when you pan
and zoom. There is an efficiency here, because you can pan and zoom
in your axes which affects the affine transformation, but you may not
-need to compte the potentially expensice nonlinear scales or
+need to compute the potentially expensive nonlinear scales or
projections on simple navigation events.
@@ -361,8 +361,8 @@
axes or subplot bounding box to `display` space, so let's look at
these other two pieces.
-``self.transLimits`` is the transformation that takes your from
-``data`` to ``axes`` coordinates; ie, it maps your view xlim and ylim
+``self.transLimits`` is the transformation that takes you from
+``data`` to ``axes`` coordinates; i.e., it maps your view xlim and ylim
to the unit space of the axes (and ``transAxes`` then takes that unit
space to display space). We can see this in action here
@@ -397,7 +397,7 @@
Out[90]: array([ 2.5, -0.5])
The final piece is the ``self.transScale`` attribute, which is
-responsible for the optional non-linear scaling of the data, eg for
+responsible for the optional non-linear scaling of the data, eg. for
logarithmic axes. When an Axes is initally setup, this is just set to
the identity transform, since the basic matplotlib axes has linear
scale, but when you call a logarithmic scaling function like
@@ -418,12 +418,13 @@
self.transData = self.transScale + self.transProjection + \
(self.transProjectionAffine + self.transAxes)
-``transProjection`` handles the projection from the space, eg latitude and longitude
-for map data, or radius and theta for polar data, to a separable
-cartesian coordinate system. There are several projection examples in
-the ``matplotlib.projections`` package, and the best way to learn more
-is to open the source for those packages and see how to make your own,
-since matplotlib supports extensible axes and projections. Michael
-Droettboom has provided a nice tutorial example of creating a hammer
-projection axes; see :ref:`api-custom_projection_example`.
+``transProjection`` handles the projection from the space,
+eg. latitude and longitude for map data, or radius and theta for polar
+data, to a separable cartesian coordinate system. There are several
+projection examples in the ``matplotlib.projections`` package, and the
+best way to learn more is to open the source for those packages and
+see how to make your own, since matplotlib supports extensible axes
+and projections. Michael Droettboom has provided a nice tutorial
+example of creating a hammer projection axes; see
+:ref:`api-custom_projection_example`.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2009-08-18 05:15:28
|
Revision: 7499
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7499&view=rev
Author: jdh2358
Date: 2009-08-18 05:15:21 +0000 (Tue, 18 Aug 2009)
Log Message:
-----------
added looking glass demo
Added Paths:
-----------
branches/v0_99_maint/examples/event_handling/looking_glass.py
Added: branches/v0_99_maint/examples/event_handling/looking_glass.py
===================================================================
--- branches/v0_99_maint/examples/event_handling/looking_glass.py (rev 0)
+++ branches/v0_99_maint/examples/event_handling/looking_glass.py 2009-08-18 05:15:21 UTC (rev 7499)
@@ -0,0 +1,47 @@
+import numpy as np
+import matplotlib.pyplot as plt
+import matplotlib.patches as patches
+x, y = np.random.rand(2, 200)
+
+fig = plt.figure()
+ax = fig.add_subplot(111)
+circ = patches.Circle( (0.5, 0.5), 0.25, alpha=0.8, fc='yellow')
+ax.add_patch(circ)
+
+
+ax.plot(x, y, alpha=0.2)
+line, = ax.plot(x, y, alpha=1.0, clip_path=circ)
+
+class EventHandler:
+ def __init__(self):
+ fig.canvas.mpl_connect('button_press_event', self.onpress)
+ fig.canvas.mpl_connect('button_release_event', self.onrelease)
+ fig.canvas.mpl_connect('motion_notify_event', self.onmove)
+ self.x0, self.y0 = circ.center
+ self.pressevent = None
+
+ def onpress(self, event):
+ if event.inaxes!=ax:
+ return
+
+ if not circ.contains(event):
+ return
+
+ self.pressevent = event
+
+ def onrelease(self, event):
+ self.pressevent = None
+ self.x0, self.y0 = circ.center
+
+ def onmove(self, event):
+ if self.pressevent is None or event.inaxes!=self.pressevent.inaxes:
+ return
+
+ dx = event.xdata - self.pressevent.xdata
+ dy = event.ydata - self.pressevent.ydata
+ circ.center = self.x0 + dx, self.y0 + dy
+ line.set_clip_path(circ)
+ fig.canvas.draw()
+
+handler = EventHandler()
+plt.show()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2009-08-18 03:48:27
|
Revision: 7498
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7498&view=rev
Author: jdh2358
Date: 2009-08-18 03:48:21 +0000 (Tue, 18 Aug 2009)
Log Message:
-----------
added path tut
Modified Paths:
--------------
branches/v0_99_maint/doc/users/index.rst
Added Paths:
-----------
branches/v0_99_maint/doc/pyplots/compound_path_demo.py
branches/v0_99_maint/doc/users/path_tutorial.rst
Added: branches/v0_99_maint/doc/pyplots/compound_path_demo.py
===================================================================
--- branches/v0_99_maint/doc/pyplots/compound_path_demo.py (rev 0)
+++ branches/v0_99_maint/doc/pyplots/compound_path_demo.py 2009-08-18 03:48:21 UTC (rev 7498)
@@ -0,0 +1,42 @@
+import numpy as np
+
+import matplotlib.pyplot as plt
+import matplotlib.patches as patches
+import matplotlib.path as path
+
+fig = plt.figure()
+ax = fig.add_subplot(111)
+
+# histogram our data with numpy
+data = np.random.randn(1000)
+n, bins = np.histogram(data, 100)
+
+# get the corners of the rectangles for the histogram
+left = np.array(bins[:-1])
+right = np.array(bins[1:])
+bottom = np.zeros(len(left))
+top = bottom + n
+nrects = len(left)
+
+nverts = nrects*(1+3+1)
+verts = np.zeros((nverts, 2))
+codes = np.ones(nverts, int) * path.Path.LINETO
+codes[0::5] = path.Path.MOVETO
+codes[4::5] = path.Path.CLOSEPOLY
+verts[0::5,0] = left
+verts[0::5,1] = bottom
+verts[1::5,0] = left
+verts[1::5,1] = top
+verts[2::5,0] = right
+verts[2::5,1] = top
+verts[3::5,0] = right
+verts[3::5,1] = bottom
+
+barpath = path.Path(verts, codes)
+patch = patches.PathPatch(barpath, facecolor='green', edgecolor='yellow', alpha=0.5)
+ax.add_patch(patch)
+
+ax.set_xlim(left[0], right[-1])
+ax.set_ylim(bottom.min(), top.max())
+
+plt.show()
Modified: branches/v0_99_maint/doc/users/index.rst
===================================================================
--- branches/v0_99_maint/doc/users/index.rst 2009-08-18 02:41:43 UTC (rev 7497)
+++ branches/v0_99_maint/doc/users/index.rst 2009-08-18 03:48:21 UTC (rev 7498)
@@ -25,6 +25,7 @@
annotations_guide.rst
legend.rst
transforms_tutorial.rst
+ path_tutorial.rst
toolkits.rst
screenshots.rst
whats_new.rst
Added: branches/v0_99_maint/doc/users/path_tutorial.rst
===================================================================
--- branches/v0_99_maint/doc/users/path_tutorial.rst (rev 0)
+++ branches/v0_99_maint/doc/users/path_tutorial.rst 2009-08-18 03:48:21 UTC (rev 7498)
@@ -0,0 +1,187 @@
+.. _path_tutorial:
+
+*************
+Path Tutorial
+*************
+
+The object underlying all of the :mod:`matplotlib.patch` objects is
+the :class:`~matplotlib.path.Path`, which supports the standard set of
+moveto, lineto, curveto commands to draw simple and compoud outlines
+consisting of line segments and splines. The ``Path`` is instantiated
+with a (N,2) array of (x,y) vertices, and a N length array of path
+codes. For example to draw the unit rectangle from (0,0) to (1,1), we
+could use this code
+
+.. plot::
+ :include-source:
+
+ import matplotlib.pyplot as plt
+ from matplotlib.path import Path
+ import matplotlib.patches as patches
+
+ verts = [
+ (0., 0.), # left, bottom
+ (0., 1.), # left, top
+ (1., 1.), # right, top
+ (1., 0.), # right, bottom
+ (0., 0.), # ignored
+ ]
+
+ codes = [Path.MOVETO,
+ Path.LINETO,
+ Path.LINETO,
+ Path.LINETO,
+ Path.CLOSEPOLY,
+ ]
+
+ path = Path(verts, codes)
+
+ fig = plt.figure()
+ ax = fig.add_subplot(111)
+ patch = patches.PathPatch(path, facecolor='orange', lw=2)
+ ax.add_patch(patch)
+ ax.set_xlim(-2,2)
+ ax.set_ylim(-2,2)
+ plt.show()
+
+
+The following path codes are recognized
+
+============== ================================= ====================================================================================================================
+Code Vertices Description
+============== ================================= ====================================================================================================================
+``STOP`` 1 (ignored) A marker for the end of the entire path (currently not required and ignored)
+``MOVETO`` 1 Pick up the pen and move to the given vertex.
+``LINETO`` 1 Draw a line from the current position to the given vertex.
+``CURVE3`` 2 (1 control point, 1 endpoint) Draw a quadratic Bezier curve from the current position, with the given control point, to the given end point.
+``CURVE4`` 3 (2 control points, 1 endpoint) Draw a cubic Bezier curve from the current position, with the given control points, to the given end point.
+``CLOSEPOLY`` 1 (ignored) Draw a line segment to the start point of the current polyline.
+============== ================================= ====================================================================================================================
+
+
+.. path-curves:
+
+
+Bezier example
+==============
+
+Some of the path components require multiple vertices to specify them:
+for example CURVE 3 is a `bezier
+<http://en.wikipedia.org/wiki/B%C3%A9zier_curve>`_ curve with one
+control point and one end point, and CURVE4 has three vertices for the
+two control points and the end point. The example below shows a
+CURVE4 Bezier spline -- the bezier curve will be contained in the
+convex hul of the start point, the two control points, and the end
+point
+
+.. plot::
+ :include-source:
+
+ import matplotlib.pyplot as plt
+ from matplotlib.path import Path
+ import matplotlib.patches as patches
+
+ verts = [
+ (0., 0.), # P0
+ (0.2, 1.), # P1
+ (1., 0.8), # P2
+ (0.8, 0.), # P3
+ ]
+
+ codes = [Path.MOVETO,
+ Path.CURVE4,
+ Path.CURVE4,
+ Path.CURVE4,
+ ]
+
+ path = Path(verts, codes)
+
+ fig = plt.figure()
+ ax = fig.add_subplot(111)
+ patch = patches.PathPatch(path, facecolor='none', lw=2)
+ ax.add_patch(patch)
+
+ xs, ys = zip(*verts)
+ ax.plot(xs, ys, 'x--', lw=2, color='black', ms=10)
+
+ ax.text(-0.05, -0.05, 'P0')
+ ax.text(0.15, 1.05, 'P1')
+ ax.text(1.05, 0.85, 'P2')
+ ax.text(0.85, -0.05, 'P3')
+
+ ax.set_xlim(-0.1, 1.1)
+ ax.set_ylim(-0.1, 1.1)
+ plt.show()
+
+.. compound_paths:
+
+Compound paths
+==============
+
+All of the simple patch primitives in matplotlib, Rectangle, Circle,
+Polygon, etc, are implemented with simple path. Plotting functions
+like :meth:`~matplotlib.axes.Axes.hist` and
+:meth:`~matplotlib.axes.Axes.bar`, which create a number of
+primitives, eg a bunch of Rectangles, can usually be implemented more
+efficiently using a compund path. The reason ``bar`` creates a list
+of rectangles and not a compound path is largely historical: the
+:class:`~matplotlib.path.Path` code is comparatively new and ``bar``
+predates it. While we could change it now, it would break old code,
+so here we will cover how to create compound paths, replacing the
+functionality in bar, in case you need to do so in your own code for
+efficiency reasons, eg you are creating an animated bar plot.
+
+We will make the histogram chart by creating a series of rectangles
+for each histogram bar: the rectangle width is the bin width and the
+rectangle height is the number of datapoints in that bin. First we'll
+create some random normally distributed data and compute the
+histogram. Because numpy returns the bin edges and not centers, the
+length of ``bins`` is 1 greater than the length of ``n`` in the
+example below::
+
+ # histogram our data with numpy
+ data = np.random.randn(1000)
+ n, bins = np.histogram(data, 100)
+
+We'll now extract the corners of the rectangles. Each of the
+``left``, ``bottom``, etc, arrays below is ``len(n)``, where ``n`` is
+the array of counts for each histogram bar::
+
+ # get the corners of the rectangles for the histogram
+ left = np.array(bins[:-1])
+ right = np.array(bins[1:])
+ bottom = np.zeros(len(left))
+ top = bottom + n
+
+Now we have to construct our compound path, which will consist of a
+series of ``MOVETO``, ``LINETO`` and ``CLOSEPOLY`` for each rectangle.
+For each rectangle, we need 5 vertices: 1 for the ``MOVETO``, 3 for
+the ``LINETO``, and 1 for the ``CLOSEPOLY``. As indicated in the
+table above, the vertex for the closepoly is ignored but we still need
+it to keep the codes aligned with the vertices::
+
+ nverts = nrects*(1+3+1)
+ verts = np.zeros((nverts, 2))
+ codes = np.ones(nverts, int) * path.Path.LINETO
+ codes[0::5] = path.Path.MOVETO
+ codes[4::5] = path.Path.CLOSEPOLY
+ verts[0::5,0] = left
+ verts[0::5,1] = bottom
+ verts[1::5,0] = left
+ verts[1::5,1] = top
+ verts[2::5,0] = right
+ verts[2::5,1] = top
+ verts[3::5,0] = right
+ verts[3::5,1] = bottom
+
+All that remains is to create the path, attach it to a
+:class:`~matplotlib.patch.PathPatch`, and ad it to our axes::
+
+ barpath = path.Path(verts, codes)
+ patch = patches.PathPatch(barpath, facecolor='green',
+ edgecolor='yellow', alpha=0.5)
+ ax.add_patch(patch)
+
+Here is the result
+
+.. plot:: pyplots/compound_path_demo.py
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2009-08-18 02:41:52
|
Revision: 7497
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7497&view=rev
Author: efiring
Date: 2009-08-18 02:41:43 +0000 (Tue, 18 Aug 2009)
Log Message:
-----------
Remove unmasked_index_ranges from lines.py; it is still in cbook.py
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/lines.py
Modified: trunk/matplotlib/lib/matplotlib/lines.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/lines.py 2009-08-15 23:51:39 UTC (rev 7496)
+++ trunk/matplotlib/lib/matplotlib/lines.py 2009-08-18 02:41:43 UTC (rev 7497)
@@ -26,15 +26,6 @@
CARETLEFT, CARETRIGHT, CARETUP, CARETDOWN) = range(8)
-# COVERAGE NOTE: Never called internally or from examples
-def unmasked_index_ranges(mask, compressed = True):
- warnings.warn("Import this directly from matplotlib.cbook",
- DeprecationWarning)
- # Warning added 2008/07/22
- from matplotlib.cbook import unmasked_index_ranges as _unmasked_index_ranges
- return _unmasked_index_ranges(mask, compressed=compressed)
-
-
def segment_hits(cx, cy, x, y, radius):
"""
Determine if any line segments are within radius of a
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2009-08-15 23:51:45
|
Revision: 7496
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7496&view=rev
Author: efiring
Date: 2009-08-15 23:51:39 +0000 (Sat, 15 Aug 2009)
Log Message:
-----------
Add docstring.py; I forgot to add it when committing the Coombs patch
Added Paths:
-----------
trunk/matplotlib/lib/matplotlib/docstring.py
Added: trunk/matplotlib/lib/matplotlib/docstring.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/docstring.py (rev 0)
+++ trunk/matplotlib/lib/matplotlib/docstring.py 2009-08-15 23:51:39 UTC (rev 7496)
@@ -0,0 +1,112 @@
+from matplotlib import cbook
+
+class Substitution(object):
+ """
+ A decorator to take a function's docstring and perform string
+ substitution on it.
+
+ This decorator should be robust even if func.__doc__ is None
+ (for example, if -OO was passed to the interpreter)
+
+ Usage: construct a docstring.Substitution with a sequence or
+ dictionary suitable for performing substitution; then
+ decorate a suitable function with the constructed object. e.g.
+
+ sub_author_name = Substitution(author='Jason')
+
+ @sub_author_name
+ def some_function(x):
+ "%(author)s wrote this function"
+
+ # note that some_function.__doc__ is now "Jason wrote this function"
+
+ One can also use positional arguments.
+
+ sub_first_last_names = Substitution('Edgar Allen', 'Poe')
+
+ @sub_first_last_names
+ def some_function(x):
+ "%s %s wrote the Raven"
+ """
+ def __init__(self, *args, **kwargs):
+ assert not (args and kwargs), "Only positional or keyword args are allowed"
+ self.params = args or kwargs
+
+ def __call__(self, func):
+ func.__doc__ = func.__doc__ and func.__doc__ % self.params
+ return func
+
+ def update(self, *args, **kwargs):
+ "Assume self.params is a dict and update it with supplied args"
+ self.params.update(*args, **kwargs)
+
+ @classmethod
+ def from_params(cls, params):
+ """
+ In the case where the params is a mutable sequence (list or dictionary)
+ and it may change before this class is called, one may explicitly use
+ a reference to the params rather than using *args or **kwargs which will
+ copy the values and not reference them.
+ """
+ result = cls()
+ result.params = params
+ return result
+
+class Appender(object):
+ """
+ A function decorator that will append an addendum to the docstring
+ of the target function.
+
+ This decorator should be robust even if func.__doc__ is None
+ (for example, if -OO was passed to the interpreter).
+
+ Usage: construct a docstring.Appender with a string to be joined to
+ the original docstring. An optional 'join' parameter may be supplied
+ which will be used to join the docstring and addendum. e.g.
+
+ add_copyright = Appender("Copyright (c) 2009", join='\n')
+
+ @add_copyright
+ def my_dog(has='fleas'):
+ "This docstring will have a copyright below"
+ pass
+ """
+ def __init__(self, addendum, join=''):
+ self.addendum = addendum
+ self.join = join
+
+ def __call__(self, func):
+ docitems = [func.__doc__, self.addendum]
+ func.__doc__ = func.__doc__ and ''.join(docitems)
+ return func
+
+def dedent(func):
+ "Dedent a docstring (if present)"
+ func.__doc__ = func.__doc__ and cbook.dedent(func.__doc__)
+ return func
+
+def copy(source):
+ "Copy a docstring from another source function (if present)"
+ def do_copy(target):
+ if source.__doc__:
+ target.__doc__ = source.__doc__
+ return target
+ return do_copy
+
+# create a decorator that will house the various documentation that
+# is reused throughout matplotlib
+interpd = Substitution()
+
+def dedent_interpd(func):
+ """A special case of the interpd that first performs a dedent on
+ the incoming docstring"""
+ return interpd(dedent(func))
+
+def copy_dedent(source):
+ """A decorator that will copy the docstring from the source and
+ then dedent it"""
+ # note the following is ugly because "Python is not a functional
+ # language" - GVR. Perhaps one day, functools.compose will exist.
+ # or perhaps not.
+ # http://mail.python.org/pipermail/patches/2007-February/021687.html
+ return lambda target: dedent(copy(source)(target))
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2009-08-15 23:05:58
|
Revision: 7495
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7495&view=rev
Author: efiring
Date: 2009-08-15 23:05:52 +0000 (Sat, 15 Aug 2009)
Log Message:
-----------
Small changes to bar kwarg handling in response to 1200213
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/axes.py
trunk/matplotlib/lib/matplotlib/pyplot.py
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2009-08-15 21:24:01 UTC (rev 7494)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2009-08-15 23:05:52 UTC (rev 7495)
@@ -4076,19 +4076,11 @@
@docstring.dedent_interpd
- def bar(self, left, height, width=0.8, bottom=None,
- color=None, edgecolor=None, linewidth=None,
- yerr=None, xerr=None, ecolor=None, capsize=3,
- align='edge', orientation='vertical', log=False,
- **kwargs
- ):
+ def bar(self, left, height, width=0.8, bottom=None, **kwargs):
"""
call signature::
- bar(left, height, width=0.8, bottom=0,
- color=None, edgecolor=None, linewidth=None,
- yerr=None, xerr=None, ecolor=None, capsize=3,
- align='edge', orientation='vertical', log=False)
+ bar(left, height, width=0.8, bottom=0, **kwargs)
Make a bar plot with rectangles bounded by:
@@ -4157,7 +4149,16 @@
.. plot:: mpl_examples/pylab_examples/bar_stacked.py
"""
if not self._hold: self.cla()
-
+ color = kwargs.pop('color', None)
+ edgecolor = kwargs.pop('edgecolor', None)
+ linewidth = kwargs.pop('linewidth', None)
+ xerr = kwargs.pop('xerr', None)
+ yerr = kwargs.pop('yerr', None)
+ ecolor = kwargs.pop('ecolor', None)
+ capsize = kwargs.pop('capsize', 3)
+ align = kwargs.pop('align', 'edge')
+ orientation = kwargs.pop('orientation', 'vertical')
+ log = kwargs.pop('log', False)
label = kwargs.pop('label', '')
def make_iterable(x):
if not iterable(x):
Modified: trunk/matplotlib/lib/matplotlib/pyplot.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/pyplot.py 2009-08-15 21:24:01 UTC (rev 7494)
+++ trunk/matplotlib/lib/matplotlib/pyplot.py 2009-08-15 23:05:52 UTC (rev 7495)
@@ -1713,7 +1713,7 @@
# This function was autogenerated by boilerplate.py. Do not edit as
# changes will be lost
@autogen_docstring(Axes.bar)
-def bar(left, height, width=0.80000000000000004, bottom=None, color=None, edgecolor=None, linewidth=None, yerr=None, xerr=None, ecolor=None, capsize=3, align='edge', orientation='vertical', log=False, hold=None, **kwargs):
+def bar(left, height, width=0.80000000000000004, bottom=None, hold=None, **kwargs):
ax = gca()
# allow callers to override the hold state by passing hold=True|False
washold = ax.ishold()
@@ -1721,7 +1721,7 @@
if hold is not None:
ax.hold(hold)
try:
- ret = ax.bar(left, height, width, bottom, color, edgecolor, linewidth, yerr, xerr, ecolor, capsize, align, orientation, log, **kwargs)
+ ret = ax.bar(left, height, width, bottom, **kwargs)
draw_if_interactive()
finally:
ax.hold(washold)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2009-08-15 21:24:09
|
Revision: 7494
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7494&view=rev
Author: efiring
Date: 2009-08-15 21:24:01 +0000 (Sat, 15 Aug 2009)
Log Message:
-----------
pyplot tracks current image at the figure and axes level;
fixes ticket 1656374
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/boilerplate.py
trunk/matplotlib/examples/pylab_examples/multi_image.py
trunk/matplotlib/lib/matplotlib/axes.py
trunk/matplotlib/lib/matplotlib/cbook.py
trunk/matplotlib/lib/matplotlib/figure.py
trunk/matplotlib/lib/matplotlib/pyplot.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2009-08-15 20:00:09 UTC (rev 7493)
+++ trunk/matplotlib/CHANGELOG 2009-08-15 21:24:01 UTC (rev 7494)
@@ -1,3 +1,6 @@
+2009-08-15 Pyplot interface: the current image is now tracked at the
+ figure and axes level, addressing tracker item 1656374. - EF
+
2009-08-15 Docstrings are now manipulated with decorators defined
in a new module, docstring.py, thanks to Jason Coombs. - EF
Modified: trunk/matplotlib/boilerplate.py
===================================================================
--- trunk/matplotlib/boilerplate.py 2009-08-15 20:00:09 UTC (rev 7493)
+++ trunk/matplotlib/boilerplate.py 2009-08-15 21:24:01 UTC (rev 7494)
@@ -1,5 +1,5 @@
# Wrap the plot commands defined in axes. The code generated by this
-# file is pasted into pylab.py. We did try to do this the smart way,
+# file is pasted into pyplot.py. We did try to do this the smart way,
# with callable functions and new.function, but could never get the
# docstrings right for python2.2. See
# http://groups.google.com/group/comp.lang.python/browse_frm/thread/dcd63ec13096a0f6/1b14640f3a4ad3dc?#1b14640f3a4ad3dc
@@ -13,7 +13,7 @@
import types
# import the local copy of matplotlib, not the installed one
-sys.path.insert(0, './lib')
+#sys.path.insert(0, './lib')
from matplotlib.axes import Axes
from matplotlib.cbook import dedent
@@ -104,16 +104,16 @@
)
cmappable = {
- 'contour' : 'if %(ret)s._A is not None: gci._current = %(ret)s',
- 'contourf': 'if %(ret)s._A is not None: gci._current = %(ret)s',
- 'hexbin' : 'gci._current = %(ret)s',
- 'scatter' : 'gci._current = %(ret)s',
- 'pcolor' : 'gci._current = %(ret)s',
- 'pcolormesh' : 'gci._current = %(ret)s',
- 'imshow' : 'gci._current = %(ret)s',
- 'spy' : 'gci._current = %(ret)s',
- 'quiver' : 'gci._current = %(ret)s',
- 'specgram' : 'gci._current = %(ret)s[-1]',
+ 'contour' : 'if %(ret)s._A is not None: sci(%(ret)s)',
+ 'contourf': 'if %(ret)s._A is not None: sci(%(ret)s)',
+ 'hexbin' : 'sci(%(ret)s)',
+ 'scatter' : 'sci(%(ret)s)',
+ 'pcolor' : 'sci(%(ret)s)',
+ 'pcolormesh': 'sci(%(ret)s)',
+ 'imshow' : 'sci(%(ret)s)',
+ 'spy' : 'sci(%(ret)s)',
+ 'quiver' : 'sci(%(ret)s)',
+ 'specgram' : 'sci(%(ret)s[-1])',
}
@@ -233,3 +233,4 @@
# add all the colormaps (autumn, hsv, ....)
for name in cmaps:
print _fmtcmap%locals()
+
Modified: trunk/matplotlib/examples/pylab_examples/multi_image.py
===================================================================
--- trunk/matplotlib/examples/pylab_examples/multi_image.py 2009-08-15 20:00:09 UTC (rev 7493)
+++ trunk/matplotlib/examples/pylab_examples/multi_image.py 2009-08-15 21:24:01 UTC (rev 7494)
@@ -5,7 +5,7 @@
It also illustrates colorbar tick labelling with a multiplier.
'''
-from matplotlib.pyplot import figure, show, sci
+from matplotlib.pyplot import figure, show, axes, sci
from matplotlib import cm, colors
from matplotlib.font_manager import FontProperties
from numpy import amin, amax, ravel
@@ -68,9 +68,11 @@
# The colorbar is also based on this master image.
fig.colorbar(images[0], cax, orientation='horizontal')
-# We need the following only if we want to run this
+# We need the following only if we want to run this interactively and
+# modify the colormap:
-sci(images[0])
+axes(ax[0]) # Return the current axes to the first one,
+sci(images[0]) # because the current image must be in current axes.
show()
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2009-08-15 20:00:09 UTC (rev 7493)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2009-08-15 21:24:01 UTC (rev 7494)
@@ -838,6 +838,7 @@
self.tables = []
self.artists = []
self.images = []
+ self._current_image = None # strictly for pyplot via _sci, _gci
self.legend_ = None
self.collections = [] # collection.Collection instances
@@ -1309,6 +1310,27 @@
#### Adding and tracking artists
+ def _sci(self, im):
+ """
+ helper for :func:`~matplotlib.pyplot.sci`;
+ do not use elsewhere.
+ """
+ if isinstance(im, matplotlib.contour.ContourSet):
+ if im.collections[0] not in self.collections:
+ raise ValueError(
+ "ContourSet must be in current Axes")
+ elif im not in self.images and im not in self.collections:
+ raise ValueError(
+ "Argument must be an image, collection, or ContourSet in this Axes")
+ self._current_image = im
+
+ def _gci(self):
+ """
+ helper for :func:`~matplotlib.pyplot.gci`;
+ do not use elsewhere.
+ """
+ return self._current_image
+
def has_data(self):
'''Return *True* if any artists have been added to axes.
Modified: trunk/matplotlib/lib/matplotlib/cbook.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/cbook.py 2009-08-15 20:00:09 UTC (rev 7493)
+++ trunk/matplotlib/lib/matplotlib/cbook.py 2009-08-15 21:24:01 UTC (rev 7494)
@@ -1007,7 +1007,7 @@
-class Stack:
+class Stack(object):
"""
Implement a stack where elements can be pushed on and you can move
back and forth. But no pop. Should mimic home / back / forward
@@ -1023,6 +1023,12 @@
if not len(self._elements): return self._default
else: return self._elements[self._pos]
+ def __len__(self):
+ return self._elements.__len__()
+
+ def __getitem__(self, ind):
+ return self._elements.__getitem__(ind)
+
def forward(self):
'move the position forward and return the current element'
N = len(self._elements)
Modified: trunk/matplotlib/lib/matplotlib/figure.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/figure.py 2009-08-15 20:00:09 UTC (rev 7493)
+++ trunk/matplotlib/lib/matplotlib/figure.py 2009-08-15 21:24:01 UTC (rev 7494)
@@ -950,6 +950,17 @@
for func in self._axobservers: func(self)
return a
+ def _gci(self):
+ """
+ helper for :func:`~matplotlib.pyplot.gci`;
+ do not use elsewhere.
+ """
+ for ax in reversed(self._axstack):
+ im = ax._gci()
+ if im is not None:
+ return im
+ return None
+
def add_axobserver(self, func):
'whenever the axes state change, func(self) will be called'
self._axobservers.append(func)
@@ -1039,7 +1050,7 @@
def colorbar(self, mappable, cax=None, ax=None, **kw):
"""
Create a colorbar for a ScalarMappable instance.
-
+
Documentation for the pylab thin wrapper:
%(colorbar_doc)s
"""
Modified: trunk/matplotlib/lib/matplotlib/pyplot.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/pyplot.py 2009-08-15 20:00:09 UTC (rev 7493)
+++ trunk/matplotlib/lib/matplotlib/pyplot.py 2009-08-15 21:24:01 UTC (rev 7494)
@@ -129,8 +129,10 @@
matplotlib.rcdefaults()
draw_if_interactive()
-# The current "image" (ScalarMappable) is tracked here on a
-# per-pylab-session basis:
+# The current "image" (ScalarMappable) is retrieved or set
+# only via the pyplot interface using the following two
+# functions:
+
def gci():
"""
Get the current :class:`~matplotlib.cm.ScalarMappable` instance
@@ -142,18 +144,20 @@
:func:`~matplotlib.pyplot.pcolor` and
:func:`~matplotlib.pyplot.scatter` create
:class:`~matplotlib.collections.Collection` instances.
+ The current image is an attribute of the current axes, or the
+ nearest earlier axes in the current figure that contains an
+ image.
"""
- return gci._current
-gci._current = None
+ return gcf()._gci()
-
def sci(im):
"""
Set the current image (target of colormap commands like
:func:`~matplotlib.pyplot.jet`, :func:`~matplotlib.pyplot.hot` or
- :func:`~matplotlib.pyplot.clim`).
+ :func:`~matplotlib.pyplot.clim`). The current image is an
+ attribute of the current axes.
"""
- gci._current = im
+ gca()._sci(im)
## Any Artist ##
@@ -1598,7 +1602,6 @@
## Plotting part 2: autogenerated wrappers for axes methods ##
-
# This function was autogenerated by boilerplate.py. Do not edit as
# changes will be lost
@autogen_docstring(Axes.acorr)
@@ -1830,7 +1833,7 @@
draw_if_interactive()
finally:
ax.hold(washold)
- if ret._A is not None: gci._current = ret
+ if ret._A is not None: sci(ret)
return ret
# This function was autogenerated by boilerplate.py. Do not edit as
@@ -1848,7 +1851,7 @@
draw_if_interactive()
finally:
ax.hold(washold)
- if ret._A is not None: gci._current = ret
+ if ret._A is not None: sci(ret)
return ret
# This function was autogenerated by boilerplate.py. Do not edit as
@@ -1956,7 +1959,7 @@
draw_if_interactive()
finally:
ax.hold(washold)
- gci._current = ret
+ sci(ret)
return ret
# This function was autogenerated by boilerplate.py. Do not edit as
@@ -2010,7 +2013,7 @@
draw_if_interactive()
finally:
ax.hold(washold)
- gci._current = ret
+ sci(ret)
return ret
# This function was autogenerated by boilerplate.py. Do not edit as
@@ -2046,7 +2049,7 @@
draw_if_interactive()
finally:
ax.hold(washold)
- gci._current = ret
+ sci(ret)
return ret
# This function was autogenerated by boilerplate.py. Do not edit as
@@ -2064,7 +2067,7 @@
draw_if_interactive()
finally:
ax.hold(washold)
- gci._current = ret
+ sci(ret)
return ret
# This function was autogenerated by boilerplate.py. Do not edit as
@@ -2154,7 +2157,7 @@
draw_if_interactive()
finally:
ax.hold(washold)
- gci._current = ret
+ sci(ret)
return ret
# This function was autogenerated by boilerplate.py. Do not edit as
@@ -2190,7 +2193,7 @@
draw_if_interactive()
finally:
ax.hold(washold)
- gci._current = ret
+ sci(ret)
return ret
# This function was autogenerated by boilerplate.py. Do not edit as
@@ -2244,7 +2247,7 @@
draw_if_interactive()
finally:
ax.hold(washold)
- gci._current = ret[-1]
+ sci(ret[-1])
return ret
# This function was autogenerated by boilerplate.py. Do not edit as
@@ -2262,7 +2265,7 @@
draw_if_interactive()
finally:
ax.hold(washold)
- gci._current = ret
+ sci(ret)
return ret
# This function was autogenerated by boilerplate.py. Do not edit as
@@ -2628,3 +2631,5 @@
draw_if_interactive()
+
+
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jo...@us...> - 2009-08-15 20:00:23
|
Revision: 7493
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7493&view=rev
Author: jouni
Date: 2009-08-15 20:00:09 +0000 (Sat, 15 Aug 2009)
Log Message:
-----------
get_sample_data improvements: remove old files from subdirectories and
not only the top-level directory; try to handle the disconnected use case;
use the perhaps more stable svnroot URL instead of the viewvc one
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/cbook.py
Modified: trunk/matplotlib/lib/matplotlib/cbook.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/cbook.py 2009-08-15 18:37:25 UTC (rev 7492)
+++ trunk/matplotlib/lib/matplotlib/cbook.py 2009-08-15 20:00:09 UTC (rev 7493)
@@ -355,7 +355,7 @@
class ViewVCCachedServer(urllib2.BaseHandler):
"""
Urllib2 handler that takes care of caching files.
- The file cache.pck holds the directory of files to be cached.
+ The file cache.pck holds the directory of files that have been cached.
"""
def __init__(self, cache_dir, baseurl):
self.cache_dir = cache_dir
@@ -386,9 +386,14 @@
cache = cPickle.load(f)
f.close()
+ # Earlier versions did not have the full paths in cache.pck
+ for url, (fn, x, y) in cache.items():
+ if not os.path.isabs(fn):
+ cache[url] = (self.in_cache_dir(fn), x, y)
+
# If any files are deleted, drop them from the cache
for url, (fn, _, _) in cache.items():
- if not os.path.exists(self.in_cache_dir(fn)):
+ if not os.path.exists(fn):
del cache[url]
self.cache = cache
@@ -398,15 +403,21 @@
Remove files from the cache directory that are not listed in
cache.pck.
"""
- listed = set([fn for (_, (fn, _, _)) in self.cache.items()])
- for path in os.listdir(self.cache_dir):
- if path not in listed and path != 'cache.pck':
- thisfile = os.path.join(self.cache_dir, path)
- if not os.path.isdir(thisfile):
- matplotlib.verbose.report('ViewVCCachedServer:remove_stale_files: removing %s'%thisfile,
- level='debug')
- os.remove(thisfile)
+ # TODO: remove empty subdirectories
+ listed = set(fn for (_, (fn, _, _)) in self.cache.items())
+ existing = reduce(set.union,
+ (set(os.path.join(dirpath, fn) for fn in filenames)
+ for (dirpath, _, filenames) in os.walk(self.cache_dir)))
+ matplotlib.verbose.report(
+ 'ViewVCCachedServer: files listed in cache.pck: %s' % listed, 'debug')
+ matplotlib.verbose.report(
+ 'ViewVCCachedServer: files in cache directory: %s' % existing, 'debug')
+ for path in existing - listed - set([self.in_cache_dir('cache.pck')]):
+ matplotlib.verbose.report('ViewVCCachedServer:remove_stale_files: removing %s'%path,
+ level='debug')
+ os.remove(path)
+
def write_cache(self):
"""
Write the cache data structure into the cache directory.
@@ -424,17 +435,12 @@
fn = url[len(self.baseurl):]
fullpath = self.in_cache_dir(fn)
- #while os.path.exists(self.in_cache_dir(fn)):
- # fn = rightmost + '.' + str(random.randint(0,9999999))
-
-
-
- f = open(self.in_cache_dir(fn), 'wb')
+ f = open(fullpath, 'wb')
f.write(data)
f.close()
# Update the cache
- self.cache[url] = (fn, headers.get('ETag'), headers.get('Last-Modified'))
+ self.cache[url] = (fullpath, headers.get('ETag'), headers.get('Last-Modified'))
self.write_cache()
# These urllib2 entry points are used:
@@ -459,9 +465,9 @@
"""
url = req.get_full_url()
fn, _, _ = self.cache[url]
- cachefile = self.in_cache_dir(fn)
- matplotlib.verbose.report('ViewVCCachedServer: reading data file from cache file "%s"'%cachefile)
- file = open(cachefile, 'rb')
+ matplotlib.verbose.report('ViewVCCachedServer: reading data file from cache file "%s"'
+ %fn, 'debug')
+ file = open(fn, 'rb')
handle = urllib2.addinfourl(file, hdrs, url)
handle.code = 304
return handle
@@ -470,6 +476,8 @@
"""
Update the cache with the returned file.
"""
+ matplotlib.verbose.report('ViewVCCachedServer: received response %d: %s'
+ % (response.code, response.msg), 'debug')
if response.code != 200:
return response
else:
@@ -489,11 +497,11 @@
store it in the cachedir.
If asfileobj is True, a file object will be returned. Else the
- path to the file as a string will be returned
-
+ path to the file as a string will be returned.
"""
+ # TODO: time out if the connection takes forever
+ # (may not be possible with urllib2 only - spawn a helper process?)
-
# quote is not in python2.4, so check for it and get it from
# urllib if it is not available
quote = getattr(urllib2, 'quote', None)
@@ -501,13 +509,25 @@
import urllib
quote = urllib.quote
+ # retrieve the URL for the side effect of refreshing the cache
url = self.baseurl + quote(fname)
- response = self.opener.open(url)
+ error = 'unknown error'
+ matplotlib.verbose.report('ViewVCCachedServer: retrieving %s'
+ % url, 'debug')
+ try:
+ response = self.opener.open(url)
+ except urllib2.URLError, e:
+ # could be a missing network connection
+ error = str(e)
+ cached = self.cache.get(url)
+ if cached is None:
+ msg = 'file %s not in cache; received %s when trying to retrieve' \
+ % (fname, error)
+ raise KeyError(msg)
+
+ fname = cached[0]
- relpath = self.cache[url][0]
- fname = self.in_cache_dir(relpath)
-
if asfileobj:
return file(fname)
else:
@@ -519,7 +539,7 @@
Check the cachedirectory ~/.matplotlib/sample_data for a sample_data
file. If it does not exist, fetch it with urllib from the mpl svn repo
- http://matplotlib.svn.sourceforge.net/viewvc/matplotlib/trunk/sample_data/
+ http://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk/sample_data/
and store it in the cachedir.
@@ -539,7 +559,7 @@
if myserver is None:
configdir = matplotlib.get_configdir()
cachedir = os.path.join(configdir, 'sample_data')
- baseurl = 'http://matplotlib.svn.sourceforge.net/viewvc/matplotlib/trunk/sample_data/'
+ baseurl = 'http://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk/sample_data/'
myserver = get_sample_data.myserver = ViewVCCachedServer(cachedir, baseurl)
return myserver.get_sample_data(fname, asfileobj=asfileobj)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2009-08-15 18:37:39
|
Revision: 7492
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7492&view=rev
Author: efiring
Date: 2009-08-15 18:37:25 +0000 (Sat, 15 Aug 2009)
Log Message:
-----------
Add CHANGELOG entry for Coombs docstring work.
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2009-08-15 18:33:54 UTC (rev 7491)
+++ trunk/matplotlib/CHANGELOG 2009-08-15 18:37:25 UTC (rev 7492)
@@ -1,3 +1,6 @@
+2009-08-15 Docstrings are now manipulated with decorators defined
+ in a new module, docstring.py, thanks to Jason Coombs. - EF
+
2009-08-14 Add support for image filtering for agg back end. See the example
demo_agg_filter.py. -JJL
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2009-08-15 18:34:05
|
Revision: 7491
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7491&view=rev
Author: efiring
Date: 2009-08-15 18:33:54 +0000 (Sat, 15 Aug 2009)
Log Message:
-----------
Use decorators to manipulate docstrings; patch by Jason Coombs
Tracker 2835685, file DocstringOptimizedTypeErrorRev5.patch
Modified Paths:
--------------
trunk/matplotlib/boilerplate.py
trunk/matplotlib/lib/matplotlib/artist.py
trunk/matplotlib/lib/matplotlib/axes.py
trunk/matplotlib/lib/matplotlib/collections.py
trunk/matplotlib/lib/matplotlib/colorbar.py
trunk/matplotlib/lib/matplotlib/figure.py
trunk/matplotlib/lib/matplotlib/lines.py
trunk/matplotlib/lib/matplotlib/mlab.py
trunk/matplotlib/lib/matplotlib/offsetbox.py
trunk/matplotlib/lib/matplotlib/patches.py
trunk/matplotlib/lib/matplotlib/projections/geo.py
trunk/matplotlib/lib/matplotlib/projections/polar.py
trunk/matplotlib/lib/matplotlib/pyplot.py
trunk/matplotlib/lib/matplotlib/quiver.py
trunk/matplotlib/lib/matplotlib/scale.py
trunk/matplotlib/lib/matplotlib/spines.py
trunk/matplotlib/lib/matplotlib/table.py
trunk/matplotlib/lib/matplotlib/text.py
Modified: trunk/matplotlib/boilerplate.py
===================================================================
--- trunk/matplotlib/boilerplate.py 2009-08-15 17:56:44 UTC (rev 7490)
+++ trunk/matplotlib/boilerplate.py 2009-08-15 18:33:54 UTC (rev 7491)
@@ -20,6 +20,7 @@
_fmtplot = """\
# This function was autogenerated by boilerplate.py. Do not edit as
# changes will be lost
+@autogen_docstring(Axes.%(func)s)
def %(func)s(%(argspec)s):
%(ax)s = gca()
# allow callers to override the hold state by passing hold=True|False
@@ -34,19 +35,16 @@
%(ax)s.hold(%(washold)s)
%(mappable)s
return %(ret)s
-if Axes.%(func)s.__doc__ is not None:
- %(func)s.__doc__ = dedent(Axes.%(func)s.__doc__) + __docstring_addendum
"""
_fmtmisc = """\
# This function was autogenerated by boilerplate.py. Do not edit as
# changes will be lost
+@docstring.copy_dedent(Axes.%(func)s)
def %(func)s(%(argspec)s):
%(ret)s = gca().%(func)s(%(call)s)
draw_if_interactive()
return %(ret)s
-if Axes.%(func)s.__doc__ is not None:
- %(func)s.__doc__ = dedent(Axes.%(func)s.__doc__)
"""
# these methods are all simple wrappers of Axes methods by the same
Modified: trunk/matplotlib/lib/matplotlib/artist.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/artist.py 2009-08-15 17:56:44 UTC (rev 7490)
+++ trunk/matplotlib/lib/matplotlib/artist.py 2009-08-15 18:33:54 UTC (rev 7491)
@@ -2,6 +2,7 @@
import re, warnings
import matplotlib
import matplotlib.cbook as cbook
+from matplotlib import docstring
from transforms import Bbox, IdentityTransform, TransformedBbox, TransformedPath
from path import Path
@@ -1193,5 +1194,4 @@
else:
return '\n'.join(ArtistInspector(a).pprint_setters(leadingspace=2))
-kwdocd = dict()
-kwdocd['Artist'] = kwdoc(Artist)
+docstring.interpd.update(Artist=kwdoc(Artist))
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2009-08-15 17:56:44 UTC (rev 7490)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2009-08-15 18:33:54 UTC (rev 7491)
@@ -15,6 +15,7 @@
import matplotlib.colors as mcolors
import matplotlib.contour as mcontour
import matplotlib.dates as mdates
+from matplotlib import docstring
import matplotlib.font_manager as font_manager
import matplotlib.image as mimage
import matplotlib.legend as mlegend
@@ -33,7 +34,6 @@
is_string_like = cbook.is_string_like
is_sequence_of_strings = cbook.is_sequence_of_strings
-
def _process_plot_format(fmt):
"""
Process a matlab(TM) style color/line style format string. Return a
@@ -1787,6 +1787,7 @@
"""
self._axisbelow = b
+ @docstring.dedent_interpd
def grid(self, b=None, **kwargs):
"""
call signature::
@@ -1810,7 +1811,6 @@
if len(kwargs): b = True
self.xaxis.grid(b, **kwargs)
self.yaxis.grid(b, **kwargs)
- grid.__doc__ = cbook.dedent(grid.__doc__) % martist.kwdocd
def ticklabel_format(self, **kwargs):
"""
@@ -2018,6 +2018,7 @@
", ".join(mscale.get_scale_names()))
return self.xaxis.get_scale()
+ @docstring.dedent_interpd
def set_xscale(self, value, **kwargs):
"""
call signature::
@@ -2035,10 +2036,6 @@
self.autoscale_view()
self._update_transScale()
- set_xscale.__doc__ = cbook.dedent(set_xscale.__doc__) % {
- 'scale': ' | '.join([repr(x) for x in mscale.get_scale_names()]),
- 'scale_docs': mscale.get_scale_docs().strip()}
-
def get_xticks(self, minor=False):
'Return the x ticks as a list of locations'
return self.xaxis.get_ticklocs(minor=minor)
@@ -2066,6 +2063,7 @@
return cbook.silent_list('Text xticklabel',
self.xaxis.get_ticklabels(minor=minor))
+ @docstring.dedent_interpd
def set_xticklabels(self, labels, fontdict=None, minor=False, **kwargs):
"""
call signature::
@@ -2083,8 +2081,6 @@
"""
return self.xaxis.set_ticklabels(labels, fontdict,
minor=minor, **kwargs)
- set_xticklabels.__doc__ = cbook.dedent(
- set_xticklabels.__doc__) % martist.kwdocd
def invert_yaxis(self):
"Invert the y-axis."
@@ -2192,6 +2188,7 @@
", ".join(mscale.get_scale_names()))
return self.yaxis.get_scale()
+ @docstring.dedent_interpd
def set_yscale(self, value, **kwargs):
"""
call signature::
@@ -2209,10 +2206,6 @@
self.autoscale_view()
self._update_transScale()
- set_yscale.__doc__ = cbook.dedent(set_yscale.__doc__) % {
- 'scale': ' | '.join([repr(x) for x in mscale.get_scale_names()]),
- 'scale_docs': mscale.get_scale_docs().strip()}
-
def get_yticks(self, minor=False):
'Return the y ticks as a list of locations'
return self.yaxis.get_ticklocs(minor=minor)
@@ -2245,6 +2238,7 @@
return cbook.silent_list('Text yticklabel',
self.yaxis.get_ticklabels(minor=minor))
+ @docstring.dedent_interpd
def set_yticklabels(self, labels, fontdict=None, minor=False, **kwargs):
"""
call signature::
@@ -2262,8 +2256,6 @@
"""
return self.yaxis.set_ticklabels(labels, fontdict,
minor=minor, **kwargs)
- set_yticklabels.__doc__ = cbook.dedent(
- set_yticklabels.__doc__) % martist.kwdocd
def xaxis_date(self, tz=None):
"""Sets up x-axis ticks and labels that treat the x data as dates.
@@ -2693,6 +2685,7 @@
"""
return self.title.get_text()
+ @docstring.dedent_interpd
def set_title(self, label, fontdict=None, **kwargs):
"""
call signature::
@@ -2722,7 +2715,6 @@
if fontdict is not None: self.title.update(fontdict)
self.title.update(kwargs)
return self.title
- set_title.__doc__ = cbook.dedent(set_title.__doc__) % martist.kwdocd
def get_xlabel(self):
"""
@@ -2731,6 +2723,7 @@
label = self.xaxis.get_label()
return label.get_text()
+ @docstring.dedent_interpd
def set_xlabel(self, xlabel, fontdict=None, labelpad=None, **kwargs):
"""
call signature::
@@ -2752,7 +2745,6 @@
"""
if labelpad is not None: self.xaxis.labelpad = labelpad
return self.xaxis.set_label_text(xlabel, fontdict, **kwargs)
- set_xlabel.__doc__ = cbook.dedent(set_xlabel.__doc__) % martist.kwdocd
def get_ylabel(self):
"""
@@ -2761,6 +2753,7 @@
label = self.yaxis.get_label()
return label.get_text()
+ @docstring.dedent_interpd
def set_ylabel(self, ylabel, fontdict=None, labelpad=None, **kwargs):
"""
call signature::
@@ -2782,8 +2775,8 @@
"""
if labelpad is not None: self.yaxis.labelpad = labelpad
return self.yaxis.set_label_text(ylabel, fontdict, **kwargs)
- set_ylabel.__doc__ = cbook.dedent(set_ylabel.__doc__) % martist.kwdocd
+ @docstring.dedent_interpd
def text(self, x, y, s, fontdict=None,
withdash=False, **kwargs):
"""
@@ -2864,8 +2857,8 @@
#if t.get_clip_on(): t.set_clip_box(self.bbox)
if 'clip_on' in kwargs: t.set_clip_box(self.bbox)
return t
- text.__doc__ = cbook.dedent(text.__doc__) % martist.kwdocd
+ @docstring.dedent_interpd
def annotate(self, *args, **kwargs):
"""
call signature::
@@ -2885,10 +2878,10 @@
if kwargs.has_key('clip_on'): a.set_clip_path(self.patch)
self.texts.append(a)
return a
- annotate.__doc__ = cbook.dedent(annotate.__doc__) % martist.kwdocd
#### Lines and spans
+ @docstring.dedent_interpd
def axhline(self, y=0, xmin=0, xmax=1, **kwargs):
"""
call signature::
@@ -2948,8 +2941,7 @@
self.autoscale_view(scalex=False, scaley=scaley)
return l
- axhline.__doc__ = cbook.dedent(axhline.__doc__) % martist.kwdocd
-
+ @docstring.dedent_interpd
def axvline(self, x=0, ymin=0, ymax=1, **kwargs):
"""
call signature::
@@ -3009,8 +3001,7 @@
self.autoscale_view(scalex=scalex, scaley=False)
return l
- axvline.__doc__ = cbook.dedent(axvline.__doc__) % martist.kwdocd
-
+ @docstring.dedent_interpd
def axhspan(self, ymin, ymax, xmin=0, xmax=1, **kwargs):
"""
call signature::
@@ -3066,8 +3057,8 @@
self.add_patch(p)
self.autoscale_view(scalex=False)
return p
- axhspan.__doc__ = cbook.dedent(axhspan.__doc__) % martist.kwdocd
+ @docstring.dedent_interpd
def axvspan(self, xmin, xmax, ymin=0, ymax=1, **kwargs):
"""
call signature::
@@ -3123,9 +3114,9 @@
self.add_patch(p)
self.autoscale_view(scaley=False)
return p
- axvspan.__doc__ = cbook.dedent(axvspan.__doc__) % martist.kwdocd
+ @docstring.dedent
def hlines(self, y, xmin, xmax, colors='k', linestyles='solid',
label='', **kwargs):
"""
@@ -3210,8 +3201,8 @@
return coll
- hlines.__doc__ = cbook.dedent(hlines.__doc__)
+ @docstring.dedent_interpd
def vlines(self, x, ymin, ymax, colors='k', linestyles='solid',
label='', **kwargs):
"""
@@ -3290,9 +3281,9 @@
self.autoscale_view()
return coll
- vlines.__doc__ = cbook.dedent(vlines.__doc__) % martist.kwdocd
#### Basic plotting
+ @docstring.dedent_interpd
def plot(self, *args, **kwargs):
"""
Plot lines and/or markers to the
@@ -3425,8 +3416,7 @@
self.autoscale_view(scalex=scalex, scaley=scaley)
return lines
- plot.__doc__ = cbook.dedent(plot.__doc__) % martist.kwdocd
-
+ @docstring.dedent_interpd
def plot_date(self, x, y, fmt='bo', tz=None, xdate=True, ydate=False,
**kwargs):
"""
@@ -3496,9 +3486,9 @@
self.autoscale_view()
return ret
- plot_date.__doc__ = cbook.dedent(plot_date.__doc__) % martist.kwdocd
+ @docstring.dedent_interpd
def loglog(self, *args, **kwargs):
"""
call signature::
@@ -3557,8 +3547,8 @@
self._hold = b # restore the hold
return l
- loglog.__doc__ = cbook.dedent(loglog.__doc__) % martist.kwdocd
+ @docstring.dedent_interpd
def semilogx(self, *args, **kwargs):
"""
call signature::
@@ -3608,8 +3598,8 @@
l = self.plot(*args, **kwargs)
self._hold = b # restore the hold
return l
- semilogx.__doc__ = cbook.dedent(semilogx.__doc__) % martist.kwdocd
+ @docstring.dedent_interpd
def semilogy(self, *args, **kwargs):
"""
call signature::
@@ -3659,8 +3649,8 @@
self._hold = b # restore the hold
return l
- semilogy.__doc__ = cbook.dedent(semilogy.__doc__) % martist.kwdocd
+ @docstring.dedent_interpd
def acorr(self, x, **kwargs):
"""
call signature::
@@ -3722,8 +3712,8 @@
.. plot:: mpl_examples/pylab_examples/xcorr_demo.py
"""
return self.xcorr(x, x, **kwargs)
- acorr.__doc__ = cbook.dedent(acorr.__doc__) % martist.kwdocd
+ @docstring.dedent_interpd
def xcorr(self, x, y, normed=True, detrend=mlab.detrend_none,
usevlines=True, maxlags=10, **kwargs):
"""
@@ -3810,7 +3800,6 @@
a, = self.plot(lags, c, **kwargs)
b = None
return lags, c, a, b
- xcorr.__doc__ = cbook.dedent(xcorr.__doc__) % martist.kwdocd
def _get_legend_handles(self):
@@ -4064,6 +4053,7 @@
return self.plot(x, y, *args, **kwargs)
+ @docstring.dedent_interpd
def bar(self, left, height, width=0.8, bottom=None,
color=None, edgecolor=None, linewidth=None,
yerr=None, xerr=None, ecolor=None, capsize=3,
@@ -4331,8 +4321,8 @@
self.dataLim.intervaly = (ymin, ymax)
self.autoscale_view()
return patches
- bar.__doc__ = cbook.dedent(bar.__doc__) % martist.kwdocd
+ @docstring.dedent_interpd
def barh(self, bottom, width, height=0.8, left=None, **kwargs):
"""
call signature::
@@ -4403,8 +4393,7 @@
orientation='horizontal', **kwargs)
return patches
- barh.__doc__ = cbook.dedent(barh.__doc__) % martist.kwdocd
-
+ @docstring.dedent_interpd
def broken_barh(self, xranges, yrange, **kwargs):
"""
call signature::
@@ -4447,8 +4436,6 @@
return col
- broken_barh.__doc__ = cbook.dedent(broken_barh.__doc__) % martist.kwdocd
-
def stem(self, x, y, linefmt='b-', markerfmt='bo', basefmt='r-'):
"""
call signature::
@@ -4642,6 +4629,7 @@
if autopct is None: return slices, texts
else: return slices, texts, autotexts
+ @docstring.dedent_interpd
def errorbar(self, x, y, yerr=None, xerr=None,
fmt='-', ecolor=None, elinewidth=None, capsize=3,
barsabove=False, lolims=False, uplims=False,
@@ -4900,7 +4888,6 @@
self.autoscale_view()
return (l0, caplines, barcols)
- errorbar.__doc__ = cbook.dedent(errorbar.__doc__) % martist.kwdocd
def boxplot(self, x, notch=0, sym='b+', vert=1, whis=1.5,
positions=None, widths=None):
@@ -5092,6 +5079,7 @@
return dict(whiskers=whiskers, caps=caps, boxes=boxes,
medians=medians, fliers=fliers)
+ @docstring.dedent_interpd
def scatter(self, x, y, s=20, c='b', marker='o', cmap=None, norm=None,
vmin=None, vmax=None, alpha=1.0, linewidths=None,
faceted=True, verts=None,
@@ -5407,8 +5395,7 @@
self.add_collection(collection)
return collection
- scatter.__doc__ = cbook.dedent(scatter.__doc__) % martist.kwdocd
-
+ @docstring.dedent_interpd
def hexbin(self, x, y, C = None, gridsize = 100, bins = None,
xscale = 'linear', yscale = 'linear', extent = None,
cmap=None, norm=None, vmin=None, vmax=None,
@@ -5821,9 +5808,8 @@
return collection
- hexbin.__doc__ = cbook.dedent(hexbin.__doc__) % martist.kwdocd
-
+ @docstring.dedent_interpd
def arrow(self, x, y, dx, dy, **kwargs):
"""
call signature::
@@ -5843,7 +5829,6 @@
a = mpatches.FancyArrow(x, y, dx, dy, **kwargs)
self.add_artist(a)
return a
- arrow.__doc__ = cbook.dedent(arrow.__doc__) % martist.kwdocd
def quiverkey(self, *args, **kw):
qk = mquiver.QuiverKey(*args, **kw)
@@ -5860,6 +5845,7 @@
return q
quiver.__doc__ = mquiver.Quiver.quiver_doc
+ @docstring.dedent_interpd
def barbs(self, *args, **kw):
"""
%(barbs_doc)s
@@ -5873,9 +5859,8 @@
self.update_datalim(b.get_offsets())
self.autoscale_view()
return b
- barbs.__doc__ = cbook.dedent(barbs.__doc__) % {
- 'barbs_doc': mquiver.Barbs.barbs_doc}
+ @docstring.dedent_interpd
def fill(self, *args, **kwargs):
"""
call signature::
@@ -5922,8 +5907,8 @@
patches.append( poly )
self.autoscale_view()
return patches
- fill.__doc__ = cbook.dedent(fill.__doc__) % martist.kwdocd
+ @docstring.dedent_interpd
def fill_between(self, x, y1, y2=0, where=None, **kwargs):
"""
call signature::
@@ -6029,8 +6014,8 @@
self.add_collection(collection)
self.autoscale_view()
return collection
- fill_between.__doc__ = cbook.dedent(fill_between.__doc__) % martist.kwdocd
+ @docstring.dedent_interpd
def fill_betweenx(self, y, x1, x2=0, where=None, **kwargs):
"""
call signature::
@@ -6136,10 +6121,10 @@
self.add_collection(collection)
self.autoscale_view()
return collection
- fill_between.__doc__ = cbook.dedent(fill_between.__doc__) % martist.kwdocd
#### plotting z(x,y): imshow, pcolor and relatives, contour
+ @docstring.dedent_interpd
def imshow(self, X, cmap=None, norm=None, aspect=None,
interpolation=None, alpha=1.0, vmin=None, vmax=None,
origin=None, extent=None, shape=None, filternorm=1,
@@ -6276,7 +6261,6 @@
self.images.append(im)
return im
- imshow.__doc__ = cbook.dedent(imshow.__doc__) % martist.kwdocd
def _pcolorargs(self, funcname, *args):
@@ -6304,6 +6288,7 @@
funcname, funcname))
return X, Y, C
+ @docstring.dedent_interpd
def pcolor(self, *args, **kwargs):
"""
call signatures::
@@ -6511,8 +6496,8 @@
self.autoscale_view()
self.add_collection(collection)
return collection
- pcolor.__doc__ = cbook.dedent(pcolor.__doc__) % martist.kwdocd
+ @docstring.dedent_interpd
def pcolormesh(self, *args, **kwargs):
"""
call signatures::
@@ -6634,8 +6619,8 @@
self.autoscale_view()
self.add_collection(collection)
return collection
- pcolormesh.__doc__ = cbook.dedent(pcolormesh.__doc__) % martist.kwdocd
+ @docstring.dedent_interpd
def pcolorfast(self, *args, **kwargs):
"""
pseudocolor plot of a 2-D array
@@ -6829,6 +6814,7 @@
return CS.clabel(*args, **kwargs)
clabel.__doc__ = mcontour.ContourSet.clabel.__doc__
+ @docstring.dedent_interpd
def table(self, **kwargs):
"""
call signature::
@@ -6853,7 +6839,6 @@
%(Table)s
"""
return mtable.table(self, **kwargs)
- table.__doc__ = cbook.dedent(table.__doc__) % martist.kwdocd
def twinx(self):
"""
@@ -6905,6 +6890,7 @@
#### Data analysis
+ @docstring.dedent_interpd
def hist(self, x, bins=10, range=None, normed=False, weights=None,
cumulative=False, bottom=None, histtype='bar', align='mid',
orientation='vertical', rwidth=None, log=False,
@@ -7257,8 +7243,8 @@
return n[0], bins, cbook.silent_list('Patch', patches[0])
else:
return n, bins, cbook.silent_list('Lists of Patches', patches)
- hist.__doc__ = cbook.dedent(hist.__doc__) % martist.kwdocd
+ @docstring.dedent_interpd
def psd(self, x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=0, pad_to=None,
sides='default', scale_by_freq=None, **kwargs):
@@ -7330,12 +7316,7 @@
return pxx, freqs
- psd_doc_dict = dict()
- psd_doc_dict.update(martist.kwdocd)
- psd_doc_dict.update(mlab.kwdocd)
- psd_doc_dict['PSD'] = cbook.dedent(psd_doc_dict['PSD'])
- psd.__doc__ = cbook.dedent(psd.__doc__) % psd_doc_dict
-
+ @docstring.dedent_interpd
def csd(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=0, pad_to=None,
sides='default', scale_by_freq=None, **kwargs):
@@ -7403,8 +7384,8 @@
self.set_yticks(ticks)
return pxy, freqs
- csd.__doc__ = cbook.dedent(csd.__doc__) % psd_doc_dict
+ @docstring.dedent_interpd
def cohere(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=0, pad_to=None,
sides='default', scale_by_freq=None, **kwargs):
@@ -7460,8 +7441,8 @@
self.grid(True)
return cxy, freqs
- cohere.__doc__ = cbook.dedent(cohere.__doc__) % psd_doc_dict
+ @docstring.dedent_interpd
def specgram(self, x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=128,
cmap=None, xextent=None, pad_to=None, sides='default',
@@ -7534,8 +7515,6 @@
self.axis('auto')
return Pxx, freqs, bins, im
- specgram.__doc__ = cbook.dedent(specgram.__doc__) % psd_doc_dict
- del psd_doc_dict #So that this does not become an Axes attribute
def spy(self, Z, precision=0, marker=None, markersize=None,
aspect='equal', **kwargs):
@@ -7908,7 +7887,8 @@
# This is provided for backward compatibility
Subplot = subplot_class_factory()
-martist.kwdocd['Axes'] = martist.kwdocd['Subplot'] = martist.kwdoc(Axes)
+docstring.interpd.update(Axes=martist.kwdoc(Axes))
+docstring.interpd.update(Subplot=martist.kwdoc(Axes))
"""
# this is some discarded code I was using to find the minimum positive
Modified: trunk/matplotlib/lib/matplotlib/collections.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/collections.py 2009-08-15 17:56:44 UTC (rev 7490)
+++ trunk/matplotlib/lib/matplotlib/collections.py 2009-08-15 18:33:54 UTC (rev 7491)
@@ -15,6 +15,7 @@
import matplotlib.cbook as cbook
import matplotlib.colors as mcolors
import matplotlib.cm as cm
+from matplotlib import docstring
import matplotlib.transforms as transforms
import matplotlib.artist as artist
from matplotlib.artist import allow_rasterization
@@ -496,7 +497,7 @@
# these are not available for the object inspector until after the
# class is built so we define an initial set here for the init
# function and they will be overridden after object defn
-artist.kwdocd['Collection'] = """\
+docstring.interpd.update(Collection = """\
Valid Collection keyword arguments:
* *edgecolors*: None
@@ -516,12 +517,13 @@
If any of *edgecolors*, *facecolors*, *linewidths*, *antialiaseds*
are None, they default to their :data:`matplotlib.rcParams` patch
setting, in sequence form.
-"""
+""")
class PathCollection(Collection):
"""
This is the most basic :class:`Collection` subclass.
"""
+ @docstring.dedent_interpd
def __init__(self, paths, **kwargs):
"""
*paths* is a sequence of :class:`matplotlib.path.Path`
@@ -532,7 +534,6 @@
Collection.__init__(self, **kwargs)
self.set_paths(paths)
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
def set_paths(self, paths):
@@ -540,6 +541,7 @@
class PolyCollection(Collection):
+ @docstring.dedent_interpd
def __init__(self, verts, sizes = None, closed = True, **kwargs):
"""
*verts* is a sequence of ( *verts0*, *verts1*, ...) where
@@ -562,7 +564,6 @@
Collection.__init__(self,**kwargs)
self._sizes = sizes
self.set_verts(verts, closed)
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
def set_verts(self, verts, closed=True):
'''This allows one to delay initialization of the vertices.'''
@@ -599,6 +600,7 @@
A collection of horizontal bars spanning *yrange* with a sequence of
*xranges*.
"""
+ @docstring.dedent_interpd
def __init__(self, xranges, yrange, **kwargs):
"""
*xranges*
@@ -613,7 +615,6 @@
ymax = ymin + ywidth
verts = [ [(xmin, ymin), (xmin, ymax), (xmin+xwidth, ymax), (xmin+xwidth, ymin), (xmin, ymin)] for xmin, xwidth in xranges]
PolyCollection.__init__(self, verts, **kwargs)
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
@staticmethod
@@ -640,6 +641,7 @@
"""Draw a collection of regular polygons with *numsides*."""
_path_generator = mpath.Path.unit_regular_polygon
+ @docstring.dedent_interpd
def __init__(self,
numsides,
rotation = 0 ,
@@ -682,8 +684,6 @@
self._rotation = rotation
self.set_transform(transforms.IdentityTransform())
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
-
@allow_rasterization
def draw(self, renderer):
self._transforms = [
@@ -875,6 +875,7 @@
"""
A collection of circles, drawn using splines.
"""
+ @docstring.dedent_interpd
def __init__(self, sizes, **kwargs):
"""
*sizes*
@@ -886,7 +887,6 @@
self._sizes = sizes
self.set_transform(transforms.IdentityTransform())
self._paths = [mpath.Path.unit_circle()]
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
def get_sizes(self):
"return sizes of circles"
@@ -906,6 +906,7 @@
"""
A collection of ellipses, drawn using splines.
"""
+ @docstring.dedent_interpd
def __init__(self, widths, heights, angles, units='points', **kwargs):
"""
*widths*: sequence
@@ -937,8 +938,6 @@
self._initialized = False
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
-
def _init(self):
def on_dpi_change(fig):
self._transforms = []
@@ -1230,9 +1229,10 @@
-artist.kwdocd['Collection'] = patchstr = artist.kwdoc(Collection)
+patchstr = artist.kwdoc(Collection)
for k in ('QuadMesh', 'PolyCollection', 'BrokenBarHCollection',
'RegularPolyCollection', 'PathCollection',
- 'StarPolygonCollection', 'PatchCollection', 'CircleCollection'):
- artist.kwdocd[k] = patchstr
-artist.kwdocd['LineCollection'] = artist.kwdoc(LineCollection)
+ 'StarPolygonCollection', 'PatchCollection',
+ 'CircleCollection', 'Collection',):
+ docstring.interpd.update({k:patchstr})
+docstring.interpd.update(LineCollection = artist.kwdoc(LineCollection))
Modified: trunk/matplotlib/lib/matplotlib/colorbar.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/colorbar.py 2009-08-15 17:56:44 UTC (rev 7490)
+++ trunk/matplotlib/lib/matplotlib/colorbar.py 2009-08-15 18:33:54 UTC (rev 7491)
@@ -23,6 +23,7 @@
import matplotlib as mpl
import matplotlib.colors as colors
import matplotlib.cm as cm
+from matplotlib import docstring
import matplotlib.ticker as ticker
import matplotlib.cbook as cbook
import matplotlib.lines as lines
@@ -150,6 +151,7 @@
''' % (make_axes_kw_doc, colormap_kw_doc)
+docstring.interpd.update(colorbar_doc=colorbar_doc)
class ColorbarBase(cm.ScalarMappable):
@@ -693,7 +695,25 @@
# be recalculating everything if there was a simple alpha
# change.
+@docstring.Substitution(make_axes_kw_doc)
def make_axes(parent, **kw):
+ '''
+ Resize and reposition a parent axes, and return a child
+ axes suitable for a colorbar::
+
+ cax, kw = make_axes(parent, **kw)
+
+ Keyword arguments may include the following (with defaults):
+
+ *orientation*
+ 'vertical' or 'horizontal'
+
+ %s
+
+ All but the first of these are stripped from the input kw set.
+
+ Returns (cax, kw), the child axes and the reduced kw dictionary.
+ '''
orientation = kw.setdefault('orientation', 'vertical')
fraction = kw.pop('fraction', 0.15)
shrink = kw.pop('shrink', 1.0)
@@ -720,22 +740,5 @@
cax = fig.add_axes(pbcb)
cax.set_aspect(aspect, anchor=anchor, adjustable='box')
return cax, kw
-make_axes.__doc__ ='''
- Resize and reposition a parent axes, and return a child
- axes suitable for a colorbar::
- cax, kw = make_axes(parent, **kw)
- Keyword arguments may include the following (with defaults):
-
- *orientation*
- 'vertical' or 'horizontal'
-
- %s
-
- All but the first of these are stripped from the input kw set.
-
- Returns (cax, kw), the child axes and the reduced kw dictionary.
- ''' % make_axes_kw_doc
-
-
Modified: trunk/matplotlib/lib/matplotlib/figure.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/figure.py 2009-08-15 17:56:44 UTC (rev 7490)
+++ trunk/matplotlib/lib/matplotlib/figure.py 2009-08-15 18:33:54 UTC (rev 7491)
@@ -32,7 +32,9 @@
from matplotlib.blocking_input import BlockingMouseInput, BlockingKeyMouseInput
import matplotlib.cbook as cbook
+from matplotlib import docstring
+docstring.interpd.update(projection_names = get_projection_names())
class SubplotParams:
"""
@@ -555,6 +557,7 @@
key = fixlist(args), fixitems(kwargs.items())
return key
+ @docstring.dedent_interpd
def add_axes(self, *args, **kwargs):
"""
Add an a axes with axes rect [*left*, *bottom*, *width*,
@@ -564,7 +567,7 @@
sets the projection type of the axes. (For backward
compatibility, ``polar=True`` may also be provided, which is
equivalent to ``projection='polar'``). Valid values for
- *projection* are: %(list)s. Some of these projections support
+ *projection* are: %(projection_names)s. Some of these projections support
additional kwargs, which may be provided to :meth:`add_axes`::
rect = l,b,w,h
@@ -624,10 +627,7 @@
self._seen[key] = a
return a
- add_axes.__doc__ = dedent(add_axes.__doc__) % \
- {'list': (", ".join(get_projection_names())),
- 'Axes': artist.kwdocd['Axes']}
-
+ @docstring.dedent_interpd
def add_subplot(self, *args, **kwargs):
"""
Add a subplot. Examples:
@@ -642,7 +642,7 @@
*projection*, which chooses a projection type for the axes.
(For backward compatibility, *polar=True* may also be
provided, which is equivalent to *projection='polar'*). Valid
- values for *projection* are: %(list)s. Some of these projections
+ values for *projection* are: %(projection_names)s. Some of these projections
support additional *kwargs*, which may be provided to
:meth:`add_axes`.
@@ -693,9 +693,6 @@
self._axstack.push(a)
self.sca(a)
return a
- add_subplot.__doc__ = dedent(add_subplot.__doc__) % {
- 'list': ", ".join(get_projection_names()),
- 'Axes': artist.kwdocd['Axes']}
def clf(self):
"""
@@ -891,6 +888,7 @@
self.legends.append(l)
return l
+ @docstring.dedent_interpd
def text(self, x, y, s, *args, **kwargs):
"""
Call signature::
@@ -915,13 +913,13 @@
self._set_artist_props(t)
self.texts.append(t)
return t
- text.__doc__ = dedent(text.__doc__) % artist.kwdocd
def _set_artist_props(self, a):
if a!= self:
a.set_figure(self)
a.set_transform(self.transFigure)
+ @docstring.dedent_interpd
def gca(self, **kwargs):
"""
Return the current axes, creating one if necessary
@@ -945,7 +943,6 @@
if isinstance(ax, projection_class):
return ax
return self.add_subplot(111, **kwargs)
- gca.__doc__ = dedent(gca.__doc__) % artist.kwdocd
def sca(self, a):
'Set the current axes to be a and return a'
@@ -1038,7 +1035,14 @@
for ax, alpha in zip(self.axes, original_axes_alpha):
ax.patch.set_alpha(alpha)
+ @docstring.dedent_interpd
def colorbar(self, mappable, cax=None, ax=None, **kw):
+ """
+ Create a colorbar for a ScalarMappable instance.
+
+ Documentation for the pylab thin wrapper:
+ %(colorbar_doc)s
+ """
if ax is None:
ax = self.gca()
if cax is None:
@@ -1056,14 +1060,7 @@
mappable.set_colorbar(cb, cax)
self.sca(ax)
return cb
- colorbar.__doc__ = '''
- Create a colorbar for a ScalarMappable instance.
- Documentation for the pylab thin wrapper:
- %s
-
- '''% cbar.colorbar_doc
-
def subplots_adjust(self, *args, **kwargs):
"""
fig.subplots_adjust(left=None, bottom=None, right=None, wspace=None, hspace=None)
@@ -1220,4 +1217,4 @@
newsize = np.clip(newsize,figsize_min,figsize_max)
return newsize
-artist.kwdocd['Figure'] = artist.kwdoc(Figure)
+docstring.interpd.update(Figure=artist.kwdoc(Figure))
Modified: trunk/matplotlib/lib/matplotlib/lines.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/lines.py 2009-08-15 17:56:44 UTC (rev 7490)
+++ trunk/matplotlib/lib/matplotlib/lines.py 2009-08-15 18:33:54 UTC (rev 7491)
@@ -19,6 +19,7 @@
from matplotlib import rcParams
from artist import allow_rasterization
+from matplotlib import docstring
# special-purpose marker identifiers:
(TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN,
@@ -172,7 +173,7 @@
markeredgewidth = None,
markeredgecolor = None,
markerfacecolor = None,
- fillstyle = 'full',
+ fillstyle = 'full',
antialiased = None,
dash_capstyle = None,
solid_capstyle = None,
@@ -1546,8 +1547,8 @@
lineMarkers = Line2D._markers
drawStyles = Line2D.drawStyles
-artist.kwdocd['Line2D'] = artist.kwdoc(Line2D)
+docstring.interpd.update(Line2D = artist.kwdoc(Line2D))
# You can not set the docstring of an instancemethod,
# but you can on the underlying function. Go figure.
-Line2D.__init__.im_func.__doc__ = dedent(Line2D.__init__.__doc__) % artist.kwdocd
+docstring.dedent_interpd(Line2D.__init__.im_func)
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2009-08-15 17:56:44 UTC (rev 7490)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2009-08-15 18:33:54 UTC (rev 7491)
@@ -147,6 +147,7 @@
import matplotlib.nxutils as nxutils
import matplotlib.cbook as cbook
+from matplotlib import docstring
def logspace(xmin,xmax,N):
@@ -288,8 +289,7 @@
return Pxy, freqs, t
#Split out these keyword docs so that they can be used elsewhere
-kwdocd = dict()
-kwdocd['PSD'] ="""
+docstring.interpd.update(PSD=cbook.dedent("""
Keyword arguments:
*NFFT*: integer
@@ -346,8 +346,9 @@
by the scaling frequency, which gives density in units of Hz^-1.
This allows for integration over the returned frequency values.
The default is True for MatLab compatibility.
-"""
+"""))
+@docstring.dedent_interpd
def psd(x, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning,
noverlap=0, pad_to=None, sides='default', scale_by_freq=None):
"""
@@ -373,8 +374,7 @@
scale_by_freq)
return Pxx.real,freqs
-psd.__doc__ = psd.__doc__ % kwdocd
-
+@docstring.dedent_interpd
def csd(x, y, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning,
noverlap=0, pad_to=None, sides='default', scale_by_freq=None):
"""
@@ -405,8 +405,7 @@
Pxy = Pxy.mean(axis=1)
return Pxy, freqs
-csd.__doc__ = csd.__doc__ % kwdocd
-
+@docstring.dedent_interpd
def specgram(x, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning,
noverlap=128, pad_to=None, sides='default', scale_by_freq=None):
"""
@@ -445,11 +444,10 @@
return Pxx, freqs, t
-specgram.__doc__ = specgram.__doc__ % kwdocd
-
_coh_error = """Coherence is calculated by averaging over *NFFT*
length segments. Your signal is too short for your choice of *NFFT*.
"""
+@docstring.dedent_interpd
def cohere(x, y, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning,
noverlap=0, pad_to=None, sides='default', scale_by_freq=None):
"""
@@ -488,9 +486,7 @@
Cxy.shape = (len(f),)
return Cxy, f
-cohere.__doc__ = cohere.__doc__ % kwdocd
-
def donothing_callback(*args):
pass
Modified: trunk/matplotlib/lib/matplotlib/offsetbox.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/offsetbox.py 2009-08-15 17:56:44 UTC (rev 7490)
+++ trunk/matplotlib/lib/matplotlib/offsetbox.py 2009-08-15 18:33:54 UTC (rev 7491)
@@ -26,6 +26,7 @@
from matplotlib.patches import FancyBboxPatch, FancyArrowPatch
from matplotlib import rcParams
+from matplotlib import docstring
import matplotlib.cbook as cbook
#from bboximage import BboxImage
@@ -1171,6 +1172,7 @@
def __str__(self):
return "AnnotationBbox(%g,%g)"%(self.xy[0],self.xy[1])
+ @docstring.dedent_interpd
def __init__(self, offsetbox, xy,
xybox=None,
xycoords='data',
@@ -1236,8 +1238,6 @@
self._drawFrame = frameon
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % martist.kwdocd
-
def contains(self,event):
t,tinfo = self.offsetbox.contains(event)
if self.arrow is not None:
Modified: trunk/matplotlib/lib/matplotlib/patches.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/patches.py 2009-08-15 17:56:44 UTC (rev 7490)
+++ trunk/matplotlib/lib/matplotlib/patches.py 2009-08-15 18:33:54 UTC (rev 7491)
@@ -9,13 +9,14 @@
import matplotlib.artist as artist
from matplotlib.artist import allow_rasterization
import matplotlib.colors as colors
+from matplotlib import docstring
import matplotlib.transforms as transforms
from matplotlib.path import Path
# these are not available for the object inspector until after the
# class is built so we define an initial set here for the init
# function and they will be overridden after object definition
-artist.kwdocd['Patch'] = """
+docstring.interpd.update(Patch = """
================= ==============================================
Property Description
@@ -38,7 +39,7 @@
zorder any number
================= ==============================================
- """
+ """)
class Patch(artist.Artist):
"""
@@ -51,6 +52,38 @@
def __str__(self):
return str(self.__class__).split('.')[-1]
+ def __init__(self,
+ edgecolor=None,
+ facecolor=None,
+ linewidth=None,
+ linestyle=None,
+ antialiased = None,
+ hatch = None,
+ fill=True,
+ **kwargs
+ ):
+ """
+ The following kwarg properties are supported
+
+ %(Patch)s
+ """
+ artist.Artist.__init__(self)
+
+ if linewidth is None: linewidth = mpl.rcParams['patch.linewidth']
+ if linestyle is None: linestyle = "solid"
+ if antialiased is None: antialiased = mpl.rcParams['patch.antialiased']
+
+ self.set_edgecolor(edgecolor)
+ self.set_facecolor(facecolor)
+ self.set_linewidth(linewidth)
+ self.set_linestyle(linestyle)
+ self.set_antialiased(antialiased)
+ self.set_hatch(hatch)
+ self.fill = fill
+ self._combined_transform = transforms.IdentityTransform()
+
+ if len(kwargs): artist.setp(self, **kwargs)
+
def get_verts(self):
"""
Return a copy of the vertices used in this patch
@@ -337,53 +370,20 @@
def get_window_extent(self, renderer=None):
return self.get_path().get_extents(self.get_transform())
-artist.kwdocd['Patch'] = patchdoc = artist.kwdoc(Patch)
+patchdoc = artist.kwdoc(Patch)
for k in ('Rectangle', 'Circle', 'RegularPolygon', 'Polygon', 'Wedge', 'Arrow',
'FancyArrow', 'YAArrow', 'CirclePolygon', 'Ellipse', 'Arc',
- 'FancyBboxPatch'):
- artist.kwdocd[k] = patchdoc
+ 'FancyBboxPatch', 'Patch'):
+ docstring.interpd.update({k:patchdoc})
-# define Patch.__init__ after the class so that the docstring can be
-# auto-generated.
-def __patch__init__(self,
- edgecolor=None,
- facecolor=None,
- linewidth=None,
- linestyle=None,
- antialiased = None,
- hatch = None,
- fill=True,
- **kwargs
- ):
- """
- The following kwarg properties are supported
+# define Patch.__init__ docstring after the class has been added to interpd
+docstring.dedent_interpd(Patch.__init__.im_func)
- %(Patch)s
- """
- artist.Artist.__init__(self)
-
- if linewidth is None: linewidth = mpl.rcParams['patch.linewidth']
- if linestyle is None: linestyle = "solid"
- if antialiased is None: antialiased = mpl.rcParams['patch.antialiased']
-
- self.set_edgecolor(edgecolor)
- self.set_facecolor(facecolor)
- self.set_linewidth(linewidth)
- self.set_linestyle(linestyle)
- self.set_antialiased(antialiased)
- self.set_hatch(hatch)
- self.fill = fill
- self._combined_transform = transforms.IdentityTransform()
-
- if len(kwargs): artist.setp(self, **kwargs)
-
-__patch__init__.__doc__ = cbook.dedent(__patch__init__.__doc__) % artist.kwdocd
-Patch.__init__ = __patch__init__
-
class Shadow(Patch):
def __str__(self):
return "Shadow(%s)"%(str(self.patch))
+ @docstring.dedent_interpd
def __init__(self, patch, ox, oy, props=None, **kwargs):
"""
Create a shadow of the given *patch* offset by *ox*, *oy*.
@@ -400,7 +400,6 @@
self._ox, self._oy = ox, oy
self._shadow_transform = transforms.Affine2D()
self._update()
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
def _update(self):
self.update_from(self.patch)
@@ -451,6 +450,7 @@
return self.__class__.__name__ \
+ "(%g,%g;%gx%g)" % (self._x, self._y, self._width, self._height)
+ @docstring.dedent_interpd
def __init__(self, xy, width, height, **kwargs):
"""
@@ -468,7 +468,6 @@
self._height = height
# Note: This cannot be calculated until this is added to an Axes
self._rect_transform = transforms.IdentityTransform()
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
def get_path(self):
"""
@@ -589,6 +588,7 @@
def __str__(self):
return "Poly%d(%g,%g)"%(self._numVertices,self._xy[0],self._xy[1])
+ @docstring.dedent_interpd
def __init__(self, xy, numVertices, radius=5, orientation=0,
**kwargs):
"""
@@ -619,8 +619,6 @@
Patch.__init__(self, **kwargs)
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
-
def _update_transform(self):
self._poly_transform.clear() \
.scale(self.radius) \
@@ -665,6 +663,7 @@
def __str__(self):
return "Poly((%g, %g) ...)" % tuple(self._path.vertices[0])
+ @docstring.dedent_interpd
def __init__(self, path, **kwargs):
"""
*path* is a :class:`matplotlib.path.Path` object.
@@ -680,7 +679,6 @@
"""
Patch.__init__(self, **kwargs)
self._path = path
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
def get_path(self):
return self._path
@@ -692,6 +690,7 @@
def __str__(self):
return "Poly((%g, %g) ...)" % tuple(self._path.vertices[0])
+ @docstring.dedent_interpd
def __init__(self, xy, closed=True, **kwargs):
"""
*xy* is a numpy array with shape Nx2.
@@ -713,8 +712,6 @@
self._path = Path(xy)
self.set_closed(closed)
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
-
def get_path(self):
return self._path
@@ -753,6 +750,7 @@
def __str__(self):
return "Wedge(%g,%g)"%(self.theta1,self.theta2)
+ @docstring.dedent_interpd
def __init__(self, center, r, theta1, theta2, width=None, **kwargs):
"""
Draw a wedge centered at *x*, *y* center with radius *r* that
@@ -798,7 +796,6 @@
v += np.asarray(center)
self._path = Path(v,c)
self._patch_transform = transforms.IdentityTransform()
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
def get_path(self):
return self._path
@@ -818,6 +815,7 @@
[ 1.0, 0.0 ], [ 0.8, 0.3],
[ 0.8, 0.1 ], [ 0.0, 0.1] ] )
+ @docstring.dedent_interpd
def __init__( self, x, y, dx, dy, width=1.0, **kwargs ):
"""
Draws an arrow, starting at (*x*, *y*), direction and length
@@ -836,7 +834,6 @@
trans3 = transforms.Affine2D().translate(x, y)
trans = trans1 + trans2 + trans3
self._patch_transform = trans.frozen()
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
def get_path(self):
return self._path
@@ -852,6 +849,7 @@
def __str__(self):
return "FancyArrow()"
+ @docstring.dedent_interpd
def __init__(self, x, y, dx, dy, width=0.001, length_includes_head=False, \
head_width=None, head_length=None, shape='full', overhang=0, \
head_starts_at_zero=False,**kwargs):
@@ -924,7 +922,6 @@
verts = np.dot(coords, M) + (x+dx, y+dy)
Polygon.__init__(self, map(tuple, verts), **kwargs)
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
class YAArrow(Patch):
"""
@@ -936,6 +933,7 @@
def __str__(self):
return "YAArrow()"
+ @docstring.dedent_interpd
def __init__(self, figure, xytip, xybase, width=4, frac=0.1, headwidth=12, **kwargs):
"""
Constructor arguments:
@@ -970,7 +968,6 @@
self.frac = frac
self.headwidth = headwidth
Patch.__init__(self, **kwargs)
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
def get_path(self):
# Since this is dpi dependent, we need to recompute the path
@@ -1034,6 +1031,7 @@
def __str__(self):
return "CirclePolygon(%d,%d)"%self.center
+ @docstring.dedent_interpd
def __init__(self, xy, radius=5,
resolution=20, # the number of vertices
**kwargs):
@@ -1052,7 +1050,6 @@
radius,
orientation=0,
**kwargs)
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
class Ellipse(Patch):
@@ -1062,6 +1059,7 @@
def __str__(self):
return "Ellipse(%s,%s;%sx%s)"%(self.center[0],self.center[1],self.width,self.height)
+ @docstring.dedent_interpd
def __init__(self, xy, width, height, angle=0.0, **kwargs):
"""
*xy*
@@ -1087,7 +1085,6 @@
self._path = Path.unit_circle()
# Note: This cannot be calculated until this is added to an Axes
self._patch_transform = transforms.IdentityTransform()
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
def _recompute_transform(self):
"""NOTE: This cannot be called until after this has been added
@@ -1127,6 +1124,7 @@
def __str__(self):
return "Circle((%g,%g),r=%g)"%(self.center[0],self.center[1],self.radius)
+ @docstring.dedent_interpd
def __init__(self, xy, radius=5, **kwargs):
"""
Create true circle at center *xy* = (*x*, *y*) with given
@@ -1145,7 +1143,6 @@
self.radius = radius
Ellipse.__init__(self, xy, radius*2, radius*2, **kwargs)
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
def set_radius(self, radius):
"""
@@ -1175,6 +1172,7 @@
def __str__(self):
return "Arc(%s,%s;%sx%s)"%(self.center[0],self.center[1],self.width,self.height)
+ @docstring.dedent_interpd
def __init__(self, xy, width, height, angle=0.0, theta1=0.0, theta2=360.0, **kwargs):
"""
The following args are supported:
@@ -1212,7 +1210,6 @@
self.theta1 = theta1
self.theta2 = theta2
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
@allow_rasterization
def draw(self, renderer):
@@ -1987,9 +1984,11 @@
_style_list["roundtooth"] = Roundtooth
- __doc__ = cbook.dedent(__doc__) % \
- {"AvailableBoxstyles": _pprint_styles(_style_list)}
+ if __doc__: # __doc__ could be None if -OO optimization is enabled
+ __doc__ = cbook.dedent(__doc__) % \
+ {"AvailableBoxstyles": _pprint_styles(_style_list)}
+docstring.interpd.update(AvailableBoxstyles=_pprint_styles(BoxStyle._style_list))
class FancyBboxPatch(Patch):
"""
@@ -2007,6 +2006,7 @@
return self.__class__.__name__ \
+ "FancyBboxPatch(%g,%g;%gx%g)" % (self._x, self._y, self._width, self._height)
+ @docstring.dedent_interpd
def __init__(self, xy, width, height,
boxstyle="round",
bbox_transmuter=None,
@@ -2054,13 +2054,7 @@
self._mutation_aspect=mutation_aspect
- kwdoc = dict()
- kwdoc["AvailableBoxstyles"]=_pprint_styles(BoxStyle._style_list)
- kwdoc.update(artist.kwdocd)
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % kwdoc
- del kwdoc
-
-
+ @docstring.dedent_interpd
def set_boxstyle(self, boxstyle=None, **kw):
"""
Set the box style.
@@ -2092,12 +2086,6 @@
self._bbox_transmuter = BoxStyle(boxstyle, **kw)
- kwdoc = dict()
- kwdoc["AvailableBoxstyles"]=_pprint_styles(BoxStyle._style_list)
- kwdoc.update(artist.kwdocd)
- set_boxstyle.__doc__ = cbook.dedent(set_boxstyle.__doc__) % kwdoc
- del kwdoc
-
def set_mutation_scale(self, scale):
"""
Set the mutation scale.
@@ -2682,12 +2670,12 @@
_style_list["bar"] = Bar
+ if __doc__:
+ __doc__ = cbook.dedent(__doc__) % \
+ {"AvailableConnectorstyles": _pprint_styles(_style_list)}
- __doc__ = cbook.dedent(__doc__) % \
- {"AvailableConnectorstyles": _pprint_styles(_style_list)}
-
class ArrowStyle(_Style):
"""
:class:`ArrowStyle` is a container class which defines several
@@ -3438,11 +3426,16 @@
_style_list["wedge"] = Wedge
- __doc__ = cbook.dedent(__doc__) % \
- {"AvailableArrowstyles": _pprint_styles(_style_list)}
+ if __doc__:
+ __doc__ = cbook.dedent(__doc__) % \
+ {"AvailableArrowstyles": _pprint_styles(_style_list)}
+docstring.interpd.update(
+ AvailableArrowstyles = _pprint_styles(ArrowStyle._style_list),
+ AvailableConnectorstyles = _pprint_styles(ConnectionStyle._style_list),
+)
class FancyArrowPatch(Patch):
"""
@@ -3454,6 +3447,7 @@
return self.__class__.__name__ \
+ "FancyArrowPatch(%g,%g,%g,%g,%g,%g)" % tuple(self._q_bezier)
+ @docstring.dedent_interpd
def __init__(self, posA=None, posB=None,
path=None,
arrowstyle="simple",
@@ -3535,14 +3529,6 @@
#self._draw_in_display_coordinate = True
- kwdoc = dict()
- kwdoc["AvailableArrowstyles"]=_pprint_styles(ArrowStyle._style_list)
- kwdoc["AvailableConnectorstyles"]=_pprint_styles(ConnectionStyle._style_list)
-
- kwdoc.update(artist.kwdocd)
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % kwdoc
- del kwdoc
-
def set_positions(self, posA, posB):
""" set the begin end end positions of the connecting
path. Use current vlaue if None.
@@ -3768,6 +3754,7 @@
return "ConnectionPatch((%g,%g),(%g,%g))" % \
(self.xy1[0],self.xy1[1],self.xy2[0],self.xy2[1])
+ @docstring.dedent_interpd
def __init__(self, xyA, xyB, coordsA, coordsB=None,
axesA=None, axesB=None,
arrowstyle="-",
@@ -3859,9 +3846,7 @@
# if True, draw annotation only if self.xy is inside the axes
self._annotation_clip = None
- __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
-
def _get_xy(self, x, y, s, axes=None):
"""
caculate the pixel position of given point
Modified: trunk/matplotlib/lib/matplotlib/projections/geo.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/projections/geo.py 2009-08-15 17:56:44 UTC (rev 7490)
+++ trunk/matplotlib/lib/matplotlib/projections/geo.py 2009-08-15 18:33:54 UTC (rev 7491)
@@ -5,7 +5,6 @@
import matplotlib
rcParams = matplotlib.rcParams
-from matplotlib.artist import kwdocd
from matplotlib.axes import Axes
from matplotlib import cbook
from matplotlib.patches import Circle
Modified: trunk/matplotlib/lib/matplotlib/projections/polar.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/projections/polar.py 2009-08-15 17:56:44 UTC (rev 7490)
+++ trunk/matplotlib/lib/matplotlib/projections/polar.py 2009-08-15 18:33:54 UTC (rev 7491)
@@ -5,10 +5,10 @@
import matplotlib
rcParams = matplotlib.rcParams
-from matplotlib.artist import kwdocd
from matplotlib.axes import Axes
import matplotlib.axis as maxis
from matplotlib import cbook
+from matplotlib import docstring
from matplotlib.patches import Circle
from matplotlib.path import Path
from matplotlib.ticker import Formatter, Locator
@@ -317,6 +317,7 @@
set_rscale = Axes.set_yscale
set_rticks = Axes.set_yticks
+ @docstring.dedent_interpd
def set_thetagrids(self, angles, labels=None, frac=None,
**kwargs):
"""
@@ -353,8 +354,8 @@
for t in self.xaxis.get_ticklabels():
t.update(kwargs)
return self.xaxis.get_ticklines(), self.xaxis.get_ticklabels()
- set_thetagrids.__doc__ = cbook.dedent(set_thetagrids.__doc__) % kwdocd
+ @docstring.dedent_interpd
def set_rgrids(self, radii, labels=None, angle=None, rpad=None, **kwargs):
"""
Set the radial locations and labels of the *r* grids.
@@ -399,8 +400,6 @@
t.update(kwargs)
return self.yaxis.get_gridlines(), self.yaxis.get_ticklabels()
- set_rgrids.__doc__ = cbook.dedent(set_rgrids.__doc__) % kwdocd
-
def set_xscale(self, scale, *args, **kwargs):
if scale != 'linear':
raise NotImplementedError("You can not set the xscale on a polar plot.")
Modified: trunk/matplotlib/lib/matplotlib/pyplot.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/pyplot.py 2009-08-15 17:56:44 UTC (rev 7490)
+++ trunk/matplotlib/lib/matplotlib/pyplot.py 2009-08-15 18:33:54 UTC (rev 7491)
@@ -3,6 +3,7 @@
import matplotlib
from matplotlib import _pylab_helpers, interactive
from matplotlib.cbook import dedent, silent_list, is_string_like, is_numlike
+from matplotlib import docstring
from matplotlib.figure import Figure, figaspect
from matplotlib.backend_bases import FigureCanvasBase
from matplotlib.image import imread as _imread
@@ -119,16 +120,14 @@
'Turn interactive mode on.'
matplotlib.interactive(True)
+@docstring.copy_dedent(matplotlib.rc)
def rc(*args, **kwargs):
matplotlib.rc(*args, **kwargs)
-if matplotlib.rc.__doc__ is not None:
- rc.__doc__ = dedent(matplotlib.rc.__doc__)
+@docstring.copy_dedent(matplotlib.rcdefaults)
def rcdefaults():
matplotlib.rcdefaults()
draw_if_interactive()
-if matplotlib.rcdefaults.__doc__ is not None:
- rcdefaults.__doc__ = dedent(matplotlib.rcdefaults.__doc__)
# The current "image" (ScalarMappable) is tracked here on a
# per-pylab-session basis:
@@ -161,12 +160,11 @@
# (getp is simply imported)
+@docstring.copy(_setp)
def setp(*args, **kwargs):
ret = _setp(*args, **kwargs)
draw_if_interactive()
return ret
-if _setp.__doc__ is not None:
- setp.__doc__ = _setp.__doc__
@@ -290,17 +288,13 @@
figManager = _pylab_helpers.Gcf.get_active()
return figManager
-# note we check for __doc__ is not None since py2exe optimize removes
-# the docstrings
+@docstring.copy_dedent(FigureCanvasBase.mpl_connect)
def connect(s, func):
return get_current_fig_manager().canvas.mpl_connect(s, func)
-if FigureCanvasBase.mpl_connect.__doc__ is not None:
- connect.__doc__ = dedent(FigureCanvasBase.mpl_connect.__doc__)
+@docstring.copy_dedent(FigureCanvasBase.mpl_disconnect)
def disconnect(cid):
return get_current_fig_manager().canvas.mpl_disconnect(cid)
-if FigureCanvasBase.mpl_disconnect.__doc__ is not None:
- disconnect.__doc__ = dedent(FigureCanvasBase.mpl_disconnect.__doc__)
def close(*args):
"""
@@ -351,12 +345,12 @@
'redraw the current figure'
get_current_fig_manager().canvas.draw()
+@docstring.copy_dedent(Figure.savefig)
def savefig(*args, **kwargs):
fig = gcf()
return fig.savefig(*args, **kwargs)
-if Figure.savefig.__doc__ is not None:
- savefig.__doc__ = dedent(Figure.savefig.__doc__)
+@docstring.copy_dedent(Figure.ginput)
def ginput(*args, **kwargs):
"""
Blocking call to interact with the figure.
@@ -367,9 +361,8 @@
If *timeout* is negative, does not timeout.
"""
return gcf().ginput(*args, **kwargs)
-if Figure.ginput.__doc__ is not None:
- ginput.__doc__ = dedent(Figure.ginput.__doc__)
+@docstring.copy_dedent(Figure.waitforbuttonpress)
def waitforbuttonpress(*args, **kwargs):
"""
Blocking call to interact with the figure.
@@ -381,36 +374,31 @@
If *timeout* is negative, does not timeout.
"""
return gcf().waitforbuttonpress(*args, **kwargs)
-if Figure.waitforbuttonpress.__doc__ is not None:
- waitforbuttonpress.__doc__ = dedent(Figure.waitforbuttonpress.__doc__)
# Putting things in figures
+@docstring.copy_dedent(Figure.text)
def figtext(*args, **kwargs):
ret = gcf().text(*args, **kwargs)
draw_if_interactive()
return ret
-if Figure.text.__doc__ is not None:
- figtext.__doc__ = dedent(Figure.text.__doc__)
+@docstring.copy_dedent(Figure.suptitle)
def suptitle(*args, **kwargs):
ret = gcf().suptitle(*args, **kwargs)
draw_if_interactive()
return ret
-if Figure.suptitle.__doc__ is not None:
- suptitle.__doc__ = dedent(Figure.suptitle.__doc__)
+@docstring.Appender("Addition kwargs: hold = [True|False] overrides default hold state", "\n")
+@docstring.copy_dedent(Figure.figimage)
def figimage(*args, **kwargs):
# allow callers to override the hold state by passing hold=True|False
ret = gcf().figimage(*args, **kwargs)
draw_if_interactive()
gci._current = ret
return ret
-if Figure.figimage.__doc__ is not None:
- figimage.__doc__ = dedent(Figure.figimage.__doc__) + """
-Addition kwargs: hold = [True|False] overrides default hold state"""
def figlegend(handles, labels, loc, **kwargs):
"""
@@ -930,6 +918,7 @@
return ret
+@docstring.dedent_interpd
def xscale(*args, **kwargs):
"""
call signature::
@@ -946,10 +935,8 @@
ret = ax.set_xscale(*args, **kwargs)
draw_if_interactive()
return ret
-xscale.__doc__ = dedent(xscale.__doc__) % {
- 'scale': ' | '.join([repr(_x) for _x in get_scale_names()]),
- 'scale_docs': get_scale_docs()}
+@docstring.dedent_interpd
def yscale(*args, **kwargs):
"""
call signature::
@@ -966,9 +953,6 @@
ret = ax.set_yscale(*args, **kwargs)
draw_if_interactive()
return ret
-yscale.__doc__ = dedent(yscale.__doc__) % {
- 'scale': ' | '.join([repr(_x) for _x in get_scale_names()]),
- 'scale_docs': get_scale_docs()}
def xticks(*args, **kwargs):
"""
@@ -1415,15 +1399,13 @@
draw_if_interactive()
+@docstring.copy_dedent(_imread)
def imre...
[truncated message content] |
|
From: <jd...@us...> - 2009-08-15 17:56:54
|
Revision: 7490
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7490&view=rev
Author: jdh2358
Date: 2009-08-15 17:56:44 +0000 (Sat, 15 Aug 2009)
Log Message:
-----------
added transformations tut, did some reorg
Modified Paths:
--------------
branches/v0_99_maint/CXX/IndirectPythonInterface.hxx
branches/v0_99_maint/agg24/include/agg_basics.h
branches/v0_99_maint/doc/users/index.rst
branches/v0_99_maint/doc/users/transforms_tutorial.rst
Added Paths:
-----------
branches/v0_99_maint/doc/pyplots/annotate_transform.py
branches/v0_99_maint/doc/users/annotations_intro.rst
branches/v0_99_maint/doc/users/legend_guide.rst
Removed Paths:
-------------
branches/v0_99_maint/doc/users/annotations_overview.rst
branches/v0_99_maint/doc/users/legend.rst
Modified: branches/v0_99_maint/CXX/IndirectPythonInterface.hxx
===================================================================
--- branches/v0_99_maint/CXX/IndirectPythonInterface.hxx 2009-08-15 17:40:27 UTC (rev 7489)
+++ branches/v0_99_maint/CXX/IndirectPythonInterface.hxx 2009-08-15 17:56:44 UTC (rev 7490)
@@ -193,6 +193,6 @@
void _XDECREF( PyObject *op );
char *__Py_PackageContext();
-};
+}
#endif // __CXX_INDIRECT_PYTHON_INTERFACE__HXX__
Modified: branches/v0_99_maint/agg24/include/agg_basics.h
===================================================================
--- branches/v0_99_maint/agg24/include/agg_basics.h 2009-08-15 17:40:27 UTC (rev 7489)
+++ branches/v0_99_maint/agg24/include/agg_basics.h 2009-08-15 17:56:44 UTC (rev 7490)
@@ -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.
//
@@ -25,12 +25,12 @@
#else
namespace agg
{
- // The policy of all AGG containers and memory allocation strategy
+ // The policy of all AGG containers and memory allocation strategy
// in general is that no allocated data requires explicit construction.
// It means that the allocator can be really simple; you can even
- // replace new/delete to malloc/free. The constructors and destructors
- // won't be called in this case, however everything will remain working.
- // The second argument of deallocate() is the size of the allocated
+ // replace new/delete to malloc/free. The constructors and destructors
+ // won't be called in this case, however everything will remain working.
+ // The second argument of deallocate() is the size of the allocated
// block. You can use this information if you wish.
//------------------------------------------------------------pod_allocator
template<class T> struct pod_allocator
@@ -40,8 +40,8 @@
};
// Single object allocator. It's also can be replaced with your custom
- // allocator. The difference is that it can only allocate a single
- // object and the constructor and destructor must be called.
+ // allocator. The difference is that it can only allocate a single
+ // object and the constructor and destructor must be called.
// In AGG there is no need to allocate an array of objects with
// calling their constructors (only single ones). So that, if you
// replace these new/delete to malloc/free make sure that the in-place
@@ -213,23 +213,23 @@
enum cover_scale_e
{
cover_shift = 8, //----cover_shift
- cover_size = 1 << cover_shift, //----cover_size
- cover_mask = cover_size - 1, //----cover_mask
- cover_none = 0, //----cover_none
- cover_full = cover_mask //----cover_full
+ cover_size = 1 << cover_shift, //----cover_size
+ cover_mask = cover_size - 1, //----cover_mask
+ cover_none = 0, //----cover_none
+ cover_full = cover_mask //----cover_full
};
//----------------------------------------------------poly_subpixel_scale_e
- // These constants determine the subpixel accuracy, to be more precise,
- // the number of bits of the fractional part of the coordinates.
+ // These constants determine the subpixel accuracy, to be more precise,
+ // the number of bits of the fractional part of the coordinates.
// The possible coordinate capacity in bits can be calculated by formula:
// sizeof(int) * 8 - poly_subpixel_shift, i.e, for 32-bit integers and
// 8-bits fractional part the capacity is 24 bits.
enum poly_subpixel_scale_e
{
poly_subpixel_shift = 8, //----poly_subpixel_shift
- poly_subpixel_scale = 1<<poly_subpixel_shift, //----poly_subpixel_scale
- poly_subpixel_mask = poly_subpixel_scale-1, //----poly_subpixel_mask
+ poly_subpixel_scale = 1<<poly_subpixel_shift, //----poly_subpixel_scale
+ poly_subpixel_mask = poly_subpixel_scale-1 //----poly_subpixel_mask
};
//----------------------------------------------------------filling_rule_e
@@ -253,7 +253,7 @@
{
return rad * 180.0 / pi;
}
-
+
//----------------------------------------------------------------rect_base
template<class T> struct rect_base
{
@@ -265,9 +265,9 @@
rect_base(T x1_, T y1_, T x2_, T y2_) :
x1(x1_), y1(y1_), x2(x2_), y2(y2_) {}
- void init(T x1_, T y1_, T x2_, T y2_)
+ void init(T x1_, T y1_, T x2_, T y2_)
{
- x1 = x1_; y1 = y1_; x2 = x2_; y2 = y2_;
+ x1 = x1_; y1 = y1_; x2 = x2_; y2 = y2_;
}
const self_type& normalize()
@@ -299,17 +299,17 @@
};
//-----------------------------------------------------intersect_rectangles
- template<class Rect>
+ template<class Rect>
inline Rect intersect_rectangles(const Rect& r1, const Rect& r2)
{
Rect r = r1;
- // First process x2,y2 because the other order
- // results in Internal Compiler Error under
- // Microsoft Visual C++ .NET 2003 69462-335-0000007-18038 in
+ // First process x2,y2 because the other order
+ // results in Internal Compiler Error under
+ // Microsoft Visual C++ .NET 2003 69462-335-0000007-18038 in
// case of "Maximize Speed" optimization option.
//-----------------
- if(r.x2 > r2.x2) r.x2 = r2.x2;
+ if(r.x2 > r2.x2) r.x2 = r2.x2;
if(r.y2 > r2.y2) r.y2 = r2.y2;
if(r.x1 < r2.x1) r.x1 = r2.x1;
if(r.y1 < r2.y1) r.y1 = r2.y1;
@@ -318,7 +318,7 @@
//---------------------------------------------------------unite_rectangles
- template<class Rect>
+ template<class Rect>
inline Rect unite_rectangles(const Rect& r1, const Rect& r2)
{
Rect r = r1;
@@ -336,26 +336,26 @@
//---------------------------------------------------------path_commands_e
enum path_commands_e
{
- path_cmd_stop = 0, //----path_cmd_stop
- path_cmd_move_to = 1, //----path_cmd_move_to
- path_cmd_line_to = 2, //----path_cmd_line_to
- path_cmd_curve3 = 3, //----path_cmd_curve3
- path_cmd_curve4 = 4, //----path_cmd_curve4
+ path_cmd_stop = 0, //----path_cmd_stop
+ path_cmd_move_to = 1, //----path_cmd_move_to
+ path_cmd_line_to = 2, //----path_cmd_line_to
+ path_cmd_curve3 = 3, //----path_cmd_curve3
+ path_cmd_curve4 = 4, //----path_cmd_curve4
path_cmd_curveN = 5, //----path_cmd_curveN
path_cmd_catrom = 6, //----path_cmd_catrom
path_cmd_ubspline = 7, //----path_cmd_ubspline
path_cmd_end_poly = 0x0F, //----path_cmd_end_poly
- path_cmd_mask = 0x0F //----path_cmd_mask
+ path_cmd_mask = 0x0F //----path_cmd_mask
};
//------------------------------------------------------------path_flags_e
enum path_flags_e
{
- path_flags_none = 0, //----path_flags_none
- path_flags_ccw = 0x10, //----path_flags_ccw
- path_flags_cw = 0x20, //----path_flags_cw
+ path_flags_none = 0, //----path_flags_none
+ path_flags_ccw = 0x10, //----path_flags_ccw
+ path_flags_cw = 0x20, //----path_flags_cw
path_flags_close = 0x40, //----path_flags_close
- path_flags_mask = 0xF0 //----path_flags_mask
+ path_flags_mask = 0xF0 //----path_flags_mask
};
//---------------------------------------------------------------is_vertex
@@ -372,7 +372,7 @@
//-----------------------------------------------------------------is_stop
inline bool is_stop(unsigned c)
- {
+ {
return c == path_cmd_stop;
}
@@ -416,7 +416,7 @@
inline bool is_close(unsigned c)
{
return (c & ~(path_flags_cw | path_flags_ccw)) ==
- (path_cmd_end_poly | path_flags_close);
+ (path_cmd_end_poly | path_flags_close);
}
//------------------------------------------------------------is_next_poly
@@ -440,19 +440,19 @@
//-------------------------------------------------------------is_oriented
inline bool is_oriented(unsigned c)
{
- return (c & (path_flags_cw | path_flags_ccw)) != 0;
+ return (c & (path_flags_cw | path_flags_ccw)) != 0;
}
//---------------------------------------------------------------is_closed
inline bool is_closed(unsigned c)
{
- return (c & path_flags_close) != 0;
+ return (c & path_flags_close) != 0;
}
//----------------------------------------------------------get_close_flag
inline unsigned get_close_flag(unsigned c)
{
- return c & path_flags_close;
+ return c & path_flags_close;
}
//-------------------------------------------------------clear_orientation
@@ -513,7 +513,7 @@
int x1, x2;
const T* ptr;
const_row_info() {}
- const_row_info(int x1_, int x2_, const T* ptr_) :
+ const_row_info(int x1_, int x2_, const T* ptr_) :
x1(x1_), x2(x2_), ptr(ptr_) {}
};
Added: branches/v0_99_maint/doc/pyplots/annotate_transform.py
===================================================================
--- branches/v0_99_maint/doc/pyplots/annotate_transform.py (rev 0)
+++ branches/v0_99_maint/doc/pyplots/annotate_transform.py 2009-08-15 17:56:44 UTC (rev 7490)
@@ -0,0 +1,34 @@
+import numpy as np
+import matplotlib.pyplot as plt
+
+x = np.arange(0, 10, 0.005)
+y = np.exp(-x/2.) * np.sin(2*np.pi*x)
+
+fig = plt.figure()
+ax = fig.add_subplot(111)
+ax.plot(x, y)
+ax.set_xlim(0, 10)
+ax.set_ylim(-1, 1)
+
+xdata, ydata = 5, 0
+xdisplay, ydisplay = ax.transData.transform((xdata, ydata))
+
+bbox = dict(boxstyle="round", fc="0.8")
+arrowprops = dict(
+ arrowstyle = "->",
+ connectionstyle = "angle,angleA=0,angleB=90,rad=10")
+
+offset = 72
+ax.annotate('data = (%.1f, %.1f)'%(xdata, ydata),
+ (xdata, ydata), xytext=(-2*offset, offset), textcoords='offset points',
+ bbox=bbox, arrowprops=arrowprops)
+
+
+disp = ax.annotate('display = (%.1f, %.1f)'%(xdisplay, ydisplay),
+ (xdisplay, ydisplay), xytext=(0.5*offset, -offset),
+ xycoords='figure pixels',
+ textcoords='offset points',
+ bbox=bbox, arrowprops=arrowprops)
+
+
+plt.show()
Copied: branches/v0_99_maint/doc/users/annotations_intro.rst (from rev 7489, branches/v0_99_maint/doc/users/annotations_overview.rst)
===================================================================
--- branches/v0_99_maint/doc/users/annotations_intro.rst (rev 0)
+++ branches/v0_99_maint/doc/users/annotations_intro.rst 2009-08-15 17:56:44 UTC (rev 7490)
@@ -0,0 +1,87 @@
+.. _annotations-tutorial:
+
+Annotating text
+===============
+
+For a more detailed introduction to annotations, see
+:ref:`plotting-guide-annotation`.
+
+The uses of the basic :func:`~matplotlib.pyplot.text` command above
+place text at an arbitrary position on the Axes. A common use case of
+text is to annotate some feature of the plot, and the
+:func:`~matplotlib.Axes.annotate` method provides helper functionality
+to make annotations easy. In an annotation, there are two points to
+consider: the location being annotated represented by the argument
+``xy`` and the location of the text ``xytext``. Both of these
+arguments are ``(x,y)`` tuples.
+
+.. plot:: pyplots/annotation_basic.py
+ :include-source:
+
+
+In this example, both the ``xy`` (arrow tip) and ``xytext`` locations
+(text location) are in data coordinates. There are a variety of other
+coordinate systems one can choose -- you can specify the coordinate
+system of ``xy`` and ``xytext`` with one of the following strings for
+``xycoords`` and ``textcoords`` (default is 'data')
+
+==================== ====================================================
+argument coordinate system
+==================== ====================================================
+ 'figure points' points from the lower left corner of the figure
+ 'figure pixels' pixels from the lower left corner of the figure
+ 'figure fraction' 0,0 is lower left of figure and 1,1 is upper, right
+ 'axes points' points from lower left corner of axes
+ 'axes pixels' pixels from lower left corner of axes
+ 'axes fraction' 0,1 is lower left of axes and 1,1 is upper right
+ 'data' use the axes data coordinate system
+==================== ====================================================
+
+For example to place the text coordinates in fractional axes
+coordinates, one could do::
+
+ ax.annotate('local max', xy=(3, 1), xycoords='data',
+ xytext=(0.8, 0.95), textcoords='axes fraction',
+ arrowprops=dict(facecolor='black', shrink=0.05),
+ horizontalalignment='right', verticalalignment='top',
+ )
+
+For physical coordinate systems (points or pixels) the origin is the
+(bottom, left) of the figure or axes. If the value is negative,
+however, the origin is from the (right, top) of the figure or axes,
+analogous to negative indexing of sequences.
+
+Optionally, you can specify arrow properties which draws an arrow
+from the text to the annotated point by giving a dictionary of arrow
+properties in the optional keyword argument ``arrowprops``.
+
+
+==================== =====================================================
+``arrowprops`` key description
+==================== =====================================================
+width the width of the arrow in points
+frac the fraction of the arrow length occupied by the head
+headwidth the width of the base of the arrow head in points
+shrink move the tip and base some percent away from
+ the annotated point and text
+
+\*\*kwargs any key for :class:`matplotlib.patches.Polygon`,
+ e.g. ``facecolor``
+==================== =====================================================
+
+
+In the example below, the ``xy`` point is in native coordinates
+(``xycoords`` defaults to 'data'). For a polar axes, this is in
+(theta, radius) space. The text in this example is placed in the
+fractional figure coordinate system. :class:`matplotlib.text.Text`
+keyword args like ``horizontalalignment``, ``verticalalignment`` and
+``fontsize are passed from the `~matplotlib.Axes.annotate` to the
+``Text`` instance
+
+.. plot:: pyplots/annotation_polar.py
+ :include-source:
+
+For more on all the wild and wonderful things you can do with
+annotations, including fancy arrows, see :ref:`plotting-guide-annotation`
+and :ref:`pylab_examples-annotation_demo`.
+
Deleted: branches/v0_99_maint/doc/users/annotations_overview.rst
===================================================================
--- branches/v0_99_maint/doc/users/annotations_overview.rst 2009-08-15 17:40:27 UTC (rev 7489)
+++ branches/v0_99_maint/doc/users/annotations_overview.rst 2009-08-15 17:56:44 UTC (rev 7490)
@@ -1,87 +0,0 @@
-.. _annotations-tutorial:
-
-Annotating text
-===============
-
-For a more detailed introduction to annotations, see
-:ref:`plotting-guide-annotation`.
-
-The uses of the basic :func:`~matplotlib.pyplot.text` command above
-place text at an arbitrary position on the Axes. A common use case of
-text is to annotate some feature of the plot, and the
-:func:`~matplotlib.Axes.annotate` method provides helper functionality
-to make annotations easy. In an annotation, there are two points to
-consider: the location being annotated represented by the argument
-``xy`` and the location of the text ``xytext``. Both of these
-arguments are ``(x,y)`` tuples.
-
-.. plot:: pyplots/annotation_basic.py
- :include-source:
-
-
-In this example, both the ``xy`` (arrow tip) and ``xytext`` locations
-(text location) are in data coordinates. There are a variety of other
-coordinate systems one can choose -- you can specify the coordinate
-system of ``xy`` and ``xytext`` with one of the following strings for
-``xycoords`` and ``textcoords`` (default is 'data')
-
-==================== ====================================================
-argument coordinate system
-==================== ====================================================
- 'figure points' points from the lower left corner of the figure
- 'figure pixels' pixels from the lower left corner of the figure
- 'figure fraction' 0,0 is lower left of figure and 1,1 is upper, right
- 'axes points' points from lower left corner of axes
- 'axes pixels' pixels from lower left corner of axes
- 'axes fraction' 0,1 is lower left of axes and 1,1 is upper right
- 'data' use the axes data coordinate system
-==================== ====================================================
-
-For example to place the text coordinates in fractional axes
-coordinates, one could do::
-
- ax.annotate('local max', xy=(3, 1), xycoords='data',
- xytext=(0.8, 0.95), textcoords='axes fraction',
- arrowprops=dict(facecolor='black', shrink=0.05),
- horizontalalignment='right', verticalalignment='top',
- )
-
-For physical coordinate systems (points or pixels) the origin is the
-(bottom, left) of the figure or axes. If the value is negative,
-however, the origin is from the (right, top) of the figure or axes,
-analogous to negative indexing of sequences.
-
-Optionally, you can specify arrow properties which draws an arrow
-from the text to the annotated point by giving a dictionary of arrow
-properties in the optional keyword argument ``arrowprops``.
-
-
-==================== =====================================================
-``arrowprops`` key description
-==================== =====================================================
-width the width of the arrow in points
-frac the fraction of the arrow length occupied by the head
-headwidth the width of the base of the arrow head in points
-shrink move the tip and base some percent away from
- the annotated point and text
-
-\*\*kwargs any key for :class:`matplotlib.patches.Polygon`,
- e.g. ``facecolor``
-==================== =====================================================
-
-
-In the example below, the ``xy`` point is in native coordinates
-(``xycoords`` defaults to 'data'). For a polar axes, this is in
-(theta, radius) space. The text in this example is placed in the
-fractional figure coordinate system. :class:`matplotlib.text.Text`
-keyword args like ``horizontalalignment``, ``verticalalignment`` and
-``fontsize are passed from the `~matplotlib.Axes.annotate` to the
-``Text`` instance
-
-.. plot:: pyplots/annotation_polar.py
- :include-source:
-
-For more on all the wild and wonderful things you can do with
-annotations, including fancy arrows, see :ref:`plotting-guide-annotation`
-and :ref:`pylab_examples-annotation_demo`.
-
Modified: branches/v0_99_maint/doc/users/index.rst
===================================================================
--- branches/v0_99_maint/doc/users/index.rst 2009-08-15 17:40:27 UTC (rev 7489)
+++ branches/v0_99_maint/doc/users/index.rst 2009-08-15 17:56:44 UTC (rev 7490)
@@ -22,7 +22,7 @@
artists.rst
legend_guide.rst
event_handling.rst
- annotation_guide.rst
+ annotations_guide.rst
legend.rst
transforms_tutorial.rst
toolkits.rst
Deleted: branches/v0_99_maint/doc/users/legend.rst
===================================================================
--- branches/v0_99_maint/doc/users/legend.rst 2009-08-15 17:40:27 UTC (rev 7489)
+++ branches/v0_99_maint/doc/users/legend.rst 2009-08-15 17:56:44 UTC (rev 7490)
@@ -1,182 +0,0 @@
-.. _plotting-guide-legend:
-
-************
-Legend guide
-************
-
-Do not proceed unless you already have read :func:`~matplotlib.pyplot.legend` and
-:class:`matplotlib.legend.Legend`!
-
-
-What to be displayed
-====================
-
-The legend command has a following call signature::
-
- legend(*args, **kwargs)
-
-If len(args) is 2, the first argument should be a list of artist to be
-labeled, and the second argument should a list of string labels. If
-len(args) is 0, it automatically generate the legend from label
-properties of the child artists by calling
-:meth:`~matplotlib.axes.Axes.get_legend_handles_labels` method.
-For example, *ax.legend()* is equivalent to::
-
- handles, labels = ax.get_legend_handles_labels()
- ax.legend(handles, labels)
-
-The :meth:`~matplotlib.axes.Axes.get_legend_handles_labels` method
-returns a tuple of two lists, i.e., list of artists and list of labels
-(python string). However, it does not return all of its child
-artists. It returns all artists in *ax.lines* and *ax.patches* and
-some artists in *ax.collection* which are instance of
-:class:`~matplotlib.collections.LineCollection` or
-:class:`~matplotlib.collections.RegularPolyCollection`. The label
-attributes (returned by get_label() method) of collected artists are
-used as text labels. If label attribute is empty string or starts with
-"_", that artist will be ignored.
-
-
- * Note that not all kind of artists are supported by the legend. The
- following is the list of artists that are currently supported.
-
- * :class:`~matplotlib.lines.Line2D`
- * :class:`~matplotlib.patches.Patch`
- * :class:`~matplotlib.collections.LineCollection`
- * :class:`~matplotlib.collections.RegularPolyCollection`
-
- Unfortunately, there is no easy workaround when you need legend for
- an artist not in the above list (You may use one of the supported
- artist as a proxy. See below), or customize it beyond what is
- supported by :class:`matplotlib.legend.Legend`.
-
- * Remember that some *pyplot* commands return artist not supported by
- legend, e.g., :func:`~matplotlib.pyplot.fill_between` returns
- :class:`~matplotlib.collections.PolyCollection` that is not
- supported. Or some return multiple artists. For example,
- :func:`~matplotlib.pyplot.plot` returns list of
- :class:`~matplotlib.lines.Line2D` instances, and
- :func:`~matplotlib.pyplot.errorbar` returns a length 3 tuple of
- :class:`~matplotlib.lines.Line2D` instances.
-
- * The legend does not care about the axes that given artists belongs,
- i.e., the artists may belong to other axes or even none.
-
-
-Adjusting the Order of Legend items
------------------------------------
-
-When you want to customize the list of artists to be displayed in the
-legend, or their order of appearance. There are a two options. First,
-you can keep lists of artists and labels, and explicitly use these for
-the first two argument of the legend call.::
-
- p1, = plot([1,2,3])
- p2, = plot([3,2,1])
- p3, = plot([2,3,1])
- legend([p2, p1], ["line 2", "line 1"])
-
-Or you may use :meth:`~matplotlib.axes.Axes.get_legend_handles_labels`
-to retrieve list of artist and labels and manipulate them before
-feeding them to legend call.::
-
- ax = subplot(1,1,1)
- p1, = ax.plot([1,2,3], label="line 1")
- p2, = ax.plot([3,2,1], label="line 2")
- p3, = ax.plot([2,3,1], label="line 3")
-
- handles, labels = ax.get_legend_handles_labels()
-
- # reverse the order
- ax.legend(handles[::-1], labels[::-1])
-
- # or sort them by labels
- import operator
- hl = sorted(zip(handles, labels),
- key=operator.itemgetter(1))
- handles2, labels2 = zip(*hl)
-
- ax.legend(handles2, labels2)
-
-
-Using Proxy Artist
-------------------
-
-When you want to display legend for an artist not supported by the
-matplotlib, you may use other supported artist as a proxy. For
-example, you may creates an proxy artist without adding it to the axes
-(so the proxy artist will not be drawn in the main axes) and feet it
-to the legend function.::
-
- p = Rectangle((0, 0), 1, 1, fc="r")
- legend([p], ["Red Rectangle"])
-
-
-Multicolumn Legend
-==================
-
-By specifying the keyword argument *ncol*, you can have a multi-column
-legend. Also, mode="expand" horizontally expand the legend to fill the
-axes area. See `legend_demo3.py
-<http://matplotlib.sourceforge.net/examples/pylab_examples/legend_demo3.html>`_
-for example.
-
-
-Legend location
-===============
-
-The location of the legend can be specified by the keyword argument
-*loc*, either by string or a integer number.
-
-============= ======
- String Number
-============= ======
- upper right 1
- upper left 2
- lower left 3
- lower right 4
- right 5
- center left 6
- center right 7
- lower center 8
- upper center 9
- center 10
-============= ======
-
-By default, the legend will anchor to the bbox of the axes
-(for legend) or the bbox of the figure (figlegend). You can specify
-your own bbox using *bbox_to_anchor* argument. *bbox_to_anchor* can be an
-instance of :class:`~matplotlib.transforms.BboxBase`, a tuple of 4
-floats (x, y, width, height of the bbox), or a tuple of 2 floats (x, y
-with width=height=0). Unless *bbox_transform* argument is given, the
-coordinates (even for the bbox instance) are considered as normalized
-axes coordinates.
-
-For example, if you want your axes legend located at the figure corner
-(instead of the axes corner)::
-
- l = legend(bbox_to_anchor=(0, 0, 1, 1), transform=gcf().transFigure)
-
-Also, you can place above or outer right-hand side of the axes,
-
-.. plot:: users/plotting/examples/simple_legend01.py
- :include-source:
-
-
-Multiple Legend
-===============
-
-Sometime, you want to split the legend into multiple ones.::
-
- p1, = plot([1,2,3])
- p2, = plot([3,2,1])
- legend([p1], ["Test1"], loc=1)
- legend([p2], ["Test2"], loc=4)
-
-However, the above code only shows the second legend. When the legend
-command is called, a new legend instance is created and old ones are
-removed from the axes. Thus, you need to manually add the removed
-legend.
-
-.. plot:: users/plotting/examples/simple_legend02.py
- :include-source:
Copied: branches/v0_99_maint/doc/users/legend_guide.rst (from rev 7489, branches/v0_99_maint/doc/users/legend.rst)
===================================================================
--- branches/v0_99_maint/doc/users/legend_guide.rst (rev 0)
+++ branches/v0_99_maint/doc/users/legend_guide.rst 2009-08-15 17:56:44 UTC (rev 7490)
@@ -0,0 +1,182 @@
+.. _plotting-guide-legend:
+
+************
+Legend guide
+************
+
+Do not proceed unless you already have read :func:`~matplotlib.pyplot.legend` and
+:class:`matplotlib.legend.Legend`!
+
+
+What to be displayed
+====================
+
+The legend command has a following call signature::
+
+ legend(*args, **kwargs)
+
+If len(args) is 2, the first argument should be a list of artist to be
+labeled, and the second argument should a list of string labels. If
+len(args) is 0, it automatically generate the legend from label
+properties of the child artists by calling
+:meth:`~matplotlib.axes.Axes.get_legend_handles_labels` method.
+For example, *ax.legend()* is equivalent to::
+
+ handles, labels = ax.get_legend_handles_labels()
+ ax.legend(handles, labels)
+
+The :meth:`~matplotlib.axes.Axes.get_legend_handles_labels` method
+returns a tuple of two lists, i.e., list of artists and list of labels
+(python string). However, it does not return all of its child
+artists. It returns all artists in *ax.lines* and *ax.patches* and
+some artists in *ax.collection* which are instance of
+:class:`~matplotlib.collections.LineCollection` or
+:class:`~matplotlib.collections.RegularPolyCollection`. The label
+attributes (returned by get_label() method) of collected artists are
+used as text labels. If label attribute is empty string or starts with
+"_", that artist will be ignored.
+
+
+ * Note that not all kind of artists are supported by the legend. The
+ following is the list of artists that are currently supported.
+
+ * :class:`~matplotlib.lines.Line2D`
+ * :class:`~matplotlib.patches.Patch`
+ * :class:`~matplotlib.collections.LineCollection`
+ * :class:`~matplotlib.collections.RegularPolyCollection`
+
+ Unfortunately, there is no easy workaround when you need legend for
+ an artist not in the above list (You may use one of the supported
+ artist as a proxy. See below), or customize it beyond what is
+ supported by :class:`matplotlib.legend.Legend`.
+
+ * Remember that some *pyplot* commands return artist not supported by
+ legend, e.g., :func:`~matplotlib.pyplot.fill_between` returns
+ :class:`~matplotlib.collections.PolyCollection` that is not
+ supported. Or some return multiple artists. For example,
+ :func:`~matplotlib.pyplot.plot` returns list of
+ :class:`~matplotlib.lines.Line2D` instances, and
+ :func:`~matplotlib.pyplot.errorbar` returns a length 3 tuple of
+ :class:`~matplotlib.lines.Line2D` instances.
+
+ * The legend does not care about the axes that given artists belongs,
+ i.e., the artists may belong to other axes or even none.
+
+
+Adjusting the Order of Legend items
+-----------------------------------
+
+When you want to customize the list of artists to be displayed in the
+legend, or their order of appearance. There are a two options. First,
+you can keep lists of artists and labels, and explicitly use these for
+the first two argument of the legend call.::
+
+ p1, = plot([1,2,3])
+ p2, = plot([3,2,1])
+ p3, = plot([2,3,1])
+ legend([p2, p1], ["line 2", "line 1"])
+
+Or you may use :meth:`~matplotlib.axes.Axes.get_legend_handles_labels`
+to retrieve list of artist and labels and manipulate them before
+feeding them to legend call.::
+
+ ax = subplot(1,1,1)
+ p1, = ax.plot([1,2,3], label="line 1")
+ p2, = ax.plot([3,2,1], label="line 2")
+ p3, = ax.plot([2,3,1], label="line 3")
+
+ handles, labels = ax.get_legend_handles_labels()
+
+ # reverse the order
+ ax.legend(handles[::-1], labels[::-1])
+
+ # or sort them by labels
+ import operator
+ hl = sorted(zip(handles, labels),
+ key=operator.itemgetter(1))
+ handles2, labels2 = zip(*hl)
+
+ ax.legend(handles2, labels2)
+
+
+Using Proxy Artist
+------------------
+
+When you want to display legend for an artist not supported by the
+matplotlib, you may use other supported artist as a proxy. For
+example, you may creates an proxy artist without adding it to the axes
+(so the proxy artist will not be drawn in the main axes) and feet it
+to the legend function.::
+
+ p = Rectangle((0, 0), 1, 1, fc="r")
+ legend([p], ["Red Rectangle"])
+
+
+Multicolumn Legend
+==================
+
+By specifying the keyword argument *ncol*, you can have a multi-column
+legend. Also, mode="expand" horizontally expand the legend to fill the
+axes area. See `legend_demo3.py
+<http://matplotlib.sourceforge.net/examples/pylab_examples/legend_demo3.html>`_
+for example.
+
+
+Legend location
+===============
+
+The location of the legend can be specified by the keyword argument
+*loc*, either by string or a integer number.
+
+============= ======
+ String Number
+============= ======
+ upper right 1
+ upper left 2
+ lower left 3
+ lower right 4
+ right 5
+ center left 6
+ center right 7
+ lower center 8
+ upper center 9
+ center 10
+============= ======
+
+By default, the legend will anchor to the bbox of the axes
+(for legend) or the bbox of the figure (figlegend). You can specify
+your own bbox using *bbox_to_anchor* argument. *bbox_to_anchor* can be an
+instance of :class:`~matplotlib.transforms.BboxBase`, a tuple of 4
+floats (x, y, width, height of the bbox), or a tuple of 2 floats (x, y
+with width=height=0). Unless *bbox_transform* argument is given, the
+coordinates (even for the bbox instance) are considered as normalized
+axes coordinates.
+
+For example, if you want your axes legend located at the figure corner
+(instead of the axes corner)::
+
+ l = legend(bbox_to_anchor=(0, 0, 1, 1), transform=gcf().transFigure)
+
+Also, you can place above or outer right-hand side of the axes,
+
+.. plot:: users/plotting/examples/simple_legend01.py
+ :include-source:
+
+
+Multiple Legend
+===============
+
+Sometime, you want to split the legend into multiple ones.::
+
+ p1, = plot([1,2,3])
+ p2, = plot([3,2,1])
+ legend([p1], ["Test1"], loc=1)
+ legend([p2], ["Test2"], loc=4)
+
+However, the above code only shows the second legend. When the legend
+command is called, a new legend instance is created and old ones are
+removed from the axes. Thus, you need to manually add the removed
+legend.
+
+.. plot:: users/plotting/examples/simple_legend02.py
+ :include-source:
Modified: branches/v0_99_maint/doc/users/transforms_tutorial.rst
===================================================================
--- branches/v0_99_maint/doc/users/transforms_tutorial.rst 2009-08-15 17:40:27 UTC (rev 7489)
+++ branches/v0_99_maint/doc/users/transforms_tutorial.rst 2009-08-15 17:56:44 UTC (rev 7490)
@@ -12,7 +12,7 @@
happens under the hood, but as you push the limits of custom figure
generation, it helps to have an understanding of these objects so you
can reuse the existing transformations matplotlib makes available to
-you, or create your own. The table below summarizes the existing
+you, or create your own (see :mod:`matplotlib.transforms`. The table below summarizes the existing
coordinate systems, the transformation object you should use to work
in that coordinate system, and the description of that system. In the
`Transformation Object` column, ``ax`` is a :class:`~matplotlib.axes.Axes` instance,
@@ -276,7 +276,8 @@
it, adjusting the zorder to make sure the shadow is drawn first and
then the object it is shadowing above it. The transforms module has a
helper transformation
-:class:~matplotlib.tranasforms.ScaledTranslation`. It is instantiated with::
+:class:`~matplotlib.transforms.ScaledTranslation`. It is
+instantiated with::
trans = ScaledTranslation(xt, yt, scale_trans)
@@ -287,7 +288,7 @@
to first scale `xty and `yt` specified in points to `display` space
before doing the final offset. The dpi and inches offset is a
common-enough use case that we have a special helper function to
-create it in :func:`~matplotlib.transforms.offset_copy`, which returns
+create it in :func:`matplotlib.transforms.offset_copy`, which returns
a new transform with an added offset. But in the example below, we'll
create the offset trransform ourselves. Note the use of the plus
operator in::
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2009-08-15 17:40:35
|
Revision: 7489
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7489&view=rev
Author: jdh2358
Date: 2009-08-15 17:40:27 +0000 (Sat, 15 Aug 2009)
Log Message:
-----------
some doc reorg
Modified Paths:
--------------
branches/v0_99_maint/doc/users/index.rst
branches/v0_99_maint/doc/users/index_text.rst
Added Paths:
-----------
branches/v0_99_maint/doc/users/annotations_guide.rst
branches/v0_99_maint/doc/users/annotations_overview.rst
branches/v0_99_maint/doc/users/legend.rst
branches/v0_99_maint/doc/users/transforms_tutorial.rst
Removed Paths:
-------------
branches/v0_99_maint/doc/users/annotations.rst
branches/v0_99_maint/doc/users/plotting/annotation.rst
branches/v0_99_maint/doc/users/plotting/legend.rst
Deleted: branches/v0_99_maint/doc/users/annotations.rst
===================================================================
--- branches/v0_99_maint/doc/users/annotations.rst 2009-08-14 18:11:05 UTC (rev 7488)
+++ branches/v0_99_maint/doc/users/annotations.rst 2009-08-15 17:40:27 UTC (rev 7489)
@@ -1,87 +0,0 @@
-.. _annotations-tutorial:
-
-Annotating text
-===============
-
-For a more detailed introduction to annotations, see
-:ref:`plotting-guide-annotation`.
-
-The uses of the basic :func:`~matplotlib.pyplot.text` command above
-place text at an arbitrary position on the Axes. A common use case of
-text is to annotate some feature of the plot, and the
-:func:`~matplotlib.Axes.annotate` method provides helper functionality
-to make annotations easy. In an annotation, there are two points to
-consider: the location being annotated represented by the argument
-``xy`` and the location of the text ``xytext``. Both of these
-arguments are ``(x,y)`` tuples.
-
-.. plot:: pyplots/annotation_basic.py
- :include-source:
-
-
-In this example, both the ``xy`` (arrow tip) and ``xytext`` locations
-(text location) are in data coordinates. There are a variety of other
-coordinate systems one can choose -- you can specify the coordinate
-system of ``xy`` and ``xytext`` with one of the following strings for
-``xycoords`` and ``textcoords`` (default is 'data')
-
-==================== ====================================================
-argument coordinate system
-==================== ====================================================
- 'figure points' points from the lower left corner of the figure
- 'figure pixels' pixels from the lower left corner of the figure
- 'figure fraction' 0,0 is lower left of figure and 1,1 is upper, right
- 'axes points' points from lower left corner of axes
- 'axes pixels' pixels from lower left corner of axes
- 'axes fraction' 0,1 is lower left of axes and 1,1 is upper right
- 'data' use the axes data coordinate system
-==================== ====================================================
-
-For example to place the text coordinates in fractional axes
-coordinates, one could do::
-
- ax.annotate('local max', xy=(3, 1), xycoords='data',
- xytext=(0.8, 0.95), textcoords='axes fraction',
- arrowprops=dict(facecolor='black', shrink=0.05),
- horizontalalignment='right', verticalalignment='top',
- )
-
-For physical coordinate systems (points or pixels) the origin is the
-(bottom, left) of the figure or axes. If the value is negative,
-however, the origin is from the (right, top) of the figure or axes,
-analogous to negative indexing of sequences.
-
-Optionally, you can specify arrow properties which draws an arrow
-from the text to the annotated point by giving a dictionary of arrow
-properties in the optional keyword argument ``arrowprops``.
-
-
-==================== =====================================================
-``arrowprops`` key description
-==================== =====================================================
-width the width of the arrow in points
-frac the fraction of the arrow length occupied by the head
-headwidth the width of the base of the arrow head in points
-shrink move the tip and base some percent away from
- the annotated point and text
-
-\*\*kwargs any key for :class:`matplotlib.patches.Polygon`,
- e.g. ``facecolor``
-==================== =====================================================
-
-
-In the example below, the ``xy`` point is in native coordinates
-(``xycoords`` defaults to 'data'). For a polar axes, this is in
-(theta, radius) space. The text in this example is placed in the
-fractional figure coordinate system. :class:`matplotlib.text.Text`
-keyword args like ``horizontalalignment``, ``verticalalignment`` and
-``fontsize are passed from the `~matplotlib.Axes.annotate` to the
-``Text`` instance
-
-.. plot:: pyplots/annotation_polar.py
- :include-source:
-
-For more on all the wild and wonderful things you can do with
-annotations, including fancy arrows, see :ref:`plotting-guide-annotation`
-and :ref:`pylab_examples-annotation_demo`.
-
Copied: branches/v0_99_maint/doc/users/annotations_guide.rst (from rev 7488, branches/v0_99_maint/doc/users/plotting/annotation.rst)
===================================================================
--- branches/v0_99_maint/doc/users/annotations_guide.rst (rev 0)
+++ branches/v0_99_maint/doc/users/annotations_guide.rst 2009-08-15 17:40:27 UTC (rev 7489)
@@ -0,0 +1,332 @@
+.. _plotting-guide-annotation:
+
+****************
+Annotating Axes
+****************
+
+Do not proceed unless you already have read
+:func:`~matplotlib.pyplot.text` and :func:`~matplotlib.pyplot.annotate`!
+
+
+Annotating with Text with Box
+=============================
+
+Let's start with a simple example.
+
+.. plot:: users/plotting/examples/annotate_text_arrow.py
+
+
+The :func:`~matplotlib.pyplot.text` function in the pyplot module (or
+text method of the Axes class) takes bbox keyword argument, and when
+given, a box around the text is drawn. ::
+
+ bbox_props = dict(boxstyle="rarrow,pad=0.3", fc="cyan", ec="b", lw=2)
+ t = ax.text(0, 0, "Direction", ha="center", va="center", rotation=45,
+ size=15,
+ bbox=bbox_props)
+
+
+The patch object associated with the text can be accessed by::
+
+ bb = t.get_bbox_patch()
+
+The return value is an instance of FancyBboxPatch and the patch
+properties like facecolor, edgewidth, etc. can be accessed and
+modified as usual. To change the shape of the box, use *set_boxstyle*
+method. ::
+
+ bb.set_boxstyle("rarrow", pad=0.6)
+
+The arguments are the name of the box style with its attributes as
+keyword arguments. Currently, followign box styles are implemented.
+
+ ========== ============== ==========================
+ Class Name Attrs
+ ========== ============== ==========================
+ LArrow ``larrow`` pad=0.3
+ RArrow ``rarrow`` pad=0.3
+ Round ``round`` pad=0.3,rounding_size=None
+ Round4 ``round4`` pad=0.3,rounding_size=None
+ Roundtooth ``roundtooth`` pad=0.3,tooth_size=None
+ Sawtooth ``sawtooth`` pad=0.3,tooth_size=None
+ Square ``square`` pad=0.3
+ ========== ============== ==========================
+
+.. plot:: mpl_examples/pylab_examples/fancybox_demo2.py
+
+
+Note that the attrubutes arguments can be specified within the style
+name with separating comma (this form can be used as "boxstyle" value
+of bbox argument when initializing the text instance) ::
+
+ bb.set_boxstyle("rarrow,pad=0.6")
+
+
+
+
+Annotating with Arrow
+=====================
+
+The :func:`~matplotlib.pyplot.annotate` function in the pyplot module
+(or annotate method of the Axes class) is used to draw an arrow
+connecting two points on the plot. ::
+
+ ax.annotate("Annotation",
+ xy=(x1, y1), xycoords='data',
+ xytext=(x2, y2), textcoords='offset points',
+ )
+
+This annotates a point at ``xy`` in the given coordinate (``xycoords``)
+with the text at ``xytext`` given in ``textcoords``. Often, the
+annotated point is specified in the *data* coordinate and the annotating
+text in *offset points*.
+See :func:`~matplotlib.pyplot.annotate` for available coordinate systems.
+
+An arrow connecting two point (xy & xytext) can be optionally drawn by
+specifying the ``arrowprops`` argument. To draw only an arrow, use
+empty string as the first argument. ::
+
+ ax.annotate("",
+ xy=(0.2, 0.2), xycoords='data',
+ xytext=(0.8, 0.8), textcoords='data',
+ arrowprops=dict(arrowstyle="->",
+ connectionstyle="arc3"),
+ )
+
+.. plot:: users/plotting/examples/annotate_simple01.py
+
+The arrow drawing takes a few steps.
+
+1. a connecting path between two points are created. This is
+ controlled by ``connectionstyle`` key value.
+
+2. If patch object is given (*patchA* & *patchB*), the path is clipped to
+ avoid the patch.
+
+3. The path is further shrinked by given amount of pixels (*shirnkA*
+ & *shrinkB*)
+
+4. The path is transmuted to arrow patch, which is controlled by the
+ ``arrowstyle`` key value.
+
+
+.. plot:: users/plotting/examples/annotate_explain.py
+
+
+The creation of the connecting path between two points is controlled by
+``connectionstyle`` key and follwing styles are available.
+
+ ========== =============================================
+ Name Attrs
+ ========== =============================================
+ ``angle`` angleA=90,angleB=0,rad=0.0
+ ``angle3`` angleA=90,angleB=0
+ ``arc`` angleA=0,angleB=0,armA=None,armB=None,rad=0.0
+ ``arc3`` rad=0.0
+ ``bar`` armA=0.0,armB=0.0,fraction=0.3,angle=None
+ ========== =============================================
+
+Note that "3" in ``angle3`` and ``arc3`` is meant to indicate that the
+resulting path is a quadratic spline segment (three control
+points). As will be discussed below, some arrow style option only can
+be used when the connecting path is a quadratic spline.
+
+The behavior of each connection style is (limitedly) demonstrated in the
+example below. (Warning : The behavior of the ``bar`` style is currently not
+well defined, it may be changed in the future).
+
+.. plot:: users/plotting/examples/connectionstyle_demo.py
+
+
+The connecting path (after clipping and shrinking) is then mutated to
+an arrow patch, according to the given ``arrowstyle``.
+
+ ========== =============================================
+ Name Attrs
+ ========== =============================================
+ ``-`` None
+ ``->`` head_length=0.4,head_width=0.2
+ ``-[`` widthB=1.0,lengthB=0.2,angleB=None
+ ``-|>`` head_length=0.4,head_width=0.2
+ ``<-`` head_length=0.4,head_width=0.2
+ ``<->`` head_length=0.4,head_width=0.2
+ ``<|-`` head_length=0.4,head_width=0.2
+ ``<|-|>`` head_length=0.4,head_width=0.2
+ ``fancy`` head_length=0.4,head_width=0.4,tail_width=0.4
+ ``simple`` head_length=0.5,head_width=0.5,tail_width=0.2
+ ``wedge`` tail_width=0.3,shrink_factor=0.5
+ ========== =============================================
+
+.. plot:: mpl_examples/pylab_examples/fancyarrow_demo.py
+
+Some arrowstyles only work with connection style that generates a
+quadratic-spline segment. They are ``fancy``, ``simple``, and ``wedge``.
+For these arrow styles, you must use "angle3" or "arc3" connection
+style.
+
+If the annotation string is given, the patchA is set to the bbox patch
+of the text by default.
+
+.. plot:: users/plotting/examples/annotate_simple02.py
+
+As in the text command, a box around the text can be drawn using
+the ``bbox`` argument.
+
+.. plot:: users/plotting/examples/annotate_simple03.py
+
+By default, the starting point is set to the center of the text
+extent. This can be adjusted with ``relpos`` key value. The values
+are normalized to the extent of the text. For example, (0,0) means
+lower-left corner and (1,1) means top-right.
+
+.. plot:: users/plotting/examples/annotate_simple04.py
+
+
+Using ConnectorPatch
+====================
+
+The ConnectorPatch is like an annotation without a text. While the
+annotate function is recommended in most of situation, the
+ConnectorPatch is useful when you want to connect points in different
+axes. ::
+
+ from matplotlib.patches import ConnectionPatch
+ xy = (0.2, 0.2)
+ con = ConnectionPatch(xyA=xy, xyB=xy, coordsA="data", coordsB="data",
+ axesA=ax1, axesB=ax2)
+ ax2.add_artist(con)
+
+The above code connects point xy in data coordinate of ``ax1`` to
+point xy int data coordiante of ``ax2``. Here is a simple example.
+
+.. plot:: users/plotting/examples/connect_simple01.py
+
+
+While the ConnectorPatch instance can be added to any axes, but you
+may want it to be added to the axes in the latter (?) of the axes
+drawing order to prevent overlap (?) by other axes.
+
+
+Placing Artist at the anchored location of the Axes
+===================================================
+
+There are class of artist that can be placed at the anchored location
+of the Axes. A common example is the legend. This type of artists can
+be created by using the OffsetBox class. A few predefined classes are
+available in ``mpl_toolkits.axes_grid.anchored_artists``. ::
+
+ from mpl_toolkits.axes_grid.anchored_artists import AnchoredText
+ at = AnchoredText("Figure 1a",
+ prop=dict(size=8), frameon=True,
+ loc=2,
+ )
+ at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
+ ax.add_artist(at)
+
+
+.. plot:: users/plotting/examples/anchored_box01.py
+
+
+The *loc* keyword has same meaning as in the legend command.
+
+A simple application is when the size of the artist (or collection of
+artists) is knwon in pixel size during the time of creation. For
+example, If you want to draw a circle with fixed size of 20 pixel x 20
+pixel (radius = 10 pixel), you can utilize
+``AnchoredDrawingArea``. The instance is created with a size of the
+drawing area (in pixel). And user can add arbitrary artist to the
+drawing area. Note that the extents of the artists that are added to
+the drawing area has nothing to do with the placement of the drawing
+area itself. The initial size only matters. ::
+
+ from mpl_toolkits.axes_grid.anchored_artists import AnchoredDrawingArea
+
+ ada = AnchoredDrawingArea(20, 20, 0, 0,
+ loc=1, pad=0., frameon=False)
+ p1 = Circle((10, 10), 10)
+ ada.drawing_area.add_artist(p1)
+ p2 = Circle((30, 10), 5, fc="r")
+ ada.drawing_area.add_artist(p2)
+
+The artists that are added to the drawing area should not have
+transform set (they will be overridden) and the dimension of those
+artists are interpreted as a pixel coordinate, i.e., the radius of the
+circles in above example are 10 pixel and 5 pixel, respectively.
+
+.. plot:: users/plotting/examples/anchored_box02.py
+
+Sometimes, you want to your artists scale with data coordinate (or
+other coordinate than canvas pixel). You can use
+``AnchoredAuxTransformBox`` class. This is similar to
+``AnchoredDrawingArea`` except that the extent of the artist is
+determined during the drawing time respecting the specified transform. ::
+
+ from mpl_toolkits.axes_grid.anchored_artists import AnchoredAuxTransformBox
+
+ box = AnchoredAuxTransformBox(ax.transData, loc=2)
+ el = Ellipse((0,0), width=0.1, height=0.4, angle=30) # in data coordinates!
+ box.drawing_area.add_artist(el)
+
+The ellipse in the above example will have width and height
+corresponds to 0.1 and 0.4 in data coordinate and will be
+automatically scaled when the view limits of the axes change.
+
+.. plot:: users/plotting/examples/anchored_box03.py
+
+As in the legend, the bbox_to_anchor argument can be set. Using the
+HPacker and VPacker, you can have an arrangement(?) of artist as in the
+legend (as a matter of fact, this is how the legend is created).
+
+.. plot:: users/plotting/examples/anchored_box04.py
+
+Note that unlike the legend, the ``bbox_transform`` is set
+to IdentityTransform by default.
+
+Advanced Topics
+***************
+
+Zoom effect between Axes
+========================
+
+mpl_toolkits.axes_grid.inset_locator defines some patch classs useful
+for interconnect two axes. Understanding the code requires some
+knowledge of how mpl's transform works. But, utilizing it will be
+straight forward.
+
+
+.. plot:: mpl_examples/pylab_examples/axes_zoom_effect.py
+
+
+Define Custom BoxStyle
+======================
+
+You can use a custom box style. The value for the ``boxstyle`` can be a
+callable object in following forms.::
+
+ def __call__(self, x0, y0, width, height, mutation_size,
+ aspect_ratio=1.):
+ """
+ Given the location and size of the box, return the path of
+ the box around it.
+
+ - *x0*, *y0*, *width*, *height* : location and size of the box
+ - *mutation_size* : a reference scale for the mutation.
+ - *aspect_ratio* : aspect-ration for the mutation.
+ """
+ path = ...
+ return path
+
+Here is a complete example.
+
+.. plot:: users/plotting/examples/custom_boxstyle01.py
+
+However, it is recommended that you derive from the
+matplotlib.patches.BoxStyle._Base as demonstrated below.
+
+.. plot:: users/plotting/examples/custom_boxstyle02.py
+ :include-source:
+
+
+Similarly, you can define custom ConnectionStyle and Custome ArrowStyle.
+See the source code of ``lib/matplotlib/patches.py`` and check
+how each style class is defined.
Copied: branches/v0_99_maint/doc/users/annotations_overview.rst (from rev 7488, branches/v0_99_maint/doc/users/annotations.rst)
===================================================================
--- branches/v0_99_maint/doc/users/annotations_overview.rst (rev 0)
+++ branches/v0_99_maint/doc/users/annotations_overview.rst 2009-08-15 17:40:27 UTC (rev 7489)
@@ -0,0 +1,87 @@
+.. _annotations-tutorial:
+
+Annotating text
+===============
+
+For a more detailed introduction to annotations, see
+:ref:`plotting-guide-annotation`.
+
+The uses of the basic :func:`~matplotlib.pyplot.text` command above
+place text at an arbitrary position on the Axes. A common use case of
+text is to annotate some feature of the plot, and the
+:func:`~matplotlib.Axes.annotate` method provides helper functionality
+to make annotations easy. In an annotation, there are two points to
+consider: the location being annotated represented by the argument
+``xy`` and the location of the text ``xytext``. Both of these
+arguments are ``(x,y)`` tuples.
+
+.. plot:: pyplots/annotation_basic.py
+ :include-source:
+
+
+In this example, both the ``xy`` (arrow tip) and ``xytext`` locations
+(text location) are in data coordinates. There are a variety of other
+coordinate systems one can choose -- you can specify the coordinate
+system of ``xy`` and ``xytext`` with one of the following strings for
+``xycoords`` and ``textcoords`` (default is 'data')
+
+==================== ====================================================
+argument coordinate system
+==================== ====================================================
+ 'figure points' points from the lower left corner of the figure
+ 'figure pixels' pixels from the lower left corner of the figure
+ 'figure fraction' 0,0 is lower left of figure and 1,1 is upper, right
+ 'axes points' points from lower left corner of axes
+ 'axes pixels' pixels from lower left corner of axes
+ 'axes fraction' 0,1 is lower left of axes and 1,1 is upper right
+ 'data' use the axes data coordinate system
+==================== ====================================================
+
+For example to place the text coordinates in fractional axes
+coordinates, one could do::
+
+ ax.annotate('local max', xy=(3, 1), xycoords='data',
+ xytext=(0.8, 0.95), textcoords='axes fraction',
+ arrowprops=dict(facecolor='black', shrink=0.05),
+ horizontalalignment='right', verticalalignment='top',
+ )
+
+For physical coordinate systems (points or pixels) the origin is the
+(bottom, left) of the figure or axes. If the value is negative,
+however, the origin is from the (right, top) of the figure or axes,
+analogous to negative indexing of sequences.
+
+Optionally, you can specify arrow properties which draws an arrow
+from the text to the annotated point by giving a dictionary of arrow
+properties in the optional keyword argument ``arrowprops``.
+
+
+==================== =====================================================
+``arrowprops`` key description
+==================== =====================================================
+width the width of the arrow in points
+frac the fraction of the arrow length occupied by the head
+headwidth the width of the base of the arrow head in points
+shrink move the tip and base some percent away from
+ the annotated point and text
+
+\*\*kwargs any key for :class:`matplotlib.patches.Polygon`,
+ e.g. ``facecolor``
+==================== =====================================================
+
+
+In the example below, the ``xy`` point is in native coordinates
+(``xycoords`` defaults to 'data'). For a polar axes, this is in
+(theta, radius) space. The text in this example is placed in the
+fractional figure coordinate system. :class:`matplotlib.text.Text`
+keyword args like ``horizontalalignment``, ``verticalalignment`` and
+``fontsize are passed from the `~matplotlib.Axes.annotate` to the
+``Text`` instance
+
+.. plot:: pyplots/annotation_polar.py
+ :include-source:
+
+For more on all the wild and wonderful things you can do with
+annotations, including fancy arrows, see :ref:`plotting-guide-annotation`
+and :ref:`pylab_examples-annotation_demo`.
+
Modified: branches/v0_99_maint/doc/users/index.rst
===================================================================
--- branches/v0_99_maint/doc/users/index.rst 2009-08-14 18:11:05 UTC (rev 7488)
+++ branches/v0_99_maint/doc/users/index.rst 2009-08-15 17:40:27 UTC (rev 7489)
@@ -20,8 +20,11 @@
shell.rst
index_text.rst
artists.rst
+ legend_guide.rst
event_handling.rst
- plotting.rst
+ annotation_guide.rst
+ legend.rst
+ transforms_tutorial.rst
toolkits.rst
screenshots.rst
whats_new.rst
Modified: branches/v0_99_maint/doc/users/index_text.rst
===================================================================
--- branches/v0_99_maint/doc/users/index_text.rst 2009-08-14 18:11:05 UTC (rev 7488)
+++ branches/v0_99_maint/doc/users/index_text.rst 2009-08-15 17:40:27 UTC (rev 7489)
@@ -9,6 +9,6 @@
text_props.rst
mathtext.rst
usetex.rst
- annotations.rst
+ annotations_intro.rst
Copied: branches/v0_99_maint/doc/users/legend.rst (from rev 7488, branches/v0_99_maint/doc/users/plotting/legend.rst)
===================================================================
--- branches/v0_99_maint/doc/users/legend.rst (rev 0)
+++ branches/v0_99_maint/doc/users/legend.rst 2009-08-15 17:40:27 UTC (rev 7489)
@@ -0,0 +1,182 @@
+.. _plotting-guide-legend:
+
+************
+Legend guide
+************
+
+Do not proceed unless you already have read :func:`~matplotlib.pyplot.legend` and
+:class:`matplotlib.legend.Legend`!
+
+
+What to be displayed
+====================
+
+The legend command has a following call signature::
+
+ legend(*args, **kwargs)
+
+If len(args) is 2, the first argument should be a list of artist to be
+labeled, and the second argument should a list of string labels. If
+len(args) is 0, it automatically generate the legend from label
+properties of the child artists by calling
+:meth:`~matplotlib.axes.Axes.get_legend_handles_labels` method.
+For example, *ax.legend()* is equivalent to::
+
+ handles, labels = ax.get_legend_handles_labels()
+ ax.legend(handles, labels)
+
+The :meth:`~matplotlib.axes.Axes.get_legend_handles_labels` method
+returns a tuple of two lists, i.e., list of artists and list of labels
+(python string). However, it does not return all of its child
+artists. It returns all artists in *ax.lines* and *ax.patches* and
+some artists in *ax.collection* which are instance of
+:class:`~matplotlib.collections.LineCollection` or
+:class:`~matplotlib.collections.RegularPolyCollection`. The label
+attributes (returned by get_label() method) of collected artists are
+used as text labels. If label attribute is empty string or starts with
+"_", that artist will be ignored.
+
+
+ * Note that not all kind of artists are supported by the legend. The
+ following is the list of artists that are currently supported.
+
+ * :class:`~matplotlib.lines.Line2D`
+ * :class:`~matplotlib.patches.Patch`
+ * :class:`~matplotlib.collections.LineCollection`
+ * :class:`~matplotlib.collections.RegularPolyCollection`
+
+ Unfortunately, there is no easy workaround when you need legend for
+ an artist not in the above list (You may use one of the supported
+ artist as a proxy. See below), or customize it beyond what is
+ supported by :class:`matplotlib.legend.Legend`.
+
+ * Remember that some *pyplot* commands return artist not supported by
+ legend, e.g., :func:`~matplotlib.pyplot.fill_between` returns
+ :class:`~matplotlib.collections.PolyCollection` that is not
+ supported. Or some return multiple artists. For example,
+ :func:`~matplotlib.pyplot.plot` returns list of
+ :class:`~matplotlib.lines.Line2D` instances, and
+ :func:`~matplotlib.pyplot.errorbar` returns a length 3 tuple of
+ :class:`~matplotlib.lines.Line2D` instances.
+
+ * The legend does not care about the axes that given artists belongs,
+ i.e., the artists may belong to other axes or even none.
+
+
+Adjusting the Order of Legend items
+-----------------------------------
+
+When you want to customize the list of artists to be displayed in the
+legend, or their order of appearance. There are a two options. First,
+you can keep lists of artists and labels, and explicitly use these for
+the first two argument of the legend call.::
+
+ p1, = plot([1,2,3])
+ p2, = plot([3,2,1])
+ p3, = plot([2,3,1])
+ legend([p2, p1], ["line 2", "line 1"])
+
+Or you may use :meth:`~matplotlib.axes.Axes.get_legend_handles_labels`
+to retrieve list of artist and labels and manipulate them before
+feeding them to legend call.::
+
+ ax = subplot(1,1,1)
+ p1, = ax.plot([1,2,3], label="line 1")
+ p2, = ax.plot([3,2,1], label="line 2")
+ p3, = ax.plot([2,3,1], label="line 3")
+
+ handles, labels = ax.get_legend_handles_labels()
+
+ # reverse the order
+ ax.legend(handles[::-1], labels[::-1])
+
+ # or sort them by labels
+ import operator
+ hl = sorted(zip(handles, labels),
+ key=operator.itemgetter(1))
+ handles2, labels2 = zip(*hl)
+
+ ax.legend(handles2, labels2)
+
+
+Using Proxy Artist
+------------------
+
+When you want to display legend for an artist not supported by the
+matplotlib, you may use other supported artist as a proxy. For
+example, you may creates an proxy artist without adding it to the axes
+(so the proxy artist will not be drawn in the main axes) and feet it
+to the legend function.::
+
+ p = Rectangle((0, 0), 1, 1, fc="r")
+ legend([p], ["Red Rectangle"])
+
+
+Multicolumn Legend
+==================
+
+By specifying the keyword argument *ncol*, you can have a multi-column
+legend. Also, mode="expand" horizontally expand the legend to fill the
+axes area. See `legend_demo3.py
+<http://matplotlib.sourceforge.net/examples/pylab_examples/legend_demo3.html>`_
+for example.
+
+
+Legend location
+===============
+
+The location of the legend can be specified by the keyword argument
+*loc*, either by string or a integer number.
+
+============= ======
+ String Number
+============= ======
+ upper right 1
+ upper left 2
+ lower left 3
+ lower right 4
+ right 5
+ center left 6
+ center right 7
+ lower center 8
+ upper center 9
+ center 10
+============= ======
+
+By default, the legend will anchor to the bbox of the axes
+(for legend) or the bbox of the figure (figlegend). You can specify
+your own bbox using *bbox_to_anchor* argument. *bbox_to_anchor* can be an
+instance of :class:`~matplotlib.transforms.BboxBase`, a tuple of 4
+floats (x, y, width, height of the bbox), or a tuple of 2 floats (x, y
+with width=height=0). Unless *bbox_transform* argument is given, the
+coordinates (even for the bbox instance) are considered as normalized
+axes coordinates.
+
+For example, if you want your axes legend located at the figure corner
+(instead of the axes corner)::
+
+ l = legend(bbox_to_anchor=(0, 0, 1, 1), transform=gcf().transFigure)
+
+Also, you can place above or outer right-hand side of the axes,
+
+.. plot:: users/plotting/examples/simple_legend01.py
+ :include-source:
+
+
+Multiple Legend
+===============
+
+Sometime, you want to split the legend into multiple ones.::
+
+ p1, = plot([1,2,3])
+ p2, = plot([3,2,1])
+ legend([p1], ["Test1"], loc=1)
+ legend([p2], ["Test2"], loc=4)
+
+However, the above code only shows the second legend. When the legend
+command is called, a new legend instance is created and old ones are
+removed from the axes. Thus, you need to manually add the removed
+legend.
+
+.. plot:: users/plotting/examples/simple_legend02.py
+ :include-source:
Deleted: branches/v0_99_maint/doc/users/plotting/annotation.rst
===================================================================
--- branches/v0_99_maint/doc/users/plotting/annotation.rst 2009-08-14 18:11:05 UTC (rev 7488)
+++ branches/v0_99_maint/doc/users/plotting/annotation.rst 2009-08-15 17:40:27 UTC (rev 7489)
@@ -1,332 +0,0 @@
-.. _plotting-guide-annotation:
-
-****************
-Annotating Axes
-****************
-
-Do not proceed unless you already have read
-:func:`~matplotlib.pyplot.text` and :func:`~matplotlib.pyplot.annotate`!
-
-
-Annotating with Text with Box
-=============================
-
-Let's start with a simple example.
-
-.. plot:: users/plotting/examples/annotate_text_arrow.py
-
-
-The :func:`~matplotlib.pyplot.text` function in the pyplot module (or
-text method of the Axes class) takes bbox keyword argument, and when
-given, a box around the text is drawn. ::
-
- bbox_props = dict(boxstyle="rarrow,pad=0.3", fc="cyan", ec="b", lw=2)
- t = ax.text(0, 0, "Direction", ha="center", va="center", rotation=45,
- size=15,
- bbox=bbox_props)
-
-
-The patch object associated with the text can be accessed by::
-
- bb = t.get_bbox_patch()
-
-The return value is an instance of FancyBboxPatch and the patch
-properties like facecolor, edgewidth, etc. can be accessed and
-modified as usual. To change the shape of the box, use *set_boxstyle*
-method. ::
-
- bb.set_boxstyle("rarrow", pad=0.6)
-
-The arguments are the name of the box style with its attributes as
-keyword arguments. Currently, followign box styles are implemented.
-
- ========== ============== ==========================
- Class Name Attrs
- ========== ============== ==========================
- LArrow ``larrow`` pad=0.3
- RArrow ``rarrow`` pad=0.3
- Round ``round`` pad=0.3,rounding_size=None
- Round4 ``round4`` pad=0.3,rounding_size=None
- Roundtooth ``roundtooth`` pad=0.3,tooth_size=None
- Sawtooth ``sawtooth`` pad=0.3,tooth_size=None
- Square ``square`` pad=0.3
- ========== ============== ==========================
-
-.. plot:: mpl_examples/pylab_examples/fancybox_demo2.py
-
-
-Note that the attrubutes arguments can be specified within the style
-name with separating comma (this form can be used as "boxstyle" value
-of bbox argument when initializing the text instance) ::
-
- bb.set_boxstyle("rarrow,pad=0.6")
-
-
-
-
-Annotating with Arrow
-=====================
-
-The :func:`~matplotlib.pyplot.annotate` function in the pyplot module
-(or annotate method of the Axes class) is used to draw an arrow
-connecting two points on the plot. ::
-
- ax.annotate("Annotation",
- xy=(x1, y1), xycoords='data',
- xytext=(x2, y2), textcoords='offset points',
- )
-
-This annotates a point at ``xy`` in the given coordinate (``xycoords``)
-with the text at ``xytext`` given in ``textcoords``. Often, the
-annotated point is specified in the *data* coordinate and the annotating
-text in *offset points*.
-See :func:`~matplotlib.pyplot.annotate` for available coordinate systems.
-
-An arrow connecting two point (xy & xytext) can be optionally drawn by
-specifying the ``arrowprops`` argument. To draw only an arrow, use
-empty string as the first argument. ::
-
- ax.annotate("",
- xy=(0.2, 0.2), xycoords='data',
- xytext=(0.8, 0.8), textcoords='data',
- arrowprops=dict(arrowstyle="->",
- connectionstyle="arc3"),
- )
-
-.. plot:: users/plotting/examples/annotate_simple01.py
-
-The arrow drawing takes a few steps.
-
-1. a connecting path between two points are created. This is
- controlled by ``connectionstyle`` key value.
-
-2. If patch object is given (*patchA* & *patchB*), the path is clipped to
- avoid the patch.
-
-3. The path is further shrinked by given amount of pixels (*shirnkA*
- & *shrinkB*)
-
-4. The path is transmuted to arrow patch, which is controlled by the
- ``arrowstyle`` key value.
-
-
-.. plot:: users/plotting/examples/annotate_explain.py
-
-
-The creation of the connecting path between two points is controlled by
-``connectionstyle`` key and follwing styles are available.
-
- ========== =============================================
- Name Attrs
- ========== =============================================
- ``angle`` angleA=90,angleB=0,rad=0.0
- ``angle3`` angleA=90,angleB=0
- ``arc`` angleA=0,angleB=0,armA=None,armB=None,rad=0.0
- ``arc3`` rad=0.0
- ``bar`` armA=0.0,armB=0.0,fraction=0.3,angle=None
- ========== =============================================
-
-Note that "3" in ``angle3`` and ``arc3`` is meant to indicate that the
-resulting path is a quadratic spline segment (three control
-points). As will be discussed below, some arrow style option only can
-be used when the connecting path is a quadratic spline.
-
-The behavior of each connection style is (limitedly) demonstrated in the
-example below. (Warning : The behavior of the ``bar`` style is currently not
-well defined, it may be changed in the future).
-
-.. plot:: users/plotting/examples/connectionstyle_demo.py
-
-
-The connecting path (after clipping and shrinking) is then mutated to
-an arrow patch, according to the given ``arrowstyle``.
-
- ========== =============================================
- Name Attrs
- ========== =============================================
- ``-`` None
- ``->`` head_length=0.4,head_width=0.2
- ``-[`` widthB=1.0,lengthB=0.2,angleB=None
- ``-|>`` head_length=0.4,head_width=0.2
- ``<-`` head_length=0.4,head_width=0.2
- ``<->`` head_length=0.4,head_width=0.2
- ``<|-`` head_length=0.4,head_width=0.2
- ``<|-|>`` head_length=0.4,head_width=0.2
- ``fancy`` head_length=0.4,head_width=0.4,tail_width=0.4
- ``simple`` head_length=0.5,head_width=0.5,tail_width=0.2
- ``wedge`` tail_width=0.3,shrink_factor=0.5
- ========== =============================================
-
-.. plot:: mpl_examples/pylab_examples/fancyarrow_demo.py
-
-Some arrowstyles only work with connection style that generates a
-quadratic-spline segment. They are ``fancy``, ``simple``, and ``wedge``.
-For these arrow styles, you must use "angle3" or "arc3" connection
-style.
-
-If the annotation string is given, the patchA is set to the bbox patch
-of the text by default.
-
-.. plot:: users/plotting/examples/annotate_simple02.py
-
-As in the text command, a box around the text can be drawn using
-the ``bbox`` argument.
-
-.. plot:: users/plotting/examples/annotate_simple03.py
-
-By default, the starting point is set to the center of the text
-extent. This can be adjusted with ``relpos`` key value. The values
-are normalized to the extent of the text. For example, (0,0) means
-lower-left corner and (1,1) means top-right.
-
-.. plot:: users/plotting/examples/annotate_simple04.py
-
-
-Using ConnectorPatch
-====================
-
-The ConnectorPatch is like an annotation without a text. While the
-annotate function is recommended in most of situation, the
-ConnectorPatch is useful when you want to connect points in different
-axes. ::
-
- from matplotlib.patches import ConnectionPatch
- xy = (0.2, 0.2)
- con = ConnectionPatch(xyA=xy, xyB=xy, coordsA="data", coordsB="data",
- axesA=ax1, axesB=ax2)
- ax2.add_artist(con)
-
-The above code connects point xy in data coordinate of ``ax1`` to
-point xy int data coordiante of ``ax2``. Here is a simple example.
-
-.. plot:: users/plotting/examples/connect_simple01.py
-
-
-While the ConnectorPatch instance can be added to any axes, but you
-may want it to be added to the axes in the latter (?) of the axes
-drawing order to prevent overlap (?) by other axes.
-
-
-Placing Artist at the anchored location of the Axes
-===================================================
-
-There are class of artist that can be placed at the anchored location
-of the Axes. A common example is the legend. This type of artists can
-be created by using the OffsetBox class. A few predefined classes are
-available in ``mpl_toolkits.axes_grid.anchored_artists``. ::
-
- from mpl_toolkits.axes_grid.anchored_artists import AnchoredText
- at = AnchoredText("Figure 1a",
- prop=dict(size=8), frameon=True,
- loc=2,
- )
- at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
- ax.add_artist(at)
-
-
-.. plot:: users/plotting/examples/anchored_box01.py
-
-
-The *loc* keyword has same meaning as in the legend command.
-
-A simple application is when the size of the artist (or collection of
-artists) is knwon in pixel size during the time of creation. For
-example, If you want to draw a circle with fixed size of 20 pixel x 20
-pixel (radius = 10 pixel), you can utilize
-``AnchoredDrawingArea``. The instance is created with a size of the
-drawing area (in pixel). And user can add arbitrary artist to the
-drawing area. Note that the extents of the artists that are added to
-the drawing area has nothing to do with the placement of the drawing
-area itself. The initial size only matters. ::
-
- from mpl_toolkits.axes_grid.anchored_artists import AnchoredDrawingArea
-
- ada = AnchoredDrawingArea(20, 20, 0, 0,
- loc=1, pad=0., frameon=False)
- p1 = Circle((10, 10), 10)
- ada.drawing_area.add_artist(p1)
- p2 = Circle((30, 10), 5, fc="r")
- ada.drawing_area.add_artist(p2)
-
-The artists that are added to the drawing area should not have
-transform set (they will be overridden) and the dimension of those
-artists are interpreted as a pixel coordinate, i.e., the radius of the
-circles in above example are 10 pixel and 5 pixel, respectively.
-
-.. plot:: users/plotting/examples/anchored_box02.py
-
-Sometimes, you want to your artists scale with data coordinate (or
-other coordinate than canvas pixel). You can use
-``AnchoredAuxTransformBox`` class. This is similar to
-``AnchoredDrawingArea`` except that the extent of the artist is
-determined during the drawing time respecting the specified transform. ::
-
- from mpl_toolkits.axes_grid.anchored_artists import AnchoredAuxTransformBox
-
- box = AnchoredAuxTransformBox(ax.transData, loc=2)
- el = Ellipse((0,0), width=0.1, height=0.4, angle=30) # in data coordinates!
- box.drawing_area.add_artist(el)
-
-The ellipse in the above example will have width and height
-corresponds to 0.1 and 0.4 in data coordinate and will be
-automatically scaled when the view limits of the axes change.
-
-.. plot:: users/plotting/examples/anchored_box03.py
-
-As in the legend, the bbox_to_anchor argument can be set. Using the
-HPacker and VPacker, you can have an arrangement(?) of artist as in the
-legend (as a matter of fact, this is how the legend is created).
-
-.. plot:: users/plotting/examples/anchored_box04.py
-
-Note that unlike the legend, the ``bbox_transform`` is set
-to IdentityTransform by default.
-
-Advanced Topics
-***************
-
-Zoom effect between Axes
-========================
-
-mpl_toolkits.axes_grid.inset_locator defines some patch classs useful
-for interconnect two axes. Understanding the code requires some
-knowledge of how mpl's transform works. But, utilizing it will be
-straight forward.
-
-
-.. plot:: mpl_examples/pylab_examples/axes_zoom_effect.py
-
-
-Define Custom BoxStyle
-======================
-
-You can use a custom box style. The value for the ``boxstyle`` can be a
-callable object in following forms.::
-
- def __call__(self, x0, y0, width, height, mutation_size,
- aspect_ratio=1.):
- """
- Given the location and size of the box, return the path of
- the box around it.
-
- - *x0*, *y0*, *width*, *height* : location and size of the box
- - *mutation_size* : a reference scale for the mutation.
- - *aspect_ratio* : aspect-ration for the mutation.
- """
- path = ...
- return path
-
-Here is a complete example.
-
-.. plot:: users/plotting/examples/custom_boxstyle01.py
-
-However, it is recommended that you derive from the
-matplotlib.patches.BoxStyle._Base as demonstrated below.
-
-.. plot:: users/plotting/examples/custom_boxstyle02.py
- :include-source:
-
-
-Similarly, you can define custom ConnectionStyle and Custome ArrowStyle.
-See the source code of ``lib/matplotlib/patches.py`` and check
-how each style class is defined.
Deleted: branches/v0_99_maint/doc/users/plotting/legend.rst
===================================================================
--- branches/v0_99_maint/doc/users/plotting/legend.rst 2009-08-14 18:11:05 UTC (rev 7488)
+++ branches/v0_99_maint/doc/users/plotting/legend.rst 2009-08-15 17:40:27 UTC (rev 7489)
@@ -1,182 +0,0 @@
-.. _plotting-guide-legend:
-
-************
-Legend guide
-************
-
-Do not proceed unless you already have read :func:`~matplotlib.pyplot.legend` and
-:class:`matplotlib.legend.Legend`!
-
-
-What to be displayed
-====================
-
-The legend command has a following call signature::
-
- legend(*args, **kwargs)
-
-If len(args) is 2, the first argument should be a list of artist to be
-labeled, and the second argument should a list of string labels. If
-len(args) is 0, it automatically generate the legend from label
-properties of the child artists by calling
-:meth:`~matplotlib.axes.Axes.get_legend_handles_labels` method.
-For example, *ax.legend()* is equivalent to::
-
- handles, labels = ax.get_legend_handles_labels()
- ax.legend(handles, labels)
-
-The :meth:`~matplotlib.axes.Axes.get_legend_handles_labels` method
-returns a tuple of two lists, i.e., list of artists and list of labels
-(python string). However, it does not return all of its child
-artists. It returns all artists in *ax.lines* and *ax.patches* and
-some artists in *ax.collection* which are instance of
-:class:`~matplotlib.collections.LineCollection` or
-:class:`~matplotlib.collections.RegularPolyCollection`. The label
-attributes (returned by get_label() method) of collected artists are
-used as text labels. If label attribute is empty string or starts with
-"_", that artist will be ignored.
-
-
- * Note that not all kind of artists are supported by the legend. The
- following is the list of artists that are currently supported.
-
- * :class:`~matplotlib.lines.Line2D`
- * :class:`~matplotlib.patches.Patch`
- * :class:`~matplotlib.collections.LineCollection`
- * :class:`~matplotlib.collections.RegularPolyCollection`
-
- Unfortunately, there is no easy workaround when you need legend for
- an artist not in the above list (You may use one of the supported
- artist as a proxy. See below), or customize it beyond what is
- supported by :class:`matplotlib.legend.Legend`.
-
- * Remember that some *pyplot* commands return artist not supported by
- legend, e.g., :func:`~matplotlib.pyplot.fill_between` returns
- :class:`~matplotlib.collections.PolyCollection` that is not
- supported. Or some return multiple artists. For example,
- :func:`~matplotlib.pyplot.plot` returns list of
- :class:`~matplotlib.lines.Line2D` instances, and
- :func:`~matplotlib.pyplot.errorbar` returns a length 3 tuple of
- :class:`~matplotlib.lines.Line2D` instances.
-
- * The legend does not care about the axes that given artists belongs,
- i.e., the artists may belong to other axes or even none.
-
-
-Adjusting the Order of Legend items
------------------------------------
-
-When you want to customize the list of artists to be displayed in the
-legend, or their order of appearance. There are a two options. First,
-you can keep lists of artists and labels, and explicitly use these for
-the first two argument of the legend call.::
-
- p1, = plot([1,2,3])
- p2, = plot([3,2,1])
- p3, = plot([2,3,1])
- legend([p2, p1], ["line 2", "line 1"])
-
-Or you may use :meth:`~matplotlib.axes.Axes.get_legend_handles_labels`
-to retrieve list of artist and labels and manipulate them before
-feeding them to legend call.::
-
- ax = subplot(1,1,1)
- p1, = ax.plot([1,2,3], label="line 1")
- p2, = ax.plot([3,2,1], label="line 2")
- p3, = ax.plot([2,3,1], label="line 3")
-
- handles, labels = ax.get_legend_handles_labels()
-
- # reverse the order
- ax.legend(handles[::-1], labels[::-1])
-
- # or sort them by labels
- import operator
- hl = sorted(zip(handles, labels),
- key=operator.itemgetter(1))
- handles2, labels2 = zip(*hl)
-
- ax.legend(handles2, labels2)
-
-
-Using Proxy Artist
-------------------
-
-When you want to display legend for an artist not supported by the
-matplotlib, you may use other supported artist as a proxy. For
-example, you may creates an proxy artist without adding it to the axes
-(so the proxy artist will not be drawn in the main axes) and feet it
-to the legend function.::
-
- p = Rectangle((0, 0), 1, 1, fc="r")
- legend([p], ["Red Rectangle"])
-
-
-Multicolumn Legend
-==================
-
-By specifying the keyword argument *ncol*, you can have a multi-column
-legend. Also, mode="expand" horizontally expand the legend to fill the
-axes area. See `legend_demo3.py
-<http://matplotlib.sourceforge.net/examples/pylab_examples/legend_demo3.html>`_
-for example.
-
-
-Legend location
-===============
-
-The location of the legend can be specified by the keyword argument
-*loc*, either by string or a integer number.
-
-============= ======
- String Number
-============= ======
- upper right 1
- upper left 2
- lower left 3
- lower right 4
- right 5
- center left 6
- center right 7
- lower center 8
- upper center 9
- center 10
-============= ======
-
-By default, the legend will anchor to the bbox of the axes
-(for legend) or the bbox of the figure (figlegend). You can specify
-your own bbox using *bbox_to_anchor* argument. *bbox_to_anchor* can be an
-instance of :class:`~matplotlib.transforms.BboxBase`, a tuple of 4
-floats (x, y, width, height of the bbox), or a tuple of 2 floats (x, y
-with width=height=0). Unless *bbox_transform* argument is given, the
-coordinates (even for the bbox instance) are considered as normalized
-axes coordinates.
-
-For example, if you want your axes legend located at the figure corner
-(instead of the axes corner)::
-
- l = legend(bbox_to_anchor=(0, 0, 1, 1), transform=gcf().transFigure)
-
-Also, you can place above or outer right-hand side of the axes,
-
-.. plot:: users/plotting/examples/simple_legend01.py
- :include-source:
-
-
-Multiple Legend
-===============
-
-Sometime, you want to split the legend into multiple ones.::
-
- p1, = plot([1,2,3])
- p2, = plot([3,2,1])
- legend([p1], ["Test1"], loc=1)
- legend([p2], ["Test2"], loc=4)
-
-However, the above code only shows the second legend. When the legend
-command is called, a new legend instance is created and old ones are
-removed from the axes. Thus, you need to manually add the removed
-legend.
-
-.. plot:: users/plotting/examples/simple_legend02.py
- :include-source:
Added: branches/v0_99_maint/doc/users/transforms_tutorial.rst
===================================================================
--- branches/v0_99_maint/doc/users/transforms_tutorial.rst (rev 0)
+++ branches/v0_99_maint/doc/users/transforms_tutorial.rst 2009-08-15 17:40:27 UTC (rev 7489)
@@ -0,0 +1,428 @@
+.. _transformstutorial:
+
+**************************
+Transformations Tutorial
+**************************
+
+Like any graphics packages, matplotlib is built on top of a
+transformation framework to easily move between coordinate systems,
+the userland `data` coordinate system, the `axes` coordinate system,
+the `figure` coordinate system, and the `display` coordinate system.
+In 95% of your plotting, you won't need to think about this, as it
+happens under the hood, but as you push the limits of custom figure
+generation, it helps to have an understanding of these objects so you
+can reuse the existing transformations matplotlib makes available to
+you, or create your own. The table below summarizes the existing
+coordinate systems, the transformation object you should use to work
+in that coordinate system, and the description of that system. In the
+`Transformation Object` column, ``ax`` is a :class:`~matplotlib.axes.Axes` instance,
+and ``fig`` is a :class:`~matplotlib.figure.Figure` instance.
+
+========== ===================== ==============================================================================================================================================================
+Coordinate Transformation Object Description
+========== ===================== ==============================================================================================================================================================
+`data` ``ax.transData`` The userland data coordinate system, controlled by the xlim and ylim
+`axes` ``ax.transAxes`` The coordinate system of the :class:`~matplotlib.axes.Axes`; (0,0) is bottom left of the axes, and (1,1) is top right of the axes
+`figure` ``fig.transFigure`` The coordinate system of the :class:`~matplotlib.figure.Figure`; (0,0) is bottom left of the figure, and (1,1) is top right of the figure
+`display` `None` This is the pixel coordinate system of the display; (0,0) is the bottom left of the display, and (width, height) is the top right of the display in pixels
+========== ===================== ==============================================================================================================================================================
+
+
+All of the transformation objects take inputs in their coordinate
+system, and transform the input to the `display` coordinate system.
+That is why the `display` coordinate system has `None` for the
+`Transformation Object` column -- it already is in display
+coordinates. The transformations also know how to invert themselves,
+to go from `display` back to the native coordinate system. This is
+particularly useful when processing events frmo the user interface,
+which typically occur in display space, and you want to know where the
+mouse click or key-press occurred in your data coordinate system.
+
+.. _data-coords:
+
+Data coordinates
+================
+
+Let's start with the most commonly used coordinate, the `data`
+coordinate system. Whenever, you add data to the axes, matplotlib
+updates the datalimits, most commonly updated in with the
+:meth:`~matplotlib.axes.Axes.set_xlim` and
+:meth:`~matplotlib.axes.Axes.set_ylim` methods. For example, in the
+figure below, the data limits stretch from 0 to 10 on the x-axis, and
+-1 to 1 on the y-axis.
+
+.. plot::
+ :include-source:
+
+ import numpy as np
+ import matplotlib.pyplot as plt
+
+ x = np.arange(0, 10, 0.005)
+ y = np.exp(-x/2.) * np.sin(2*np.pi*x)
+
+ fig = plt.figure()
+ ax = fig.add_subplot(111)
+ ax.plot(x, y)
+ ax.set_xlim(0, 10)
+ ax.set_ylim(-1, 1)
+
+ plt.show()
+
+You can use the ``ax.transData`` instance to transform from your
+`data` to your `display` coordinate system, either a single point or a
+sequence of points as shown below:
+
+.. sourcecode:: ipython
+
+ In [14]: type(ax.transData)
+ Out[14]: <class 'matplotlib.transforms.CompositeGenericTransform'>
+
+ In [15]: ax.transData.transform((5, 0))
+ Out[15]: array([ 335.175, 247. ])
+
+ In [16]: ax.transData.transform([(5, 0), (1,2)])
+ Out[16]:
+ array([[ 335.175, 247. ],
+ [ 132.435, 642.2 ]])
+
+You can use the :meth`~matplotlib.transforms.Transform.inverted`
+method to create a transform which will take you from display to data
+coordinates:
+
+.. sourcecode:: ipython
+
+ In [41]: inv = ax.transData.inverted()
+
+ In [42]: type(inv)
+ Out[42]: <class 'matplotlib.transforms.CompositeGenericTransform'>
+
+ In [43]: inv.transform((335.175, 247.))
+ Out[43]: array([ 5., 0.])
+
+If your are typing along with this tutorial, the exact values of the
+display coordinates may differ if you have a different window size or
+dpi setting. Likewise, in the figure below, the display labeled
+points are probably not the same as in the ipython session because the
+documentation figure size defaults are different.
+
+.. plot:: pyplots/annotate_transform.py
+
+
+.. note::
+ If you run the source code in the example above in a GUI backend,
+ you may also find that the two arrows for the `data` and `display`
+ annotations do not point to exactly the same point. This is because
+ the display point was computed before the figure was displayed, and
+ the GUI backend may slightly resize the figure when it is created.
+ The effect is more pronounced if you resize the figure yourself.
+ This is one good reason why you rarely want to work in display
+ space, but you can connect to the ``'on_draw'``
+ :class:`~matplotlib.backend_bases.Event` to update figure
+ coordinates on figure draws; see :ref:`event-handling-tutorial`.
+
+When you change the x or y limits of your axes, the data limits are
+updated so the transformation yields a new display point. Note that
+when we just change the ylim, only the y-display coordinate is
+altered, and when we change the xlim too, both are altered. More on
+this later when we talk about the
+:class:`~matplotlib.transforms.Bbox`.
+
+.. sourcecode:: ipython
+
+ In [54]: ax.transData.transform((5, 0))
+ Out[54]: array([ 335.175, 247. ])
+
+ In [55]: ax.set_ylim(-1,2)
+ Out[55]: (-1, 2)
+
+ In [56]: ax.transData.transform((5, 0))
+ Out[56]: array([ 335.175 , 181.13333333])
+
+ In [57]: ax.set_xlim(10,20)
+ Out[57]: (10, 20)
+
+ In [58]: ax.transData.transform((5, 0))
+ Out[58]: array([-171.675 , 181.13333333])
+
+
+
+.. _axes-coords:
+
+Axes coordinates
+================
+
+After the `data` coordinate system, `axes` is probably the second most
+useful coordinate system. Here the point (0,0) is the bottom left
+of your axes or subplot, (0.5, 0.5) is the center, and (1.0,
+1.0) is the top right. You can also refer to points outside the
+range, so (-0.1, 1.1) is to the left and above your axes. This
+coordinate system is extremely useful when making placing text in your
+axes, because you often want a text bubble in a fixed, location, eg
+the upper left of the axes pane, and have that location remain fixed
+when you pan or zoom. Here is a simple example that creates four
+panels and labels them 'A', 'B', 'C', 'D' as you often see in journals.
+
+.. plot::
+ :include-source:
+
+ import numpy as np
+ import matplotlib.pyplot as plt
+
+ fig = plt.figure()
+ for i, label in enumerate(('A', 'B', 'C', 'D')):
+ ax = fig.add_subplot(2,2,i+1)
+ ax.text(0.05, 0.95, label, transform=ax.transAxes,
+ fontsize=16, fontweight='bold', va='top')
+
+ plt.show()
+
+You can also make lines or patches in the axes coordinate system, but
+this is less useful in my experience than using ``ax.transAxes`` for
+placing text. Nonetheless, here is a silly example which plots some
+random dots in `data` space, and overlays a semi-transparent
+:class:`~matplotlib.patches.Circle` centered in the middle of the axes
+with a radius one quarter of the axes -- if your axes does not
+preserve aspect ratio (see :meth:`~matplotlib.axes.Axes.set_aspect`),
+this will look like an ellipse. Use the pan/zoom tool to move around,
+or manually change the data xlim and ylim, and you will see the data
+move, but the circle will remain fixed because it is not in `data`
+coordinates and will always remain at the center of the axes.
+
+.. plot::
+ :include-source:
+
+ import numpy as np
+ import matplotlib.pyplot as plt
+ import matplotlib.patches as patches
+ fig = plt.figure()
+ ax = fig.add_subplot(111)
+ x, y = 10*np.random.rand(2, 1000)
+ ax.plot(x, y, 'go') # plot some data in data coordinates
+
+ circ = patches.Circle((0.5, 0.5), 0.25, transform=ax.transAxes,
+ facecolor='yellow', alpha=0.5)
+ ax.add_patch(circ)
+
+ plt.show()
+
+.. blended_transformations:
+
+Blended transformations
+=======================
+
+Drawing in `blended` coordinate spaces which mix `axes` with `data`
+coordinates is extremely useful, for example to create a horizontal
+span which highlights some region of the y-data but spans across the
+x-axis regardless of the data limits, pan or zoom level, etc. In fact
+these blended lines and spans are so useful, we have built in
+functions to make them easy to plot (see
+:meth:`~matplotlib.axes.Axes.axhline`,
+:meth:`~matplotlib.axes.Axes.axvline`,
+:meth:`~matplotlib.axes.Axes.axhspan`,
+:meth:`~matplotlib.axes.Axes.axvspan`) but for didactic purposes we
+will implement the horizontal span here using a blended
+transformation. This trick only works for separable transformations,
+like you see in normal cartesian coordinate systems, but not on
+inseparable transformations like the
+:class:`~matplotlib.projections.polar.PolarAxes.PolarTransform`.
+
+.. plot::
+ :include-source:
+
+ import numpy as np
+ import matplotlib.pyplot as plt
+ import matplotlib.patches as patches
+ import matplotlib.transforms as transforms
+
+ fig = plt.figure()
+ ax = fig.add_subplot(111)
+
+ x = np.random.randn(1000)
+
+ ax.hist(x, 30)
+ ax.set_title(r'$\sigma=1 \/ \dots \/ \sigma=2$', fontsize=16)
+
+ # the x coords of this transformation are data, and the
+ # y coord are axes
+ trans = transforms.blended_transform_factory(
+ ax.transData, ax.transAxes)
+
+ # highlight the 1..2 stddev region with a span.
+ # We want x to be in data coordinates and y to
+ # span from 0..1 in axes coords
+ rect = patches.Rectangle((1,0), width=1, height=1,
+ transform=trans, color='yellow',
+ alpha=0.5)
+
+ ax.add_patch(rect)
+
+ plt.show()
+
+
+.. offset-transforms-shadow:
+
+Using offset transforms to create a shadow effect
+=================================================
+
+One use of transformations is to create a new transformation that is
+offset from another annotation, eg to place one object shited a bit
+relative to another object. Typically you want the shift to be in
+some physical dimension, like points or inches rather than in data
+coordinates, so that the shift effect is constant at different zoom
+levels and dpi settings.
+
+One use for an offset is to create a shadow effect, where you draw one
+object identical to the first just to the right of it, and just below
+it, adjusting the zorder to make sure the shadow is drawn first and
+then the object it is sh...
[truncated message content] |
|
From: <lee...@us...> - 2009-08-14 18:11:13
|
Revision: 7488
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7488&view=rev
Author: leejjoon
Date: 2009-08-14 18:11:05 +0000 (Fri, 14 Aug 2009)
Log Message:
-----------
add support for image filtering in agg backend
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/artist.py
trunk/matplotlib/lib/matplotlib/backend_bases.py
trunk/matplotlib/lib/matplotlib/backends/backend_agg.py
trunk/matplotlib/lib/matplotlib/backends/backend_mixed.py
trunk/matplotlib/lib/matplotlib/colors.py
trunk/matplotlib/lib/matplotlib/text.py
Added Paths:
-----------
trunk/matplotlib/examples/pylab_examples/demo_agg_filter.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2009-08-14 13:56:44 UTC (rev 7487)
+++ trunk/matplotlib/CHANGELOG 2009-08-14 18:11:05 UTC (rev 7488)
@@ -1,3 +1,6 @@
+2009-08-14 Add support for image filtering for agg back end. See the example
+ demo_agg_filter.py. -JJL
+
2009-08-09 AnnotationBbox added. Similar to Annotation, but works with
OffsetBox instead of Text. See the example
demo_annotation_box.py. -JJL
Added: trunk/matplotlib/examples/pylab_examples/demo_agg_filter.py
===================================================================
--- trunk/matplotlib/examples/pylab_examples/demo_agg_filter.py (rev 0)
+++ trunk/matplotlib/examples/pylab_examples/demo_agg_filter.py 2009-08-14 18:11:05 UTC (rev 7488)
@@ -0,0 +1,312 @@
+import matplotlib.pyplot as plt
+
+import numpy as np
+import scipy.ndimage as NI
+import matplotlib.cm as cm
+import matplotlib.mlab as mlab
+
+
+class BaseFilter(object):
+ def prepare_image(self, src_image, dpi, pad):
+ ny, nx, depth = src_image.shape
+ #tgt_image = np.zeros([pad*2+ny, pad*2+nx, depth], dtype="d")
+ padded_src = np.zeros([pad*2+ny, pad*2+nx, depth], dtype="d")
+ padded_src[pad:-pad, pad:-pad,:] = src_image[:,:,:]
+
+ return padded_src#, tgt_image
+
+ def get_pad(self, dpi):
+ return 0
+
+ def __call__(self, im, dpi):
+ pad = self.get_pad(dpi)
+ padded_src = self.prepare_image(im, dpi, pad)
+ tgt_image = self.process_image(padded_src, dpi)
+ return tgt_image, -pad, -pad
+
+
+class OffsetFilter(BaseFilter):
+ def __init__(self, offsets=None):
+ if offsets is None:
+ self.offsets = (0, 0)
+ else:
+ self.offsets = offsets
+
+ def get_pad(self, dpi):
+ return max(*self.offsets)
+
+ def process_image(self, padded_src, dpi):
+ ox, oy = self.offsets
+ a1 = np.roll(padded_src, ox, axis=1)
+ a2 = np.roll(a1, -oy, axis=0)
+ return a2
+
+class GaussianFilter(BaseFilter):
+ "simple gauss filter"
+ def __init__(self, sigma, alpha=0.5, color=None):
+ self.sigma = sigma
+ self.alpha = alpha
+ if color is None:
+ self.color=(0, 0, 0)
+ else:
+ self.color=color
+
+ def get_pad(self, dpi):
+ return int(self.sigma*3)
+
+
+ def process_image(self, padded_src, dpi):
+ #offsetx, offsety = int(self.offsets[0]), int(self.offsets[1])
+ tgt_image = np.zeros_like(padded_src)
+ tgt_image[:,:,-1] = NI.gaussian_filter(padded_src[:,:,-1]*self.alpha,
+ self.sigma)
+ tgt_image[:,:,:-1] = self.color
+ return tgt_image
+
+class DropShadowFilter(BaseFilter):
+ def __init__(self, sigma, alpha=0.3, color=None, offsets=None):
+ self.gauss_filter = GaussianFilter(sigma, alpha, color)
+ self.offset_filter = OffsetFilter(offsets)
+
+ def get_pad(self, dpi):
+ return max(self.gauss_filter.get_pad(dpi),
+ self.offset_filter.get_pad(dpi))
+
+ def process_image(self, padded_src, dpi):
+ t1 = self.gauss_filter.process_image(padded_src, dpi)
+ t2 = self.offset_filter.process_image(t1, dpi)
+ return t2
+
+
+from matplotlib.colors import LightSource
+
+class LightFilter(BaseFilter):
+ "simple gauss filter"
+ def __init__(self, sigma, fraction=0.5):
+ self.gauss_filter = GaussianFilter(sigma, alpha=1)
+ self.light_source = LightSource()
+ self.fraction = fraction
+ #hsv_min_val=0.5,hsv_max_val=0.9,
+ # hsv_min_sat=0.1,hsv_max_sat=0.1)
+ def get_pad(self, dpi):
+ return self.gauss_filter.get_pad(dpi)
+
+ def process_image(self, padded_src, dpi):
+ t1 = self.gauss_filter.process_image(padded_src, dpi)
+ elevation = t1[:,:,3]
+ rgb = padded_src[:,:,:3]
+
+ rgb2 = self.light_source.shade_rgb(rgb, elevation,
+ fraction=self.fraction)
+
+ tgt = np.empty_like(padded_src)
+ tgt[:,:,:3] = rgb2
+ tgt[:,:,3] = padded_src[:,:,3]
+
+ return tgt
+
+
+
+class GrowFilter(BaseFilter):
+ "enlarge the area"
+ def __init__(self, pixels, color=None):
+ self.pixels = pixels
+ if color is None:
+ self.color=(1, 1, 1)
+ else:
+ self.color=color
+
+ def __call__(self, im, dpi):
+ pad = self.pixels
+ ny, nx, depth = im.shape
+ new_im = np.empty([pad*2+ny, pad*2+nx, depth], dtype="d")
+ alpha = new_im[:,:,3]
+ alpha.fill(0)
+ alpha[pad:-pad, pad:-pad] = im[:,:,-1]
+ alpha2 = NI.grey_dilation(alpha, size=(self.pixels, self.pixels))
+ new_im[:,:,-1] = alpha2
+ new_im[:,:,:-1] = self.color
+ offsetx, offsety = -pad, -pad
+
+ return new_im, offsetx, offsety
+
+
+from matplotlib.artist import Artist
+
+class FilteredArtistList(Artist):
+ """
+ A simple container to draw filtered artist.
+ """
+ def __init__(self, artist_list, filter):
+ self._artist_list = artist_list
+ self._filter = filter
+ Artist.__init__(self)
+
+ def draw(self, renderer):
+ renderer.start_rasterizing()
+ renderer.start_filter()
+ for a in self._artist_list:
+ a.draw(renderer)
+ renderer.stop_filter(self._filter)
+ renderer.stop_rasterizing()
+
+
+
+import matplotlib.transforms as mtransforms
+
+def filtered_text(ax):
+ # mostly copied from contour_demo.py
+
+ # prepare image
+ delta = 0.025
+ x = np.arange(-3.0, 3.0, delta)
+ y = np.arange(-2.0, 2.0, delta)
+ X, Y = np.meshgrid(x, y)
+ Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
+ Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
+ # difference of Gaussians
+ Z = 10.0 * (Z2 - Z1)
+
+
+ # draw
+ im = ax.imshow(Z, interpolation='bilinear', origin='lower',
+ cmap=cm.gray, extent=(-3,3,-2,2))
+ levels = np.arange(-1.2, 1.6, 0.2)
+ CS = ax.contour(Z, levels,
+ origin='lower',
+ linewidths=2,
+ extent=(-3,3,-2,2))
+
+ ax.set_aspect("auto")
+
+ # contour label
+ cl = ax.clabel(CS, levels[1::2], # label every second level
+ inline=1,
+ fmt='%1.1f',
+ fontsize=11)
+
+ # change clable color to black
+ for t in cl:
+ t.set_color("k")
+
+ # Add white glows to improve visibility of labels.
+ white_glows = FilteredArtistList(cl, GrowFilter(3))
+ ax.add_artist(white_glows)
+ white_glows.set_zorder(cl[0].get_zorder()-0.1)
+
+ ax.xaxis.set_visible(False)
+ ax.yaxis.set_visible(False)
+
+
+def drop_shadow_line(ax):
+ # copyed from examples/misc/svg_filter_line.py
+
+ # draw lines
+ l1, = ax.plot([0.1, 0.5, 0.9], [0.1, 0.9, 0.5], "bo-",
+ mec="b", mfc="w", lw=5, mew=3, ms=10, label="Line 1")
+ l2, = ax.plot([0.1, 0.5, 0.9], [0.5, 0.2, 0.7], "ro-",
+ mec="r", mfc="w", lw=5, mew=3, ms=10, label="Line 1")
+
+
+ gauss = DropShadowFilter(2)
+
+ for l in [l1, l2]:
+
+ # draw shadows with same lines with slight offset.
+
+ xx = l.get_xdata()
+ yy = l.get_ydata()
+ shadow, = ax.plot(xx, yy)
+ shadow.update_from(l)
+
+ # offset transform
+ ot = mtransforms.offset_copy(l.get_transform(), ax.figure,
+ x=4.0, y=-6.0, units='points')
+
+ shadow.set_transform(ot)
+
+
+ # adjust zorder of the shadow lines so that it is drawn below the
+ # original lines
+ shadow.set_zorder(l.get_zorder()-0.5)
+ shadow.set_agg_filter(gauss)
+ shadow.set_rasterized(True) # to support mixed-mode renderers
+
+
+
+ ax.set_xlim(0., 1.)
+ ax.set_ylim(0., 1.)
+
+ ax.xaxis.set_visible(False)
+ ax.yaxis.set_visible(False)
+
+
+
+
+def drop_shadow_patches(ax):
+ # copyed from barchart_demo.py
+ N = 5
+ menMeans = (20, 35, 30, 35, 27)
+
+ ind = np.arange(N) # the x locations for the groups
+ width = 0.35 # the width of the bars
+
+ rects1 = ax.bar(ind, menMeans, width, color='r', ec="w", lw=2)
+
+ womenMeans = (25, 32, 34, 20, 25)
+ rects2 = ax.bar(ind+width+0.1, womenMeans, width, color='y', ec="w", lw=2)
+
+ #gauss = GaussianFilter(1.5, offsets=(1,1), )
+ gauss = DropShadowFilter(1.5, offsets=(1,1), )
+ shadow = FilteredArtistList(rects1+rects2, gauss)
+ ax.add_artist(shadow)
+ shadow.set_zorder(rects1[0].get_zorder()-0.1)
+
+ ax.set_xlim(ind[0]-0.5, ind[-1]+1.5)
+ ax.set_ylim(0, 40)
+
+ ax.xaxis.set_visible(False)
+ ax.yaxis.set_visible(False)
+
+
+def light_filter_pie(ax):
+ fracs = [15,30,45, 10]
+ explode=(0, 0.05, 0, 0)
+ pies = ax.pie(fracs, explode=explode)
+ ax.patch.set_visible(True)
+
+ light_filter = LightFilter(8)
+ for p in pies[0]:
+ p.set_agg_filter(light_filter)
+ p.set_rasterized(True) # to support mixed-mode renderers
+ p.set(ec="none",
+ lw=2)
+
+ gauss = DropShadowFilter(3, offsets=(3,4), alpha=0.7)
+ shadow = FilteredArtistList(pies[0], gauss)
+ ax.add_artist(shadow)
+ shadow.set_zorder(pies[0][0].get_zorder()-0.1)
+
+
+if 1:
+
+ plt.figure(1, figsize=(6, 6))
+ plt.subplots_adjust(left=0.05, right=0.95)
+
+ ax = plt.subplot(221)
+ filtered_text(ax)
+
+ ax = plt.subplot(222)
+ drop_shadow_line(ax)
+
+ ax = plt.subplot(223)
+ drop_shadow_patches(ax)
+
+ ax = plt.subplot(224)
+ ax.set_aspect(1)
+ light_filter_pie(ax)
+ ax.set_frame_on(True)
+
+ plt.show()
+
+
Modified: trunk/matplotlib/lib/matplotlib/artist.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/artist.py 2009-08-14 13:56:44 UTC (rev 7487)
+++ trunk/matplotlib/lib/matplotlib/artist.py 2009-08-14 18:11:05 UTC (rev 7488)
@@ -36,7 +36,15 @@
if artist.get_rasterized():
renderer.start_rasterizing()
+ if artist.get_agg_filter() is not None:
+ renderer.start_filter()
+
+
def after(artist, renderer):
+
+ if artist.get_agg_filter() is not None:
+ renderer.stop_filter(artist.get_agg_filter())
+
if artist.get_rasterized():
renderer.stop_rasterizing()
@@ -78,7 +86,8 @@
self._picker = None
self._contains = None
self._rasterized = None
-
+ self._agg_filter = None
+
self.eventson = False # fire events only if eventson
self._oid = 0 # an observer id
self._propobservers = {} # a dict from oids to funcs
@@ -548,6 +557,7 @@
gc.set_clip_path(None)
def get_rasterized(self):
+ "return True if the artist is to be rasterized"
return self._rasterized
def set_rasterized(self, rasterized):
@@ -563,6 +573,17 @@
self._rasterized = rasterized
+ def get_agg_filter(self):
+ "return filter function to be used for agg filter"
+ return self._agg_filter
+
+ def set_agg_filter(self, filter_func):
+ """
+ set agg_filter fuction.
+
+ """
+ self._agg_filter = filter_func
+
def draw(self, renderer, *args, **kwargs):
'Derived classes drawing method'
if not self.get_visible(): return
Modified: trunk/matplotlib/lib/matplotlib/backend_bases.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backend_bases.py 2009-08-14 13:56:44 UTC (rev 7487)
+++ trunk/matplotlib/lib/matplotlib/backend_bases.py 2009-08-14 18:11:05 UTC (rev 7488)
@@ -409,12 +409,36 @@
return cbook.strip_math(s)
def start_rasterizing(self):
+ """
+ Used in MixedModeRenderer. Switch to the raster renderer.
+ """
pass
def stop_rasterizing(self):
+ """
+ Used in MixedModeRenderer. Switch back to the vector renderer
+ and draw the contents of the raster renderer as an image on
+ the vector renderer.
+ """
pass
+ def start_filter(self):
+ """
+ Used in AggRenderer. Switch to a temporary renderer for image
+ filtering effects.
+ """
+ pass
+ def stop_filter(self, filter_func):
+ """
+ Used in AggRenderer. Switch back to the original renderer.
+ The contents of the temporary renderer is processed with the
+ *filter_func* and is drawn on the original renderer as an
+ image.
+ """
+ pass
+
+
class GraphicsContextBase:
"""
An abstract base class that provides color, line styles, etc...
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_agg.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_agg.py 2009-08-14 13:56:44 UTC (rev 7487)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_agg.py 2009-08-14 18:11:05 UTC (rev 7488)
@@ -57,22 +57,33 @@
self.height = height
if __debug__: verbose.report('RendererAgg.__init__ width=%s, height=%s'%(width, height), 'debug-annoying')
self._renderer = _RendererAgg(int(width), int(height), dpi, debug=False)
+ self._filter_renderers = []
+
if __debug__: verbose.report('RendererAgg.__init__ _RendererAgg done',
'debug-annoying')
+
+ self._update_methods()
+ self.mathtext_parser = MathTextParser('Agg')
+
+ self.bbox = Bbox.from_bounds(0, 0, self.width, self.height)
+ if __debug__: verbose.report('RendererAgg.__init__ done',
+ 'debug-annoying')
+
+ def draw_markers(self, *kl, **kw):
+ # for filtering to work with rastrization, methods needs to be wrapped.
+ # maybe there is better way to do it.
+ return self._renderer.draw_markers(*kl, **kw)
+
+ def _update_methods(self):
#self.draw_path = self._renderer.draw_path # see below
- self.draw_markers = self._renderer.draw_markers
+ #self.draw_markers = self._renderer.draw_markers
self.draw_path_collection = self._renderer.draw_path_collection
self.draw_quad_mesh = self._renderer.draw_quad_mesh
self.draw_gouraud_triangle = self._renderer.draw_gouraud_triangle
self.draw_image = self._renderer.draw_image
self.copy_from_bbox = self._renderer.copy_from_bbox
self.tostring_rgba_minimized = self._renderer.tostring_rgba_minimized
- self.mathtext_parser = MathTextParser('Agg')
- self.bbox = Bbox.from_bounds(0, 0, self.width, self.height)
- if __debug__: verbose.report('RendererAgg.__init__ done',
- 'debug-annoying')
-
def draw_path(self, gc, path, transform, rgbFace=None):
"""
Draw the path
@@ -165,6 +176,7 @@
d /= 64.0
return w, h, d
+
def draw_tex(self, gc, x, y, s, prop, angle):
# todo, handle props, angle, origins
size = prop.get_size_in_points()
@@ -271,7 +283,58 @@
else:
self._renderer.restore_region(region)
+ def start_filter(self):
+ """
+ Start filtering. It simply create a new canvas (the old one is saved).
+ """
+ self._filter_renderers.append(self._renderer)
+ self._renderer = _RendererAgg(int(self.width), int(self.height),
+ self.dpi)
+ self._update_methods()
+ def stop_filter(self, post_processing):
+ """
+ Save the plot in the current canvas as a image and apply
+ the *post_processing* function.
+
+ def post_processing(image, dpi):
+ # ny, nx, depth = image.shape
+ # image (numpy array) has RGBA channels and has a depth of 4.
+ ...
+ # create a new_image (numpy array of 4 channels, size can be
+ # different). The resulting image may have offsets from
+ # lower-left corner of the original image
+ return new_image, offset_x, offset_y
+
+ The saved renderer is restored and the returned image from
+ post_processing is plotted (using draw_image) on it.
+ """
+
+ from matplotlib._image import fromarray
+
+ width, height = int(self.width), int(self.height)
+
+ buffer, bounds = self._renderer.tostring_rgba_minimized()
+
+ l, b, w, h = bounds
+
+
+ self._renderer = self._filter_renderers.pop()
+ self._update_methods()
+
+ if w > 0 and h > 0:
+ img = npy.fromstring(buffer, npy.uint8)
+ img, ox, oy = post_processing(img.reshape((h, w, 4)) / 255.,
+ self.dpi)
+ image = fromarray(img, 1)
+ image.flipud_out()
+
+ gc = self.new_gc()
+ self._renderer.draw_image(gc,
+ l+ox, height - b - h +oy,
+ image)
+
+
def new_figure_manager(num, *args, **kwargs):
"""
Create a new figure manager instance
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_mixed.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_mixed.py 2009-08-14 13:56:44 UTC (rev 7487)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_mixed.py 2009-08-14 18:11:05 UTC (rev 7488)
@@ -58,6 +58,7 @@
finalize flipy get_canvas_width_height get_image_magnification
get_texmanager get_text_width_height_descent new_gc open_group
option_image_nocomposite points_to_pixels strip_math
+ start_filter stop_filter
""".split()
def _set_current_renderer(self, renderer):
self._renderer = renderer
Modified: trunk/matplotlib/lib/matplotlib/colors.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/colors.py 2009-08-14 13:56:44 UTC (rev 7487)
+++ trunk/matplotlib/lib/matplotlib/colors.py 2009-08-14 18:11:05 UTC (rev 7488)
@@ -1021,6 +1021,19 @@
RGBA values are returned, which can then be used to
plot the shaded image with imshow.
"""
+
+ rgb0 = cmap((data-data.min())/(data.max()-data.min()))
+ rgb1 = self.shade_rgb(rgb0, elevation=data)
+ rgb0[:,:,0:3] = rgb1
+ return rgb0
+
+ def shade_rgb(self,rgb, elevation, fraction=1.):
+ """
+ Take the input RGB array (ny*nx*3) adjust their color values
+ to given the impression of a shaded relief map with a
+ specified light source using the elevation (ny*nx).
+ A new RGB array ((ny*nx*3)) is returned.
+ """
# imagine an artificial sun placed at infinity in
# some azimuth and elevation position illuminating our surface. The parts of
# the surface that slope toward the sun should brighten while those sides
@@ -1029,7 +1042,7 @@
az = self.azdeg*np.pi/180.0
alt = self.altdeg*np.pi/180.0
# gradient in x and y directions
- dx, dy = np.gradient(data)
+ dx, dy = np.gradient(elevation)
slope = 0.5*np.pi - np.arctan(np.hypot(dx, dy))
aspect = np.arctan2(dx, dy)
intensity = np.sin(alt)*np.sin(slope) + np.cos(alt)*np.cos(slope)*np.cos(-az -\
@@ -1037,9 +1050,9 @@
# rescale to interval -1,1
# +1 means maximum sun exposure and -1 means complete shade.
intensity = (intensity - intensity.min())/(intensity.max() - intensity.min())
- intensity = 2.*intensity - 1.
+ intensity = (2.*intensity - 1.)*fraction
# convert to rgb, then rgb to hsv
- rgb = cmap((data-data.min())/(data.max()-data.min()))
+ #rgb = cmap((data-data.min())/(data.max()-data.min()))
hsv = rgb_to_hsv(rgb[:,:,0:3])
# modify hsv values to simulate illumination.
hsv[:,:,1] = np.where(np.logical_and(np.abs(hsv[:,:,1])>1.e-10,intensity>0),\
@@ -1053,5 +1066,4 @@
hsv[:,:,1:] = np.where(hsv[:,:,1:]<0.,0,hsv[:,:,1:])
hsv[:,:,1:] = np.where(hsv[:,:,1:]>1.,1,hsv[:,:,1:])
# convert modified hsv back to rgb.
- rgb[:,:,0:3] = hsv_to_rgb(hsv)
- return rgb
+ return hsv_to_rgb(hsv)
Modified: trunk/matplotlib/lib/matplotlib/text.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/text.py 2009-08-14 13:56:44 UTC (rev 7487)
+++ trunk/matplotlib/lib/matplotlib/text.py 2009-08-14 18:11:05 UTC (rev 7488)
@@ -18,6 +18,8 @@
from matplotlib.transforms import Affine2D, Bbox
from matplotlib.lines import Line2D
+from matplotlib.artist import allow_rasterization
+
import matplotlib.nxutils as nxutils
def _process_text_args(override, fontdict=None, **kwargs):
@@ -501,6 +503,7 @@
self._bbox_patch.draw(renderer)
+ @allow_rasterization
def draw(self, renderer):
"""
Draws the :class:`Text` object to the given *renderer*.
@@ -1727,6 +1730,7 @@
self.arrow.set_clip_box(self.get_clip_box())
+ @allow_rasterization
def draw(self, renderer):
"""
Draw the :class:`Annotation` object to the given *renderer*.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|