|
From: <ef...@us...> - 2007-09-04 05:53:57
|
Revision: 3772
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3772&view=rev
Author: efiring
Date: 2007-09-03 22:53:56 -0700 (Mon, 03 Sep 2007)
Log Message:
-----------
Errorbar limit symbols patch by Manuel Metz
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/axes.py
trunk/matplotlib/lib/matplotlib/lines.py
Added Paths:
-----------
trunk/matplotlib/examples/errorbar_limits.py
Added: trunk/matplotlib/examples/errorbar_limits.py
===================================================================
--- trunk/matplotlib/examples/errorbar_limits.py (rev 0)
+++ trunk/matplotlib/examples/errorbar_limits.py 2007-09-04 05:53:56 UTC (rev 3772)
@@ -0,0 +1,40 @@
+'''
+Illustration of upper and lower limit symbols on errorbars
+'''
+
+from math import pi
+from numpy import array, arange, sin
+import pylab as P
+
+fig = P.figure()
+x = arange(10.0)
+y = sin(arange(10.0)/20.0*pi)
+
+P.errorbar(x,y,yerr=0.1,capsize=3)
+
+y = sin(arange(10.0)/20.0*pi) + 1
+P.errorbar(x,y,yerr=0.1, uplims=True)
+
+y = sin(arange(10.0)/20.0*pi) + 2
+upperlimits = array([1,0]*5)
+lowerlimits = array([0,1]*5)
+P.errorbar(x, y, yerr=0.1, uplims=upperlimits, lolims=lowerlimits)
+
+P.xlim(-1,10)
+
+fig = P.figure()
+x = arange(10.0)/10.0
+y = (x+0.1)**2
+
+P.errorbar(x, y, xerr=0.1, xlolims=True)
+y = (x+0.1)**3
+
+P.errorbar(x+0.6, y, xerr=0.1, xuplims=upperlimits, xlolims=lowerlimits)
+
+y = (x+0.1)**4
+P.errorbar(x+1.2, y, xerr=0.1, xuplims=True)
+
+P.xlim(-0.2,2.4)
+P.ylim(-0.1,1.3)
+
+P.show()
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2007-09-03 22:16:19 UTC (rev 3771)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2007-09-04 05:53:56 UTC (rev 3772)
@@ -3522,10 +3522,13 @@
def errorbar(self, x, y, yerr=None, xerr=None,
fmt='-', ecolor=None, capsize=3,
- barsabove=False, **kwargs):
+ barsabove=False, lolims=False, uplims=False,
+ xlolims=False, xuplims=False, **kwargs):
"""
ERRORBAR(x, y, yerr=None, xerr=None,
- fmt='b-', ecolor=None, capsize=3, barsabove=False)
+ fmt='b-', ecolor=None, capsize=3, barsabove=False,
+ lolims=False, uplims=False,
+ xlolims=False, xuplims=False)
Plot x versus y with error deltas in yerr and xerr.
Vertical errorbars are plotted if yerr is not None
@@ -3554,6 +3557,11 @@
barsabove, if True, will plot the errorbars above the plot symbols
- default is below
+ lolims, uplims, xlolims, xuplims: These arguments can be used
+ to indicate that a value gives only upper/lower limits. In
+ that case a caret symbol is used to indicate this. lims-arguments
+ may be of the same type as xerr and yerr.
+
kwargs are passed on to the plot command for the markers.
So you can add additional key=value pairs to control the
errorbar markers. For example, this code makes big red
@@ -3579,18 +3587,18 @@
if not self._hold: self.cla()
# make sure all the args are iterable arrays
- if not iterable(x): x = npy.asarray([x])
+ if not iterable(x): x = npy.array([x])
else: x = npy.asarray(x)
- if not iterable(y): y = npy.asarray([y])
+ if not iterable(y): y = npy.array([y])
else: y = npy.asarray(y)
if xerr is not None:
- if not iterable(xerr): xerr = npy.asarray([xerr])
+ if not iterable(xerr): xerr = npy.array([xerr])
else: xerr = npy.asarray(xerr)
if yerr is not None:
- if not iterable(yerr): yerr = npy.asarray([yerr])
+ if not iterable(yerr): yerr = npy.array([yerr])
else: yerr = npy.asarray(yerr)
l0 = None
@@ -3607,6 +3615,18 @@
if 'lw' in kwargs:
lines_kw['lw']=kwargs['lw']
+ if not iterable(lolims): lolims = npy.array([lolims]*len(x), bool)
+ else: lolims = npy.asarray(lolims, bool)
+
+ if not iterable(uplims): uplims = npy.array([uplims]*len(x), bool)
+ else: uplims = npy.asarray(uplims, bool)
+
+ if not iterable(xlolims): xlolims = npy.array([xlolims]*len(x), bool)
+ else: xlolims = npy.asarray(xlolims, bool)
+
+ if not iterable(xuplims): xuplims = npy.array([xuplims]*len(x), bool)
+ else: xuplims = npy.asarray(xuplims, bool)
+
if capsize > 0:
plot_kw = {
'ms':2*capsize,
@@ -3626,9 +3646,20 @@
barcols.append( self.hlines(y, left, right, **lines_kw ) )
if capsize > 0:
- caplines.extend( self.plot(left, y, 'k|', **plot_kw) )
- caplines.extend( self.plot(right, y, 'k|', **plot_kw) )
+ if xlolims.any():
+ caplines.extend( self.plot(left[xlolims], y[xlolims], ls='None', marker=mlines.CARETLEFT, **plot_kw) )
+ xlolims = ~xlolims
+ caplines.extend( self.plot(left[xlolims], y[xlolims], 'k|', **plot_kw) )
+ else:
+ caplines.extend( self.plot(left, y, 'k|', **plot_kw) )
+ if xuplims.any():
+ caplines.extend( self.plot(right[xuplims], y[xuplims], ls='None', marker=mlines.CARETRIGHT, **plot_kw) )
+ xuplims = ~xuplims
+ caplines.extend( self.plot(right[xuplims], y[xuplims], 'k|', **plot_kw) )
+ else:
+ caplines.extend( self.plot(right, y, 'k|', **plot_kw) )
+
if yerr is not None:
if len(yerr.shape) == 1:
lower = y-yerr
@@ -3639,9 +3670,21 @@
barcols.append( self.vlines(x, lower, upper, **lines_kw) )
if capsize > 0:
- caplines.extend( self.plot(x, lower, 'k_', **plot_kw) )
- caplines.extend( self.plot(x, upper, 'k_', **plot_kw) )
+ if lolims.any():
+ caplines.extend( self.plot(x[lolims], lower[lolims], ls='None', marker=mlines.CARETDOWN, **plot_kw) )
+ lolims = ~lolims
+ caplines.extend( self.plot(x[lolims], lower[lolims], 'k_', **plot_kw) )
+ else:
+ caplines.extend( self.plot(x, lower, 'k_', **plot_kw) )
+
+ if uplims.any():
+ caplines.extend( self.plot(x[uplims], upper[uplims], ls='None', marker=mlines.CARETUP, **plot_kw) )
+ uplims = ~uplims
+ caplines.extend( self.plot(x[uplims], upper[uplims], 'k_', **plot_kw) )
+ else:
+ caplines.extend( self.plot(x, upper, 'k_', **plot_kw) )
+
if not barsabove and fmt is not None:
l0, = self.plot(x,y,fmt,**kwargs)
Modified: trunk/matplotlib/lib/matplotlib/lines.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/lines.py 2007-09-03 22:16:19 UTC (rev 3771)
+++ trunk/matplotlib/lib/matplotlib/lines.py 2007-09-04 05:53:56 UTC (rev 3772)
@@ -21,7 +21,9 @@
from transforms import lbwh_to_bbox, LOG10
from matplotlib import rcParams
-TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN = range(4)
+# special-purpose marker identifiers:
+(TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN,
+ CARETLEFT, CARETRIGHT, CARETUP, CARETDOWN) = range(8)
def unmasked_index_ranges(mask, compressed = True):
'''
@@ -97,7 +99,7 @@
point_hits = (cx - x)**2 + (cy - y)**2 <= radius**2
#if any(point_hits): print "points",xr[candidates]
candidates = candidates & ~point_hits[:-1] & ~point_hits[1:]
-
+
# For those candidates which remain, determine how far they lie away
# from the line.
px,py = xr+u*dx,yr+u*dy
@@ -147,6 +149,10 @@
TICKRIGHT : '_draw_tickright',
TICKUP : '_draw_tickup',
TICKDOWN : '_draw_tickdown',
+ CARETLEFT : '_draw_caretleft',
+ CARETRIGHT : '_draw_caretright',
+ CARETUP : '_draw_caretup',
+ CARETDOWN : '_draw_caretdown',
'None' : '_draw_nothing',
' ' : '_draw_nothing',
'' : '_draw_nothing',
@@ -1201,6 +1207,62 @@
renderer.draw_line(gc, x, y, x-offset2, y+offset1)
renderer.draw_line(gc, x, y, x-offset2, y-offset1)
+ def _draw_caretdown(self, renderer, gc, xt, yt):
+ offset = 0.5*renderer.points_to_pixels(self._markersize)
+ offset1 = 1.5*offset
+ if self._newstyle:
+ path = agg.path_storage()
+ path.move_to(-offset, offset1)
+ path.line_to(0, 0)
+ path.line_to(+offset, offset1)
+ renderer.draw_markers(gc, path, None, xt, yt, self.get_transform())
+ else:
+ for (x,y) in zip(xt, yt):
+ renderer.draw_line(gc, x-offset, y+offset1, x, y)
+ renderer.draw_line(gc, x, y, x+offset, y+offset1)
+
+ def _draw_caretup(self, renderer, gc, xt, yt):
+ offset = 0.5*renderer.points_to_pixels(self._markersize)
+ offset1 = 1.5*offset
+ if self._newstyle:
+ path = agg.path_storage()
+ path.move_to(-offset, -offset1)
+ path.line_to(0, 0)
+ path.line_to(+offset, -offset1)
+ renderer.draw_markers(gc, path, None, xt, yt, self.get_transform())
+ else:
+ for (x,y) in zip(xt, yt):
+ renderer.draw_line(gc, x-offset, y-offset1, x, y)
+ renderer.draw_line(gc, x, y, x+offset, y-offset1)
+
+ def _draw_caretleft(self, renderer, gc, xt, yt):
+ offset = 0.5*renderer.points_to_pixels(self._markersize)
+ offset1 = 1.5*offset
+ if self._newstyle:
+ path = agg.path_storage()
+ path.move_to(offset1, -offset)
+ path.line_to(0, 0)
+ path.line_to(offset1, offset)
+ renderer.draw_markers(gc, path, None, xt, yt, self.get_transform())
+ else:
+ for (x,y) in zip(xt, yt):
+ renderer.draw_line(gc, x+offset1, y-offset, x, y)
+ renderer.draw_line(gc, x, y, x+offset1, y+offset)
+
+ def _draw_caretright(self, renderer, gc, xt, yt):
+ offset = 0.5*renderer.points_to_pixels(self._markersize)
+ offset1 = 1.5*offset
+ if self._newstyle:
+ path = agg.path_storage()
+ path.move_to(-offset1, -offset)
+ path.line_to(0, 0)
+ path.line_to(-offset1, offset)
+ renderer.draw_markers(gc, path, None, xt, yt, self.get_transform())
+ else:
+ for (x,y) in zip(xt, yt):
+ renderer.draw_line(gc, x-offset1, y-offset, x, y)
+ renderer.draw_line(gc, x, y, x-offset1, y+offset)
+
def _draw_x(self, renderer, gc, xt, yt):
offset = 0.5*renderer.points_to_pixels(self._markersize)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2007-09-04 05:58:49
|
Revision: 3773
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3773&view=rev
Author: efiring
Date: 2007-09-03 22:58:48 -0700 (Mon, 03 Sep 2007)
Log Message:
-----------
Update CHANGELOG and API_CHANGES for Manuel Metz's errorbar patch.
Modified Paths:
--------------
trunk/matplotlib/API_CHANGES
trunk/matplotlib/CHANGELOG
Modified: trunk/matplotlib/API_CHANGES
===================================================================
--- trunk/matplotlib/API_CHANGES 2007-09-04 05:53:56 UTC (rev 3772)
+++ trunk/matplotlib/API_CHANGES 2007-09-04 05:58:48 UTC (rev 3773)
@@ -1,3 +1,7 @@
+ The errorbar method and function now accept additional kwargs
+ so that upper and lower limits can be indicated by capping the
+ bar with a caret instead of a straight line segment.
+
The dviread.py file now has a parser for files like psfonts.map
and pdftex.map, to map TeX font names to external files.
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2007-09-04 05:53:56 UTC (rev 3772)
+++ trunk/matplotlib/CHANGELOG 2007-09-04 05:58:48 UTC (rev 3773)
@@ -1,3 +1,6 @@
+2007-09-03 Added ability of errorbar show limits via caret or
+ arrowhead ends on the bars; patch by Manual Metz. - EF
+
2007-09-03 Created type1font.py, added features to AFM and FT2Font
(see API_CHANGES), started work on embedding Type 1 fonts
in pdf files. - JKS
@@ -7,7 +10,7 @@
2007-08-16 Added a set_extent method to AxesImage, allow data extent
to be modified after initial call to imshow - DSD
-2007-08-14 Fixed a bug in pyqt4 subplots-adjust. Thanks to
+2007-08-14 Fixed a bug in pyqt4 subplots-adjust. Thanks to
Xavier Gnata for the report and suggested fix - DSD
2007-08-13 Use pickle to cache entire fontManager; change to using
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2007-09-04 14:52:18
|
Revision: 3774
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3774&view=rev
Author: jdh2358
Date: 2007-09-04 07:52:03 -0700 (Tue, 04 Sep 2007)
Log Message:
-----------
added manuels star poly patch
Modified Paths:
--------------
trunk/matplotlib/examples/scatter_star_poly.py
trunk/matplotlib/lib/matplotlib/axes.py
trunk/matplotlib/lib/matplotlib/collections.py
trunk/matplotlib/lib/matplotlib/mpl-data/matplotlibrc
trunk/matplotlib/lib/matplotlib/pylab.py
trunk/matplotlib/mpl1/mpl1.py
Modified: trunk/matplotlib/examples/scatter_star_poly.py
===================================================================
--- trunk/matplotlib/examples/scatter_star_poly.py 2007-09-04 05:58:48 UTC (rev 3773)
+++ trunk/matplotlib/examples/scatter_star_poly.py 2007-09-04 14:52:03 UTC (rev 3774)
@@ -3,19 +3,25 @@
x = pylab.nx.mlab.rand(10)
y = pylab.nx.mlab.rand(10)
-pylab.subplot(221)
+pylab.subplot(321)
pylab.scatter(x,y,s=80,marker=">")
-pylab.subplot(222)
+pylab.subplot(322)
pylab.scatter(x,y,s=80,marker=(5,0))
verts = zip([-1.,1.,1.],[-1.,-1.,1.])
-pylab.subplot(223)
+pylab.subplot(323)
pylab.scatter(x,y,s=80,marker=(verts,0))
# equivalent:
#pylab.scatter(x,y,s=80,marker=None, verts=verts)
-pylab.subplot(224)
+pylab.subplot(324)
pylab.scatter(x,y,s=80,marker=(5,1))
+pylab.subplot(325)
+pylab.scatter(x,y,s=80,marker='+')
+
+pylab.subplot(326)
+pylab.scatter(x,y,s=80,marker=(5,2), edgecolor='g')
+
pylab.show()
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2007-09-04 05:58:48 UTC (rev 3773)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2007-09-04 14:52:03 UTC (rev 3774)
@@ -3976,16 +3976,18 @@
if not self._hold: self.cla()
syms = { # a dict from symbol to (numsides, angle)
- 's' : (4, math.pi/4.0), # square
- 'o' : (20, 0), # circle
- '^' : (3,0), # triangle up
- '>' : (3,math.pi/2.0), # triangle right
- 'v' : (3,math.pi), # triangle down
- '<' : (3,3*math.pi/2.0), # triangle left
- 'd' : (4,0), # diamond
- 'p' : (5,0), # pentagram
- 'h' : (6,0), # hexagon
- '8' : (8,0), # octagon
+ 's' : (4,math.pi/4.0,0), # square
+ 'o' : (20,0,0), # circle
+ '^' : (3,0,0), # triangle up
+ '>' : (3,math.pi/2.0,0), # triangle right
+ 'v' : (3,math.pi,0), # triangle down
+ '<' : (3,3*math.pi/2.0,0), # triangle left
+ 'd' : (4,0,0), # diamond
+ 'p' : (5,0,0), # pentagram
+ 'h' : (6,0,0), # hexagon
+ '8' : (8,0,0), # octagon
+ '+' : (4,0,2), # plus
+ 'x' : (4,math.pi/4.0,2) # cross
}
self._process_unit_info(xdata=x, ydata=y, kwargs=kwargs)
@@ -4013,7 +4015,7 @@
else: edgecolors = 'None'
sym = None
- starlike = False
+ symstyle = 0
# to be API compatible
if marker is None and not (verts is None):
@@ -4025,7 +4027,7 @@
sym = syms.get(marker)
if sym is None and verts is None:
raise ValueError('Unknown marker symbol to scatter')
- numsides, rotation = syms[marker]
+ numsides, rotation, symstyle = syms[marker]
elif iterable(marker):
# accept marker to be:
@@ -4040,21 +4042,19 @@
# (numsides, style, [angle])
if len(marker)==2:
- numsides, rotation = marker[0], math.pi/4.
+ numsides, rotation = marker[0], 0.
elif len(marker)==3:
numsides, rotation = marker[0], marker[2]
sym = True
- if marker[1]==1:
- # starlike symbol, everthing else is interpreted
- # as solid symbol
- starlike = True
+ if marker[1] in (1,2):
+ symstyle = marker[1]
else:
verts = npy.asarray(marker[0])
if sym is not None:
- if not starlike:
+ if symstyle==0:
collection = mcoll.RegularPolyCollection(
self.figure.dpi,
@@ -4065,7 +4065,7 @@
offsets = zip(x,y),
transOffset = self.transData,
)
- else:
+ elif symstyle==1:
collection = mcoll.StarPolygonCollection(
self.figure.dpi,
numsides, rotation, scales,
@@ -4075,6 +4075,16 @@
offsets = zip(x,y),
transOffset = self.transData,
)
+ elif symstyle==2:
+ collection = mcoll.AsteriskPolygonCollection(
+ self.figure.dpi,
+ numsides, rotation, scales,
+ facecolors = colors,
+ edgecolors = edgecolors,
+ linewidths = linewidths,
+ offsets = zip(x,y),
+ transOffset = self.transData,
+ )
else:
# rescale verts
rescale = npy.sqrt(max(verts[:,0]**2+verts[:,1]**2))
Modified: trunk/matplotlib/lib/matplotlib/collections.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/collections.py 2007-09-04 05:58:48 UTC (rev 3773)
+++ trunk/matplotlib/lib/matplotlib/collections.py 2007-09-04 14:52:03 UTC (rev 3774)
@@ -568,9 +568,42 @@
ns2 = self.numsides*2
r = scale*npy.ones(ns2)
r[1::2] *= 0.5
- theta = (2.*math.pi/(ns2))*npy.arange(ns2) + self.rotation
+ theta = (math.pi/self.numsides)*npy.arange(ns2) + self.rotation
self._verts = zip( r*npy.sin(theta), r*npy.cos(theta) )
+class AsteriskPolygonCollection(RegularPolyCollection):
+ def __init__(self,
+ dpi,
+ numsides,
+ rotation = 0 ,
+ sizes = (1,),
+ **kwargs):
+ """
+ Draw a regular asterisk Polygone with numsides spikes.
+
+ * dpi is the figure dpi instance, and is required to do the
+ area scaling.
+
+ * numsides: the number of spikes of the polygon
+
+ * sizes gives the area of the circle circumscribing the
+ regular polygon in points^2
+
+ * rotation is the rotation of the polygon in radians
+
+ %(PatchCollection)s
+ """
+
+ RegularPolyCollection.__init__(self, dpi, numsides, rotation, sizes, **kwargs)
+ __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
+
+ def _update_verts(self):
+ scale = 1.0/math.sqrt(math.pi)
+ r = scale*npy.ones(self.numsides*2)
+ r[1::2] = 0
+ theta = (math.pi/self.numsides)*npy.arange(2*self.numsides) + self.rotation
+ self._verts = zip( r*npy.sin(theta), r*npy.cos(theta) )
+
class LineCollection(Collection, cm.ScalarMappable):
"""
All parameters must be sequences or scalars; if scalars, they will
Modified: trunk/matplotlib/lib/matplotlib/mpl-data/matplotlibrc
===================================================================
--- trunk/matplotlib/lib/matplotlib/mpl-data/matplotlibrc 2007-09-04 05:58:48 UTC (rev 3773)
+++ trunk/matplotlib/lib/matplotlib/mpl-data/matplotlibrc 2007-09-04 14:52:03 UTC (rev 3774)
@@ -26,7 +26,7 @@
#### CONFIGURATION BEGINS HERE
# the default backend; one of GTK GTKAgg GTKCairo FltkAgg QtAgg TkAgg
# Agg Cairo GD GDK Paint PS PDF SVG Template
-backend : WXAgg
+backend : TkAgg
numerix : numpy # numpy, Numeric or numarray
#maskedarray : False # True to use external maskedarray module
# instead of numpy.ma; this is a temporary
Modified: trunk/matplotlib/lib/matplotlib/pylab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/pylab.py 2007-09-04 05:58:48 UTC (rev 3773)
+++ trunk/matplotlib/lib/matplotlib/pylab.py 2007-09-04 14:52:03 UTC (rev 3774)
@@ -1464,8 +1464,8 @@
is either an int or a string. if it is an int, it indicates the
column number. If it is a string, it indicates the column header.
mpl will make column headers lower case, replace spaces with
- strings, and remove all illegal characters; so 'Adj Close*' will
- have name 'adj_close'
+ underscores, and remove all illegal characters; so 'Adj Close*'
+ will have name 'adj_close'
if len(cols)==1, only that column will be plotted on the y axis.
if len(cols)>1, the first element will be an identifier for data
@@ -1480,7 +1480,8 @@
names in both.
comments, skiprows, checkrows, and delimiter are all passed on to
- matplotlib.mlab.csv2rec to load the data into a record array
+ matplotlib.mlab.csv2rec to load the data into a record array. See
+ the help there fore more information.
kwargs are passed on to plotting functions
Modified: trunk/matplotlib/mpl1/mpl1.py
===================================================================
--- trunk/matplotlib/mpl1/mpl1.py 2007-09-04 05:58:48 UTC (rev 3773)
+++ trunk/matplotlib/mpl1/mpl1.py 2007-09-04 14:52:03 UTC (rev 3774)
@@ -12,7 +12,7 @@
sudo rm -rf /usr/local/lib/python2.5/site-packages/enthought*
sudo easy_install \
-f http://code.enthought.com/enstaller/eggs/source/unstable \
- "enthought.resource <3.0a" "enthought.traits < 3.0a"
+ "enthought.traits < 3.0a"
"""
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jo...@us...> - 2007-09-04 18:19:20
|
Revision: 3775
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3775&view=rev
Author: jouni
Date: 2007-09-04 11:19:16 -0700 (Tue, 04 Sep 2007)
Log Message:
-----------
More work on supporting Type 1 fonts in PDF,
still doesn't produce usable files.
Modified Paths:
--------------
trunk/matplotlib/API_CHANGES
trunk/matplotlib/lib/matplotlib/afm.py
trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py
trunk/matplotlib/lib/matplotlib/dviread.py
Modified: trunk/matplotlib/API_CHANGES
===================================================================
--- trunk/matplotlib/API_CHANGES 2007-09-04 14:52:03 UTC (rev 3774)
+++ trunk/matplotlib/API_CHANGES 2007-09-04 18:19:16 UTC (rev 3775)
@@ -15,7 +15,8 @@
to read an afm file in addition to a pfa/pfb file, to get metrics
and kerning information for a Type 1 font.
- The AFM class now supports querying CapHeight and stem widths.
+ The AFM class now supports querying CapHeight and stem widths. The
+ get_name_char method now has an isord kwarg like get_width_char.
Changed pcolor default to shading='flat'; but as noted now in the
docstring, it is preferable to simply use the edgecolor kwarg.
Modified: trunk/matplotlib/lib/matplotlib/afm.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/afm.py 2007-09-04 14:52:03 UTC (rev 3774)
+++ trunk/matplotlib/lib/matplotlib/afm.py 2007-09-04 18:19:16 UTC (rev 3775)
@@ -378,11 +378,12 @@
"""
return self.get_str_bbox_and_descent(s)[:4]
- def get_name_char(self, c):
+ def get_name_char(self, c, isord=False):
"""
Get the name of the character, ie, ';' is 'semicolon'
"""
- wx, name, bbox = self._metrics[ord(c)]
+ if not isord: c=ord(c)
+ wx, name, bbox = self._metrics[c]
return name
def get_width_char(self, c, isord=False):
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py 2007-09-04 14:52:03 UTC (rev 3774)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py 2007-09-04 18:19:16 UTC (rev 3775)
@@ -18,6 +18,7 @@
from math import ceil, cos, floor, pi, sin
from sets import Set
+import matplotlib
from matplotlib import __version__, rcParams, agg, get_data_path
from matplotlib._pylab_helpers import Gcf
from matplotlib.backend_bases import RendererBase, GraphicsContextBase,\
@@ -493,12 +494,16 @@
def embedType1(self, filename, fontinfo):
fh = open(filename, 'rb')
+ matplotlib.verbose.report(
+ 'Embedding Type 1 font ' + filename, 'debug')
try:
fontdata = fh.read()
finally:
fh.close()
fh = open(fontinfo.afmfile, 'rb')
+ matplotlib.verbose.report(
+ 'Reading metrics from ' + fontinfo.afmfile, 'debug')
try:
afmdata = AFM(fh)
finally:
@@ -519,9 +524,26 @@
differencesArray = [ Name(ch) for ch in
dviread.Encoding(fontinfo.encodingfile) ]
differencesArray = [ 0 ] + differencesArray
+ firstchar = 0
lastchar = len(differencesArray) - 2
+ widths = [ 100 for x in range(firstchar,lastchar+1) ] # XXX TODO
else:
- lastchar = 255 # ?
+ widths = [ None for i in range(256) ]
+ for ch in range(256):
+ try:
+ widths[ch] = afmdata.get_width_char(ch, isord=True)
+ except KeyError:
+ pass
+ not_None = (ch for ch in range(256)
+ if widths[ch] is not None)
+ firstchar = not_None.next()
+ lastchar = max(not_None)
+ widths = widths[firstchar:lastchar+1]
+
+ differencesArray = [ firstchar ]
+ for ch in range(firstchar, lastchar+1):
+ differencesArray.append(Name(
+ afmdata.get_name_char(ch, isord=True)))
fontdict = {
'Type': Name('Font'),
@@ -533,16 +555,15 @@
'FontDescriptor': fontdescObject,
}
- if fontinfo.encodingfile is not None:
- fontdict.update({
- 'Encoding': { 'Type': Name('Encoding'),
- 'Differences': differencesArray },
- })
+ fontdict.update({
+ 'Encoding': { 'Type': Name('Encoding'),
+ 'Differences': differencesArray },
+ })
flags = 0
if fixed_pitch: flags |= 1 << 0 # fixed width
if 0: flags |= 1 << 1 # TODO: serif
- if 0: flags |= 1 << 2 # TODO: symbolic
+ if 1: flags |= 1 << 2 # TODO: symbolic
else: flags |= 1 << 5 # non-symbolic
if italic_angle: flags |= 1 << 6 # italic
if 0: flags |= 1 << 16 # TODO: all caps
@@ -557,12 +578,16 @@
'ItalicAngle': italic_angle,
'Ascent': font.ascender,
'Descent': font.descender,
- 'CapHeight': afmdata.get_capheight(),
+ 'CapHeight': 1000, # default guess if missing from AFM file
'XHeight': afmdata.get_xheight(),
'FontFile': fontfileObject,
'FontFamily': Name(familyname),
#'FontWeight': a number where 400 = Regular, 700 = Bold
}
+ try:
+ descriptor['CapHeight'] = afmdata.get_capheight()
+ except KeyError:
+ pass
# StemV is obligatory in PDF font descriptors but optional in
# AFM files. The collection of AFM files in my TeX Live 2007
@@ -579,7 +604,7 @@
descriptor['StemH'] = StemH
self.writeObject(fontdictObject, fontdict)
- self.writeObject(widthsObject, [ 100 for i in range(256)]) # XXX TODO
+ self.writeObject(widthsObject, widths)
self.writeObject(fontdescObject, descriptor)
fontdata = type1font.Type1Font(filename)
@@ -591,6 +616,8 @@
self.currentstream.write(fontdata.data)
self.endStream()
+ return fontdictObject
+
def _get_xobject_symbol_name(self, filename, symbol_name):
return "%s-%s" % (
os.path.splitext(os.path.basename(filename))[0],
Modified: trunk/matplotlib/lib/matplotlib/dviread.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/dviread.py 2007-09-04 14:52:03 UTC (rev 3774)
+++ trunk/matplotlib/lib/matplotlib/dviread.py 2007-09-04 18:19:16 UTC (rev 3775)
@@ -35,6 +35,7 @@
opens the file; actually reading the file happens when
iterating through the pages of the file.
"""
+ matplotlib.verbose.report('Dvi: ' + filename, 'debug')
self.file = open(filename, 'rb')
self.dpi = dpi
self.fonts = {}
@@ -57,7 +58,7 @@
while True:
have_page = self._read()
if have_page:
- yield self.text, self.boxes
+ yield self._output()
else:
break
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2007-09-04 19:00:22
|
Revision: 3776
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3776&view=rev
Author: mdboom
Date: 2007-09-04 12:00:18 -0700 (Tue, 04 Sep 2007)
Log Message:
-----------
Add support for arbitrary angles of rotation on mathtext in Agg
backend. Uses agg to rotate the raster of the text.
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/backends/backend_agg.py
trunk/matplotlib/lib/matplotlib/backends/backend_ps.py
trunk/matplotlib/lib/matplotlib/mathtext.py
trunk/matplotlib/src/_backend_agg.cpp
trunk/matplotlib/src/ft2font.cpp
trunk/matplotlib/src/ft2font.h
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_agg.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_agg.py 2007-09-04 18:19:16 UTC (rev 3775)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_agg.py 2007-09-04 19:00:18 UTC (rev 3776)
@@ -174,17 +174,10 @@
'debug-annoying')
ox, oy, width, height, descent, font_image, used_characters = \
self.mathtext_parser.parse(s, self.dpi.get(), prop)
-
- if angle == 90:
- width, height = height, width
- ox, oy = oy, ox
- x = int(x) - width + ox
- y = int(y) - height + oy
- font_image.rotate()
- else:
- x = int(x) + ox
- y = int(y) - height + oy
- self._renderer.draw_text_image(font_image, x, y + 1, gc)
+
+ x = int(x) + ox
+ y = int(y) - oy
+ self._renderer.draw_text_image(font_image, x, y + 1, angle, gc)
if 0:
self._renderer.draw_rectangle(gc, None,
int(x),
@@ -205,12 +198,14 @@
if len(s) == 1 and ord(s) > 127:
font.load_char(ord(s), flags=LOAD_DEFAULT)
else:
- font.set_text(s, angle, flags=LOAD_DEFAULT)
+ font.set_text(s, 0, flags=LOAD_DEFAULT)
font.draw_glyphs_to_bitmap()
#print x, y, int(x), int(y)
- self._renderer.draw_text_image(font.get_image(), int(x), int(y) + 1, gc)
+ # We pass '0' for angle here, since is has already been rotated
+ # (in vector space) in the above call to font.set_text.
+ self._renderer.draw_text_image(font.get_image(), int(x), int(y) + 1, angle, gc)
def get_text_width_height_descent(self, s, prop, ismath, rgb=(0,0,0)):
@@ -229,7 +224,7 @@
Z = texmanager.get_rgba(s, size, self.dpi.get(), rgb)
m,n,tmp = Z.shape
# TODO: descent of TeX text (I am imitating backend_ps here -JKS)
- return n, m, m
+ return n, m, 0
if ismath:
ox, oy, width, height, descent, fonts, used_characters = \
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_ps.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_ps.py 2007-09-04 18:19:16 UTC (rev 3775)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_ps.py 2007-09-04 19:00:18 UTC (rev 3776)
@@ -275,10 +275,9 @@
l,b,r,t = texmanager.get_ps_bbox(s, fontsize)
w = (r-l)
h = (t-b)
- #print s, w, h
# TODO: We need a way to get a good baseline from
# text.usetex
- return w, h, h
+ return w, h, 0
if ismath:
width, height, descent, pswriter, used_characters = \
Modified: trunk/matplotlib/lib/matplotlib/mathtext.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mathtext.py 2007-09-04 18:19:16 UTC (rev 3775)
+++ trunk/matplotlib/lib/matplotlib/mathtext.py 2007-09-04 19:00:18 UTC (rev 3776)
@@ -541,7 +541,7 @@
self.font = font
self.charmap = font.get_charmap()
self.glyphmap = dict(
- [(glyphind, ccode) for ccode, glyphind in self.charmap.items()])
+ [(glyphind, ccode) for ccode, glyphind in self.charmap.iteritems()])
def __repr__(self):
return repr(self.font)
@@ -671,7 +671,7 @@
def __init__(self, *args, **kwargs):
TruetypeFonts.__init__(self, *args, **kwargs)
if not len(self.fontmap):
- for key, val in self._fontmap.items():
+ for key, val in self._fontmap.iteritems():
fullpath = os.path.join(self.basepath, val + ".ttf")
self.fontmap[key] = fullpath
self.fontmap[val] = fullpath
Modified: trunk/matplotlib/src/_backend_agg.cpp
===================================================================
--- trunk/matplotlib/src/_backend_agg.cpp 2007-09-04 18:19:16 UTC (rev 3775)
+++ trunk/matplotlib/src/_backend_agg.cpp 2007-09-04 19:00:18 UTC (rev 3776)
@@ -16,6 +16,9 @@
#include "agg_scanline_storage_aa.h"
#include "agg_scanline_storage_bin.h"
#include "agg_renderer_primitives.h"
+#include "agg_span_image_filter_gray.h"
+#include "agg_span_interpolator_linear.h"
+#include "agg_span_allocator.h"
#include "util/agg_color_conv_rgb8.h"
#include "ft2font.h"
@@ -2103,13 +2106,74 @@
}
+/**
+ * This is a custom span generator that converts spans in the
+ * 8-bit inverted greyscale font buffer to rgba that agg can use.
+ */
+template<
+ class ColorT,
+ class ChildGenerator>
+class font_to_rgba :
+ public agg::span_generator<ColorT,
+ agg::span_allocator<ColorT> >
+{
+public:
+ typedef ChildGenerator child_type;
+ typedef ColorT color_type;
+ typedef agg::span_allocator<color_type> allocator_type;
+ typedef agg::span_generator<
+ ColorT,
+ agg::span_allocator<ColorT> > base_type;
+private:
+ child_type* _gen;
+ allocator_type _alloc;
+ color_type _color;
+
+public:
+ font_to_rgba(child_type* gen, color_type color) :
+ base_type(_alloc),
+ _gen(gen),
+ _color(color) {
+ }
+ color_type* generate(int x, int y, unsigned len)
+ {
+ color_type* dst = base_type::allocator().span();
+
+ typename child_type::color_type* src = _gen->generate(x, y, len);
+
+ do {
+ *dst = _color;
+ dst->a = src->v;
+ ++src;
+ ++dst;
+ } while (--len);
+
+ return base_type::allocator().span();
+ }
+
+ void prepare(unsigned max_span_len)
+ {
+ _alloc.allocate(max_span_len);
+ _gen->prepare(max_span_len);
+ }
+
+};
+
Py::Object
RendererAgg::draw_text_image(const Py::Tuple& args) {
_VERBOSE("RendererAgg::draw_text");
+
+ typedef agg::span_interpolator_linear<> interpolator_type;
+ typedef agg::span_image_filter_gray<agg::gray8, interpolator_type>
+ image_span_gen_type;
+ typedef font_to_rgba<pixfmt::color_type, image_span_gen_type>
+ span_gen_type;
+ typedef agg::renderer_scanline_aa<renderer_base, span_gen_type>
+ renderer_type;
- args.verify_length(4);
+ args.verify_length(5);
FT2Image *image = static_cast<FT2Image*>(args[0].ptr());
if (!image->get_buffer())
@@ -2125,70 +2189,48 @@
return Py::Object();
}
- GCAgg gc = GCAgg(args[3], dpi);
+ double angle = Py::Float( args[3] );
+
+ GCAgg gc = GCAgg(args[4], dpi);
- set_clipbox_rasterizer( gc.cliprect);
-
-
- pixfmt::color_type p;
- p.r = int(255*gc.color.r);
- p.b = int(255*gc.color.b);
- p.g = int(255*gc.color.g);
- p.a = int(255*gc.color.a);
-
- //y = y-font->image.height;
- unsigned thisx, thisy;
-
- double l = 0;
- double b = 0;
- double r = width;
- double t = height;
- if (gc.cliprect!=NULL) {
- l = gc.cliprect[0] ;
- b = gc.cliprect[1] ;
- double w = gc.cliprect[2];
- double h = gc.cliprect[3];
- r = l+w;
- t = b+h;
- }
-
+ set_clipbox_rasterizer(gc.cliprect);
+
const unsigned char* const buffer = image->get_buffer();
+ agg::rendering_buffer srcbuf
+ ((agg::int8u*)buffer, image->get_width(),
+ image->get_height(), image->get_width());
+ agg::pixfmt_gray8 pixf_img(srcbuf);
- for (size_t i=0; i< image->get_width(); i++) {
- for (size_t j=0; j< image->get_height(); j++) {
- thisx = i+x+image->offsetx;
- thisy = j+y+image->offsety;
- if (thisx<l || thisx>=r) continue;
- if (thisy<height-t || thisy>=height-b) continue;
- pixFmt->blend_pixel
- (thisx, thisy, p, buffer[i + j*image->get_width()]);
- }
- }
+ agg::trans_affine mtx;
+ mtx *= agg::trans_affine_translation(0, -(int)image->get_height());
+ mtx *= agg::trans_affine_rotation(-angle * agg::pi / 180.0);
+ mtx *= agg::trans_affine_translation(x, y);
+
+ agg::path_storage rect;
+ rect.move_to(0, 0);
+ rect.line_to(image->get_width(), 0);
+ rect.line_to(image->get_width(), image->get_height());
+ rect.line_to(0, image->get_height());
+ rect.line_to(0, 0);
+ agg::conv_transform<agg::path_storage> rect2(rect, mtx);
+
+ agg::trans_affine inv_mtx(mtx);
+ inv_mtx.invert();
+
+ agg::image_filter_lut filter;
+ filter.calculate(agg::image_filter_spline36());
+ interpolator_type interpolator(inv_mtx);
+ agg::span_allocator<agg::gray8> gray_span_allocator;
+ image_span_gen_type image_span_generator(gray_span_allocator,
+ srcbuf, 0, interpolator, filter);
+ span_gen_type output_span_generator(&image_span_generator, gc.color);
+ renderer_type ri(*rendererBase, output_span_generator);
+ agg::rasterizer_scanline_aa<> rasterizer;
+ agg::scanline_p8 scanline;
+ rasterizer.add_path(rect2);
+ agg::render_scanlines(rasterizer, scanline, ri);
- /* bbox the text for debug purposes
-
- agg::path_storage path;
-
- path.move_to(x, y);
- path.line_to(x, y+font->image.height);
- path.line_to(x+font->image.width, y+font->image.height);
- path.line_to(x+font->image.width, y);
- path.close_polygon();
-
- agg::rgba edgecolor(1,0,0,1);
-
- //now fill the edge
- agg::conv_stroke<agg::path_storage> stroke(path);
- stroke.width(1.0);
- rendererAA->color(edgecolor);
- //self->theRasterizer->gamma(agg::gamma_power(gamma));
- theRasterizer->add_path(stroke);
- agg::render_scanlines(*theRasterizer, *slineP8, *rendererAA);
-
- */
-
return Py::Object();
-
}
Modified: trunk/matplotlib/src/ft2font.cpp
===================================================================
--- trunk/matplotlib/src/ft2font.cpp 2007-09-04 18:19:16 UTC (rev 3775)
+++ trunk/matplotlib/src/ft2font.cpp 2007-09-04 19:00:18 UTC (rev 3776)
@@ -43,8 +43,6 @@
FT_Library _ft2Library;
FT2Image::FT2Image() :
- offsetx(0), offsety(0),
- _bRotated(false),
_isDirty(true),
_buffer(NULL),
_width(0), _height(0),
@@ -54,8 +52,6 @@
}
FT2Image::FT2Image(unsigned long width, unsigned long height) :
- offsetx(0), offsety(0),
- _bRotated(false),
_isDirty(true),
_buffer(NULL),
_width(0), _height(0),
@@ -85,7 +81,6 @@
for (size_t n=0; n<numBytes; n++)
_buffer[n] = 0;
- _bRotated = false;
_isDirty = true;
}
@@ -113,10 +108,7 @@
_width = 0;
_height = 0;
- offsetx = 0;
- offsety = 0;
_isDirty = true;
- _bRotated = false;
delete [] _buffer;
_buffer = NULL;
if (_rgbCopy) {
@@ -142,58 +134,6 @@
return Py::Object();
}
-void FT2Image::rotate() {
- // If we have already rotated, just return.
- if (_bRotated)
- return;
-
- unsigned long width = _width;
- unsigned long height = _height;
-
- unsigned long newWidth = _height;
- unsigned long newHeight = _width;
-
- unsigned long numBytes = _width * _height;
-
- unsigned char * buffer = new unsigned char [numBytes];
-
- unsigned long i, j, k, offset, nhMinusOne;
-
- nhMinusOne = newHeight - 1;
-
- unsigned char * read_it = _buffer;
-
- for (i=0; i<height; i++) {
- offset = i*width;
- for (j=0; j<width; j++) {
- k = nhMinusOne - j;
- buffer[i + k*newWidth] = *(read_it++);
- }
- }
-
- delete [] _buffer;
- _buffer = buffer;
- _width = newWidth;
- _height = newHeight;
- _bRotated = true;
- _isDirty = true;
-}
-char FT2Image::rotate__doc__[] =
-"rotate()\n"
-"\n"
-"Rotates the image 90 degrees.\n"
-;
-Py::Object
-FT2Image::py_rotate(const Py::Tuple & args) {
- _VERBOSE("FT2Image::rotate");
-
- args.verify_length(0);
-
- rotate();
-
- return Py::Object();
-}
-
void
FT2Image::draw_bitmap( FT_Bitmap* bitmap,
FT_Int x,
@@ -404,17 +344,11 @@
unsigned char *src_end = src + (_width * _height);
unsigned char *dst = _rgbaCopy->_buffer;
- // This pre-multiplies the alpha, which apparently shouldn't
- // be necessary for wxGTK, but it sure as heck seems to be.
- unsigned int c;
- unsigned int tmp;
while (src != src_end) {
- c = *src++;
- tmp = ((255 - c) * c) >> 8;
- *dst++ = tmp;
- *dst++ = tmp;
- *dst++ = tmp;
- *dst++ = c;
+ *dst++ = 0;
+ *dst++ = 0;
+ *dst++ = 0;
+ *dst++ = *src++;
}
}
@@ -1266,12 +1200,6 @@
image->resize(width, height);
}
- image->offsetx = (int)(string_bbox.xMin / 64.0);
- if (angle==0)
- image->offsety = -image->get_height();
- else
- image->offsety = (int)(-string_bbox.yMax/64.0);
-
for ( size_t n = 0; n < glyphs.size(); n++ )
{
FT_BBox bbox;
@@ -1840,8 +1768,6 @@
FT2Image::clear__doc__);
add_varargs_method("resize", &FT2Image::py_resize,
FT2Image::resize__doc__);
- add_varargs_method("rotate", &FT2Image::py_rotate,
- FT2Image::rotate__doc__);
add_varargs_method("write_bitmap", &FT2Image::py_write_bitmap,
FT2Image::write_bitmap__doc__);
add_varargs_method("draw_rect", &FT2Image::py_draw_rect,
Modified: trunk/matplotlib/src/ft2font.h
===================================================================
--- trunk/matplotlib/src/ft2font.h 2007-09-04 18:19:16 UTC (rev 3775)
+++ trunk/matplotlib/src/ft2font.h 2007-09-04 19:00:18 UTC (rev 3776)
@@ -30,7 +30,6 @@
void resize(unsigned long width, unsigned long height);
void clear();
- void rotate();
void draw_bitmap(FT_Bitmap* bitmap, FT_Int x, FT_Int y);
void write_bitmap(const char* filename) const;
void draw_rect(unsigned long x0, unsigned long y0,
@@ -46,8 +45,6 @@
Py::Object py_clear(const Py::Tuple & args);
static char resize__doc__ [];
Py::Object py_resize(const Py::Tuple & args);
- static char rotate__doc__ [];
- Py::Object py_rotate(const Py::Tuple & args);
static char write_bitmap__doc__ [];
Py::Object py_write_bitmap(const Py::Tuple & args);
static char draw_rect__doc__ [];
@@ -64,11 +61,7 @@
Py::Object py_get_width(const Py::Tuple & args);
Py::Object py_get_height(const Py::Tuple & args);
- unsigned long offsetx;
- unsigned long offsety;
-
private:
- bool _bRotated;
bool _isDirty;
unsigned char *_buffer;
unsigned long _width;
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jo...@us...> - 2007-09-04 20:27:39
|
Revision: 3779
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3779&view=rev
Author: jouni
Date: 2007-09-04 13:27:36 -0700 (Tue, 04 Sep 2007)
Log Message:
-----------
More work on supporting Type 1 fonts in PDF. Sort of works now.
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py
trunk/matplotlib/lib/matplotlib/dviread.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2007-09-04 19:52:23 UTC (rev 3778)
+++ trunk/matplotlib/CHANGELOG 2007-09-04 20:27:36 UTC (rev 3779)
@@ -1,3 +1,7 @@
+2007-09-04 Embedding Type 1 fonts in PDF, and thus usetex support
+ via dviread, sort of works. To test, enable it by
+ renaming _draw_tex to draw_tex. - JKS
+
2007-09-03 Added ability of errorbar show limits via caret or
arrowhead ends on the bars; patch by Manual Metz. - EF
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py 2007-09-04 19:52:23 UTC (rev 3778)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py 2007-09-04 20:27:36 UTC (rev 3779)
@@ -581,7 +581,7 @@
'CapHeight': 1000, # default guess if missing from AFM file
'XHeight': afmdata.get_xheight(),
'FontFile': fontfileObject,
- 'FontFamily': Name(familyname),
+ 'FontFamily': familyname,
#'FontWeight': a number where 400 = Regular, 700 = Bold
}
try:
@@ -1422,7 +1422,7 @@
self.file.output(Op.grestore)
def _draw_tex(self, gc, x, y, s, prop, angle):
- # Rename to draw_tex to enable, but it doesn't work at the moment
+ # Rename to draw_tex to enable
texmanager = self.get_texmanager()
fontsize = prop.get_size_in_points()
@@ -1606,6 +1606,19 @@
return draw_text_woven(chunks)
def get_text_width_height_descent(self, s, prop, ismath):
+ if rcParams['text.usetex']:
+ texmanager = self.get_texmanager()
+ fontsize = prop.get_size_in_points()
+ dvifile = texmanager.make_dvi(s, fontsize)
+ dvi = dviread.Dvi(dvifile, 72)
+ text, boxes = iter(dvi).next()
+ # TODO: better bounding box -- this is not quite right:
+ l = min(p[0] for p in text+boxes)
+ r = max(p[0] for p in text+boxes) + fontsize
+ b = min(p[1] for p in text+boxes)
+ t = max(p[1] for p in text+boxes) + fontsize
+ # (not to even mention finding the baseline)
+ return r-l, t-b, t-b
if ismath:
w, h, d, glyphs, rects, used_characters = \
self.mathtext_parser.parse(s, 72, prop)
Modified: trunk/matplotlib/lib/matplotlib/dviread.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/dviread.py 2007-09-04 19:52:23 UTC (rev 3778)
+++ trunk/matplotlib/lib/matplotlib/dviread.py 2007-09-04 20:27:36 UTC (rev 3779)
@@ -15,6 +15,8 @@
...
"""
+# TODO: support for TeX virtual fonts (*.vf) which are a dvi-like format
+
import matplotlib
import matplotlib.cbook as mpl_cbook
import os
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ds...@us...> - 2007-09-05 13:28:38
|
Revision: 3782
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3782&view=rev
Author: dsdale
Date: 2007-09-05 06:28:37 -0700 (Wed, 05 Sep 2007)
Log Message:
-----------
fixed qt version reporting in setupext.py
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/setupext.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2007-09-05 11:51:57 UTC (rev 3781)
+++ trunk/matplotlib/CHANGELOG 2007-09-05 13:28:37 UTC (rev 3782)
@@ -1,3 +1,5 @@
+2007-09-05 Fixed Qt version reporting in setupext.py - DSD
+
2007-09-04 Embedding Type 1 fonts in PDF, and thus usetex support
via dviread, sort of works. To test, enable it by
renaming _draw_tex to draw_tex. - JKS
Modified: trunk/matplotlib/setupext.py
===================================================================
--- trunk/matplotlib/setupext.py 2007-09-05 11:51:57 UTC (rev 3781)
+++ trunk/matplotlib/setupext.py 2007-09-05 13:28:37 UTC (rev 3782)
@@ -278,6 +278,14 @@
ret = os.popen(s).read().strip()
return ret
+def convert_qt_version(version):
+ version = '%x'%version
+ temp = []
+ while len(version) > 0:
+ version, chunk = version[:-2], version[-2:]
+ temp.insert(0, str(int(chunk, 16)))
+ return '.'.join(temp)
+
def check_for_qt():
try:
import pyqtconfig
@@ -286,20 +294,20 @@
return False
else:
print_status("Qt", "Qt: %s, pyqt: %s" %
- (pyqtconfig.Configuration().pyqt_version_str,
- pyqtconfig.Configuration().qt_version))
+ (convert_qt_version(pyqtconfig.Configuration().qt_version),
+ pyqtconfig.Configuration().pyqt_version_str))
return True
def check_for_qt4():
try:
- import PyQt4.pyqtconfig
+ from PyQt4 import pyqtconfig
except ImportError:
print_status("Qt4", "no")
return False
else:
print_status("Qt4", "Qt: %s, pyqt: %s" %
- (PyQt4.pyqtconfig.Configuration().pyqt_version_str,
- PyQt4.pyqtconfig.Configuration().qt_version))
+ (convert_qt_version(pyqtconfig.Configuration().qt_version),
+ pyqtconfig.Configuration().pyqt_version_str))
return True
def check_for_cairo():
@@ -455,14 +463,14 @@
if not os.environ.has_key('PKG_CONFIG_PATH'):
# If Gtk+ is installed, pkg-config is required to be installed
os.environ['PKG_CONFIG_PATH'] = 'C:\GTK\lib\pkgconfig'
-
- pygtkIncludes = getoutput('pkg-config --cflags-only-I pygtk-2.0').split()
- gtkIncludes = getoutput('pkg-config --cflags-only-I gtk+-2.0').split()
- includes = pygtkIncludes + gtkIncludes
- module.include_dirs.extend([include[2:] for include in includes])
-
- pygtkLinker = getoutput('pkg-config --libs pygtk-2.0').split()
- gtkLinker = getoutput('pkg-config --libs gtk+-2.0').split()
+
+ pygtkIncludes = getoutput('pkg-config --cflags-only-I pygtk-2.0').split()
+ gtkIncludes = getoutput('pkg-config --cflags-only-I gtk+-2.0').split()
+ includes = pygtkIncludes + gtkIncludes
+ module.include_dirs.extend([include[2:] for include in includes])
+
+ pygtkLinker = getoutput('pkg-config --libs pygtk-2.0').split()
+ gtkLinker = getoutput('pkg-config --libs gtk+-2.0').split()
linkerFlags = pygtkLinker + gtkLinker
module.libraries.extend(
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2007-09-06 18:50:14
|
Revision: 3798
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3798&view=rev
Author: mdboom
Date: 2007-09-06 11:50:08 -0700 (Thu, 06 Sep 2007)
Log Message:
-----------
Refactoring of FigureCanvas*.print_figure so that each backend does
not have to track all other possible filetypes. This should make it
easier to add new filetype backends without updating lots of places.
All GUI backends have the same base set of filetypes they support,
defined in FigureCanvasBase. Non-GUI backends, for the most part will
still only write to their own file format (and not do any
switch_backend magic.) All GUI backends (where possible) now generate
a list of file patterns for their file chooser dialogs, rather than
having hard-coded lists.
See FILETYPES for matrix of filetypes supported by each backend.
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/backend_bases.py
trunk/matplotlib/lib/matplotlib/backends/backend_agg.py
trunk/matplotlib/lib/matplotlib/backends/backend_cairo.py
trunk/matplotlib/lib/matplotlib/backends/backend_emf.py
trunk/matplotlib/lib/matplotlib/backends/backend_fltkagg.py
trunk/matplotlib/lib/matplotlib/backends/backend_gd.py
trunk/matplotlib/lib/matplotlib/backends/backend_gdk.py
trunk/matplotlib/lib/matplotlib/backends/backend_gtk.py
trunk/matplotlib/lib/matplotlib/backends/backend_gtkagg.py
trunk/matplotlib/lib/matplotlib/backends/backend_gtkcairo.py
trunk/matplotlib/lib/matplotlib/backends/backend_paint.py
trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py
trunk/matplotlib/lib/matplotlib/backends/backend_ps.py
trunk/matplotlib/lib/matplotlib/backends/backend_qt.py
trunk/matplotlib/lib/matplotlib/backends/backend_qt4.py
trunk/matplotlib/lib/matplotlib/backends/backend_qt4agg.py
trunk/matplotlib/lib/matplotlib/backends/backend_qtagg.py
trunk/matplotlib/lib/matplotlib/backends/backend_svg.py
trunk/matplotlib/lib/matplotlib/backends/backend_template.py
trunk/matplotlib/lib/matplotlib/backends/backend_tkagg.py
trunk/matplotlib/lib/matplotlib/backends/backend_wx.py
trunk/matplotlib/lib/matplotlib/backends/backend_wxagg.py
trunk/matplotlib/lib/matplotlib/figure.py
Added Paths:
-----------
trunk/matplotlib/FILETYPES
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2007-09-06 14:46:49 UTC (rev 3797)
+++ trunk/matplotlib/CHANGELOG 2007-09-06 18:50:08 UTC (rev 3798)
@@ -1,3 +1,11 @@
+2007-09-06 Refactored image saving code so that all GUI backends can
+ save most image types. See FILETYPES for a matrix of
+ backends and their supported file types.
+ Backend canvases should no longer write their own print_figure()
+ method -- instead they should write a print_xxx method for
+ each filetype they can output and add an entry to their
+ class-scoped filetypes dictionary. - MGD
+
2007-09-05 Fixed Qt version reporting in setupext.py - DSD
2007-09-04 Embedding Type 1 fonts in PDF, and thus usetex support
Added: trunk/matplotlib/FILETYPES
===================================================================
--- trunk/matplotlib/FILETYPES (rev 0)
+++ trunk/matplotlib/FILETYPES 2007-09-06 18:50:08 UTC (rev 3798)
@@ -0,0 +1,60 @@
+This is a table of the output formats supported by each backend.
+
+You may need to expand your terminal window to read this table
+correctly. It may be edited with emacs' table mode.
+
+Each cell specifies the backend that actually handles the file format.
+A cell with a '+' in it denotes the rasterizer and the file writing
+infrastructure as separate pieces.
+
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
+| |bmp |emf |eps |jpeg |pcx |pdf |png |ps |raw |svg |tiff |xpm |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
+|Agg | |emf |ps | | |pdf |agg * |ps |agg |svg | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
+|Cairo | |emf |ps | | |cairo |cairo |cairo|agg |cairo| | |
+|[1] | | |[2] | | | |* | | | | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
+|CocoaAgg| |emf |ps | | |pdf |agg * |ps |agg |svg | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
+|Emf | |emf *| | | | | | | | | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
+|FltkAgg | |emf |ps | | |pdf |agg * |ps |agg |svg | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
+|Gd | | | | | | |gd * | | | | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
+|Gtk | |emf |ps |gdk + | |pdf |gdk + |ps |agg |svg | | |
+|(gdk) | | | |pixbuf | | |pixbuf| | | | | |
+| | | | | | | |* | | | | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
+|GtkAgg | |emf |ps |agg + | |pdf |agg + |ps |agg |svg | | |
+| | | | |pixbuf | | |pixbuf| | | | | |
+| | | | | | | |* | | | | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
+|GtkCairo| |emf |ps |cairo +| |cairo |cairo |cairo|agg |svg | | |
+| | | | |pixbuf | | |* | | | | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
+|Paint | | | | | | |libart| | | | | |
+|(libart)| | | | | | |* | | | | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
+|Pdf | | | | | |pdf * | | | | | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
+|Ps | | |ps | | | | |ps * | | | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
+|QtAgg | |emf |ps | | |pdf |agg * |ps |agg |svg | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
+|Qt4Agg | |emf |ps | | |pdf |agg * |ps |agg |svg | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
+|Svg | | | | | | | | | |svg *| | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
+|TkAgg | |emf |ps | | |pdf |agg * |ps |agg |svg | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
+|Wx |wx + |emf |ps |wx + wx|wx + |pdf |wx + |ps |agg |svg |wx + |wx + |
+| |wx | | | |wx | |wx * | | | |wx |wx |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
+|WxAgg | |emf |ps | | |pdf |agg * |ps |agg |svg | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
+
+* Default filetype for the backend
+[1] Cairo's default filetype is specified in rcParams['cairo.format']
+[2] Cairo does not produce .eps files, and instead falls back on backend_ps.py
\ No newline at end of file
Modified: trunk/matplotlib/lib/matplotlib/backend_bases.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backend_bases.py 2007-09-06 14:46:49 UTC (rev 3797)
+++ trunk/matplotlib/lib/matplotlib/backend_bases.py 2007-09-06 18:50:08 UTC (rev 3798)
@@ -4,7 +4,7 @@
"""
from __future__ import division
-import sys, warnings
+import os, sys, warnings
import numpy as npy
import matplotlib.numerix.npyma as ma
@@ -12,6 +12,7 @@
import matplotlib.colors as colors
import matplotlib.transforms as transforms
import matplotlib.widgets as widgets
+from matplotlib import rcParams
class RendererBase:
"""An abstract base class to handle drawing/rendering operations
@@ -1071,8 +1072,70 @@
(depending on the backend), truncated to integers"""
return int(self.figure.bbox.width()), int(self.figure.bbox.height())
+ filetypes = {
+ 'emf': 'Enhanced Metafile',
+ 'eps': 'Encapsulated Postscript',
+ 'pdf': 'Portable Document Format',
+ 'png': 'Portable Network Graphics',
+ 'ps' : 'Postscript',
+ 'raw': 'Raw RGBA bitmap',
+ 'rgb': 'Raw RGBA bitmap',
+ 'svg': 'Scalable Vector Graphics',
+ }
+
+ # All of these print_* functions do a lazy import because
+ # a) otherwise we'd have cyclical imports, since all of these
+ # classes inherit from FigureCanvasBase
+ # b) so we don't import a bunch of stuff the user may never use
+
+ def print_emf(self, *args, **kwargs):
+ from backends.backend_emf import FigureCanvasEMF # lazy import
+ emf = self.switch_backends(FigureCanvasEMF)
+ return emf.print_emf(*args, **kwargs)
+
+ def print_eps(self, *args, **kwargs):
+ from backends.backend_ps import FigureCanvasPS # lazy import
+ ps = self.switch_backends(FigureCanvasPS)
+ return ps.print_eps(*args, **kwargs)
+
+ def print_pdf(self, *args, **kwargs):
+ from backends.backend_pdf import FigureCanvasPdf # lazy import
+ pdf = self.switch_backends(FigureCanvasPdf)
+ return pdf.print_pdf(*args, **kwargs)
+
+ def print_png(self, *args, **kwargs):
+ from backends.backend_agg import FigureCanvasAgg # lazy import
+ agg = self.switch_backends(FigureCanvasAgg)
+ return agg.print_png(*args, **kwargs)
+
+ def print_ps(self, *args, **kwargs):
+ from backends.backend_ps import FigureCanvasPS # lazy import
+ ps = self.switch_backends(FigureCanvasPS)
+ return ps.print_ps(*args, **kwargs)
+
+ def print_raw(self, *args, **kwargs):
+ from backends.backend_agg import FigureCanvasAgg # lazy import
+ agg = self.switch_backends(FigureCanvasAgg)
+ return agg.print_raw(*args, **kwargs)
+ print_bmp = print_rgb = print_raw
+
+ def print_svg(self, *args, **kwargs):
+ from backends.backend_svg import FigureCanvasSVG # lazy import
+ svg = self.switch_backends(FigureCanvasSVG)
+ return svg.print_svg(*args, **kwargs)
+
+ def get_supported_filetypes(self):
+ return self.filetypes
+
+ def get_supported_filetypes_grouped(self):
+ groupings = {}
+ for ext, name in self.filetypes.items():
+ groupings.setdefault(name, []).append(ext)
+ groupings[name].sort()
+ return groupings
+
def print_figure(self, filename, dpi=None, facecolor='w', edgecolor='w',
- orientation='portrait', **kwargs):
+ orientation='portrait', format=None, **kwargs):
"""
Render the figure to hardcopy. Set the figure patch face and edge
colors. This is useful because some of the GUIs have a gray figure
@@ -1085,9 +1148,57 @@
facecolor - the facecolor of the figure
edgecolor - the edgecolor of the figure
orientation - 'landscape' | 'portrait' (not supported on all backends)
+ format - when set, forcibly set the file format to save to
"""
- pass
+ if format is None:
+ if cbook.is_string_like(filename):
+ format = os.path.splitext(filename)[1][1:]
+ if format is None or format == '':
+ format = self.get_default_filetype()
+ if cbook.is_string_like(filename):
+ filename = filename.rstrip('.') + '.' + format
+ format = format.lower()
+ method_name = 'print_%s' % format
+ if (format not in self.filetypes or
+ not hasattr(self, method_name)):
+ formats = self.filetypes.keys()
+ formats.sort()
+ raise ValueError(
+ 'Format "%s" is not supported.\n'
+ 'Supported formats: '
+ '%s.' % (format, ', '.join(formats)))
+
+ if dpi is None:
+ dpi = rcParams['savefig.dpi']
+
+ origDPI = self.figure.dpi.get()
+ origfacecolor = self.figure.get_facecolor()
+ origedgecolor = self.figure.get_edgecolor()
+
+ self.figure.dpi.set(dpi)
+ self.figure.set_facecolor(facecolor)
+ self.figure.set_edgecolor(edgecolor)
+
+ try:
+ result = getattr(self, method_name)(
+ filename,
+ dpi=dpi,
+ facecolor=facecolor,
+ edgecolor=edgecolor,
+ orientation=orientation,
+ **kwargs)
+ finally:
+ self.figure.dpi.set(origDPI)
+ self.figure.set_facecolor(origfacecolor)
+ self.figure.set_edgecolor(origedgecolor)
+ self.figure.set_canvas(self)
+
+ return result
+
+ def get_default_filetype(self):
+ raise NotImplementedError
+
def switch_backends(self, FigureCanvasClass):
"""
instantiate an instance of FigureCanvasClass
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_agg.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_agg.py 2007-09-06 14:46:49 UTC (rev 3797)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_agg.py 2007-09-06 18:50:08 UTC (rev 3798)
@@ -405,95 +405,15 @@
'debug-annoying')
return self.renderer.buffer_rgba(x,y)
- def print_figure(self, filename, dpi=None, facecolor='w', edgecolor='w',
- orientation='portrait', **kwargs):
- """
- Render the figure to hardcopy. Set the figure patch face and
- edge colors. This is useful because some of the GUIs have a
- gray figure face color background and you'll probably want to
- override this on hardcopy
+ def get_default_filetype(self):
+ return 'png'
- If the extension matches PNG, write a PNG file
-
- If the extension matches BMP or RAW, write an RGBA bitmap file
-
- If filename is a fileobject, write png to file object (thus
- you can, for example, write the png to stdout
- """
- if __debug__: verbose.report('FigureCanvasAgg.print_figure',
- 'debug-annoying')
- if dpi is None: dpi = matplotlib.rcParams['savefig.dpi']
-
- # store the orig figure dpi, color and size information so we
- # can restore them later. For image creation alone, this is
- # not important since after the print the figure is done. But
- # backend_agg may be used as a renderer for a GUI figure, and
- # restoring figure props will be important in that case.
- # TODO: move most of this functionality into backend_bases
-
- origDPI = self.figure.dpi.get()
- origfacecolor = self.figure.get_facecolor()
- origedgecolor = self.figure.get_edgecolor()
-
- self.figure.dpi.set(dpi)
- self.figure.set_facecolor(facecolor)
- self.figure.set_edgecolor(edgecolor)
-
- # render the printed figure
+ def print_raw(self, filename, *args, **kwargs):
self.draw()
-
- printfunc = None
- if not is_string_like(filename):
- # assume png and write to fileobject
- self.renderer._renderer.write_png(filename)
- #pass
- else:
- # take a look at the extension and choose the print handler
- basename, ext = os.path.splitext(filename)
- if not len(ext):
- ext = '.png'
- filename += ext
-
- ext = ext.lower()
- if (ext.find('rgb')>=0 or
- ext.find('raw')>=0 or
- ext.find('bmp')>=0 ):
- # agg doesn't handle unicode yet
- self.renderer._renderer.write_rgba(str(filename))
- elif ext.find('png')>=0:
- # agg doesn't handle unicode yet
- self.renderer._renderer.write_png(str(filename))
- #pass
- elif ext.find('svg')>=0:
- from backend_svg import FigureCanvasSVG
- svg = self.switch_backends(FigureCanvasSVG)
- printfunc = svg.print_figure
- elif ext.find('ps')>=0 or ext.find('ep')>=0:
- from backend_ps import FigureCanvasPS # lazy import
- ps = self.switch_backends(FigureCanvasPS)
- printfunc = ps.print_figure
- elif ext.find('pdf')>=0:
- from backend_pdf import FigureCanvasPdf
- pdf = self.switch_backends(FigureCanvasPdf)
- printfunc = pdf.print_figure
- else:
- raise IOError('Do not know know to handle extension *%s' % ext)
-
- if printfunc is not None:
- try:
- printfunc(filename, dpi, facecolor, edgecolor, orientation, **kwargs)
- except:
- # restore the original figure properties
- self.figure.dpi.set(origDPI)
- self.figure.set_facecolor(origfacecolor)
- self.figure.set_edgecolor(origedgecolor)
- self.figure.set_canvas(self)
- raise
-
- # restore the original figure properties
- self.figure.dpi.set(origDPI)
- self.figure.set_facecolor(origfacecolor)
- self.figure.set_edgecolor(origedgecolor)
- self.figure.set_canvas(self)
-
-
+ self.get_renderer()._renderer.write_rgba(str(filename))
+ print_rgba = print_raw
+
+ def print_png(self, filename, *args, **kwargs):
+ self.draw()
+ self.get_renderer()._renderer.write_png(str(filename))
+
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_cairo.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_cairo.py 2007-09-06 14:46:49 UTC (rev 3797)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_cairo.py 2007-09-06 18:50:08 UTC (rev 3798)
@@ -488,41 +488,7 @@
class FigureCanvasCairo (FigureCanvasBase):
- def print_figure(self, fo, dpi=150, facecolor='w', edgecolor='w',
- orientation='portrait', format=None, **kwargs):
- if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name())
- # settings for printing
- self.figure.dpi.set(dpi)
- self.figure.set_facecolor(facecolor)
- self.figure.set_edgecolor(edgecolor)
-
- if format is None and isinstance (fo, basestring):
- # get format from filename extension
- format = os.path.splitext(fo)[1][1:]
- if format == '':
- format = rcParams['cairo.format']
- fo = '%s.%s' % (fo, format)
-
- if format is not None:
- format = format.lower()
-
- if format == 'png':
- self._save_png (fo)
- elif format in ('pdf', 'ps', 'svg'):
- self._save (fo, format, orientation, **kwargs)
- elif format == 'eps': # backend_ps for eps
- warnings.warn('eps format is printed by ps backend, not cairo')
- from backend_ps import FigureCanvasPS as FigureCanvas
- fc = FigureCanvas(self.figure)
- fc.print_figure (fo, dpi, facecolor, edgecolor,
- orientation, **kwargs)
- else:
- warnings.warn('Format "%s" is not supported.\n'
- 'Supported formats: '
- '%s.' % (format, ', '.join(IMAGE_FORMAT)))
-
-
- def _save_png (self, fobj):
+ def print_png(self, fobj, *args, **kwargs):
width, height = self.get_width_height()
renderer = RendererCairo (self.figure.dpi)
@@ -532,9 +498,20 @@
self.figure.draw (renderer)
surface.write_to_png (fobj)
+
+ def print_pdf(self, fobj, *args, **kwargs):
+ return self._save(fobj, 'pdf', *args, **kwargs)
+ def print_ps(self, fobj, *args, **kwargs):
+ return self._save(fobj, 'ps', *args, **kwargs)
- def _save (self, fo, format, orientation, **kwargs):
+ def print_svg(self, fobj, *args, **kwargs):
+ return self._save(fobj, 'svg', *args, **kwargs)
+
+ def get_default_filetype(self):
+ return rcParams['cairo.format']
+
+ def _save (self, fo, format, **kwargs):
# save PDF/PS/SVG
orientation = kwargs.get('orientation', 'portrait')
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_emf.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_emf.py 2007-09-06 14:46:49 UTC (rev 3797)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_emf.py 2007-09-06 18:50:08 UTC (rev 3798)
@@ -599,36 +599,17 @@
"""
pass
- def print_figure(self, filename, dpi=300, facecolor='w', edgecolor='w',
- orientation='portrait', **kwargs):
- """
- Render the figure to hardcopy. Set the figure patch face and edge
- colors. This is useful because some of the GUIs have a gray figure
- face color background and you'll probably want to override this on
- hardcopy.
-
- Following the style of backend_ps and backend_gd
- """
- basename, ext = os.path.splitext(filename)
- if not ext:
- ext = '.emf'
- filename += ext
-
- # set the DPI to this hardcoded value for now, because libEMF
- # doesn't allow any changes to the device pixel size (1024
- # pixels per 320 mm)
- #dpi=1024.0/320.0*25.4
- #dpi=300
- self.figure.dpi.set(dpi)
+ filetypes = {'emf': 'Enhanced Metafile'}
+
+ def print_emf(self, filename, dpi=300, **kwargs):
width, height = self.figure.get_size_inches()
- self.figure.set_facecolor(facecolor)
- self.figure.set_edgecolor(edgecolor)
-
renderer = RendererEMF(filename,width,height,dpi)
self.figure.draw(renderer)
renderer.save()
-
+ def get_default_filetype(self):
+ return 'emf'
+
class FigureManagerEMF(FigureManagerBase):
"""
Wrap everything up into a window for the pylab interface
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_fltkagg.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_fltkagg.py 2007-09-06 14:46:49 UTC (rev 3797)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_fltkagg.py 2007-09-06 18:50:08 UTC (rev 3798)
@@ -242,17 +242,8 @@
def blit(self,bbox):
self.canvas.blit(bbox)
-
show = draw
- def print_figure(self, filename, dpi=None, facecolor='w', edgecolor='w',
- orientation='portrait', **kwargs):
- if dpi is None: dpi = matplotlib.rcParams['savefig.dpi']
- agg = self.switch_backends(FigureCanvasAgg)
- agg.print_figure(filename, dpi, facecolor, edgecolor, orientation,
- **kwargs)
- self.figure.set_canvas(self)
-
def widget(self):
return self.canvas
@@ -493,7 +484,23 @@
def save_figure(ptr,base):
+ filetypes = base.canvas.get_supported_filetypes()
+ default_filetype = base.canvas.get_default_filetype()
+ sorted_filetypes = filetypes.items()
+ sorted_filetypes.sort()
+
+ selected_filter = 0
+ filters = []
+ for i, (ext, name) in enumerate(sorted_filetypes):
+ filter = '%s (*.%s)' % (name, ext)
+ filters.append(filter)
+ if ext == default_filetype:
+ selected_filter = i
+ filters = '\t'.join(filters)
+
file_chooser=base._fc
+ file_chooser.filter(filters)
+ file_chooser.filter_value(selected_filter)
file_chooser.show()
while file_chooser.visible() :
Fltk.Fl.wait()
@@ -507,9 +514,10 @@
#start from last directory
lastDir = os.path.dirname(fname)
file_chooser.directory(lastDir)
-
+ format = sorted_filetypes[file_chooser.filter_value()][0]
+
try:
- base.canvas.print_figure(fname)
+ base.canvas.print_figure(fname, format=format)
except IOError, msg:
err = '\n'.join(map(str, msg))
msg = 'Failed to save %s: Error msg was\n\n%s' % (
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_gd.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_gd.py 2007-09-06 14:46:49 UTC (rev 3797)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_gd.py 2007-09-06 18:50:08 UTC (rev 3798)
@@ -329,38 +329,15 @@
class FigureCanvasGD(FigureCanvasBase):
+ filetypes = {'PNG': 'Portable Network Graphics'}
- def print_figure(self, filename, dpi=150, facecolor='w', edgecolor='w',
- orientation='portrait', **kwargs):
-
- """
- Render the figure to hardcopy using self.renderer as the
- renderer if neccessary
-
- filename can be a string filename or writable file instance
-
- """
-
- origDPI = self.figure.dpi.get()
- origfacecolor = self.figure.get_facecolor()
- origedgecolor = self.figure.get_edgecolor()
-
- self.figure.dpi.set(dpi)
- self.figure.set_facecolor(facecolor)
- self.figure.set_edgecolor(edgecolor)
-
+ def print_png(self, filename, *args, **kwargs):
im = self.draw()
-
- if is_string_like(filename):
- basename, ext = os.path.splitext(filename)
- if not len(ext): filename += '.png'
-
- im.writePng( filename )
-
- self.figure.dpi.set(origDPI)
- self.figure.set_facecolor(origfacecolor)
- self.figure.set_edgecolor(origedgecolor)
-
+ im.writePng(filename)
+
+ def get_default_filetype(self):
+ return 'png'
+
def draw(self):
"""
Draw to a gd image and return the image instance
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_gdk.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_gdk.py 2007-09-06 14:46:49 UTC (rev 3797)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_gdk.py 2007-09-06 18:50:08 UTC (rev 3798)
@@ -199,26 +199,24 @@
def _draw_mathtext(self, gc, x, y, s, prop, angle):
- width, height, descent, fonts, used_characters = self.mathtext_parser.parse(
- s, self.dpi.get(), prop)
+ ox, oy, width, height, descent, font_image, used_characters = \
+ self.mathtext_parser.parse(s, self.dpi.get(), prop)
if angle==90:
width, height = height, width
x -= width
y -= height
- imw, imh, image_str = fonts[0].image_as_str()
- N = imw*imh
+ imw = font_image.get_width()
+ imh = font_image.get_height()
+ N = imw * imh
# a numpixels by num fonts array
- Xall = npy.zeros((N,len(fonts)), npy.uint8)
+ Xall = npy.zeros((N,1), npy.uint8)
+
+ image_str = font_image.as_str()
+ Xall[:,0] = npy.fromstring(image_str, npy.uint8)
- for i, font in enumerate(fonts):
- if angle == 90:
- font.get_image().rotate() # <-- Rotate
- imw, imh, image_str = font.image_as_str()
- Xall[:,i] = npy.fromstring(image_str, npy.uint8)
-
# get the max alpha at each pixel
Xs = npy.amax(Xall,axis=1)
@@ -342,8 +340,8 @@
def get_text_width_height_descent(self, s, prop, ismath):
if ismath:
- width, height, descent, fonts, used_characters = self.mathtext_parser.parse(
- s, self.dpi.get(), prop)
+ ox, oy, width, height, descent, font_image, used_characters = \
+ self.mathtext_parser.parse(s, self.dpi.get(), prop)
return width, height, descent
layout, inkRect, logicalRect = self._get_pango_layout(s, prop)
@@ -478,55 +476,28 @@
self._renderer.set_width_height (width, height)
self.figure.draw (self._renderer)
- def print_figure(self, filename, dpi=150, facecolor='w', edgecolor='w',
- orientation='portrait', **kwargs):
- root, ext = os.path.splitext(filename)
- ext = ext[1:]
- if ext == '':
- ext = IMAGE_FORMAT_DEFAULT
- filename = filename + '.' + ext
+ filetypes = FigureCanvasBase.filetypes.copy()
+ filetypes['jpg'] = 'JPEG'
+ filetypes['jpeg'] = 'JPEG'
- self.figure.dpi.set(dpi)
- self.figure.set_facecolor(facecolor)
- self.figure.set_edgecolor(edgecolor)
+ def print_jpeg(self, filename, *args, **kwargs):
+ return self._print_image(filename, 'jpeg')
+ print_jpg = print_jpeg
- ext = ext.lower()
- if ext in ('jpg', 'png'): # native printing
- width, height = self.get_width_height()
- pixmap = gtk.gdk.Pixmap (None, width, height, depth=24)
- self._render_figure(pixmap, width, height)
+ def print_png(self, filename, *args, **kwargs):
+ return self._print_image(filename, 'png')
+
+ def _print_image(self, filename, format, *args, **kwargs):
+ width, height = self.get_width_height()
+ pixmap = gtk.gdk.Pixmap (None, width, height, ...
[truncated message content] |
|
From: <md...@us...> - 2007-09-06 19:35:03
|
Revision: 3799
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3799&view=rev
Author: mdboom
Date: 2007-09-06 12:35:00 -0700 (Thu, 06 Sep 2007)
Log Message:
-----------
Add svgz support to backend_svg and backend_cairo.
Put all styles inside of a separate <style> element in backend_svg, to
save considerably on file size.
Modified Paths:
--------------
trunk/matplotlib/FILETYPES
trunk/matplotlib/lib/matplotlib/backend_bases.py
trunk/matplotlib/lib/matplotlib/backends/backend_cairo.py
trunk/matplotlib/lib/matplotlib/backends/backend_svg.py
Modified: trunk/matplotlib/FILETYPES
===================================================================
--- trunk/matplotlib/FILETYPES 2007-09-06 18:50:08 UTC (rev 3798)
+++ trunk/matplotlib/FILETYPES 2007-09-06 19:35:00 UTC (rev 3799)
@@ -7,54 +7,55 @@
A cell with a '+' in it denotes the rasterizer and the file writing
infrastructure as separate pieces.
-+--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
-| |bmp |emf |eps |jpeg |pcx |pdf |png |ps |raw |svg |tiff |xpm |
-+--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
-|Agg | |emf |ps | | |pdf |agg * |ps |agg |svg | | |
-+--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
-|Cairo | |emf |ps | | |cairo |cairo |cairo|agg |cairo| | |
-|[1] | | |[2] | | | |* | | | | | |
-+--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
-|CocoaAgg| |emf |ps | | |pdf |agg * |ps |agg |svg | | |
-+--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
-|Emf | |emf *| | | | | | | | | | |
-+--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
-|FltkAgg | |emf |ps | | |pdf |agg * |ps |agg |svg | | |
-+--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
-|Gd | | | | | | |gd * | | | | | |
-+--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
-|Gtk | |emf |ps |gdk + | |pdf |gdk + |ps |agg |svg | | |
-|(gdk) | | | |pixbuf | | |pixbuf| | | | | |
-| | | | | | | |* | | | | | |
-+--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
-|GtkAgg | |emf |ps |agg + | |pdf |agg + |ps |agg |svg | | |
-| | | | |pixbuf | | |pixbuf| | | | | |
-| | | | | | | |* | | | | | |
-+--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
-|GtkCairo| |emf |ps |cairo +| |cairo |cairo |cairo|agg |svg | | |
-| | | | |pixbuf | | |* | | | | | |
-+--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
-|Paint | | | | | | |libart| | | | | |
-|(libart)| | | | | | |* | | | | | |
-+--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
-|Pdf | | | | | |pdf * | | | | | | |
-+--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
-|Ps | | |ps | | | | |ps * | | | | |
-+--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
-|QtAgg | |emf |ps | | |pdf |agg * |ps |agg |svg | | |
-+--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
-|Qt4Agg | |emf |ps | | |pdf |agg * |ps |agg |svg | | |
-+--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
-|Svg | | | | | | | | | |svg *| | |
-+--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
-|TkAgg | |emf |ps | | |pdf |agg * |ps |agg |svg | | |
-+--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
-|Wx |wx + |emf |ps |wx + wx|wx + |pdf |wx + |ps |agg |svg |wx + |wx + |
-| |wx | | | |wx | |wx * | | | |wx |wx |
-+--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
-|WxAgg | |emf |ps | | |pdf |agg * |ps |agg |svg | | |
-+--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+-----+
+| |bmp |emf |eps |jpeg |pcx |pdf |png |ps |raw |svg |svgz |tiff |xpm |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+-----+
+|Agg | |emf |ps | | |pdf |agg * |ps |agg |svg |svg | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+-----+
+|Cairo | |emf |ps | | |cairo |cairo |cairo|agg |cairo|cairo| | |
+|[1] | | |[2] | | | |* | | | | | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+-----+
+|CocoaAgg| |emf |ps | | |pdf |agg * |ps |agg |svg |svg | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+-----+
+|Emf | |emf *| | | | | | | | | | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+-----+
+|FltkAgg | |emf |ps | | |pdf |agg * |ps |agg |svg |svg | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+-----+
+|Gd | | | | | | |gd * | | | | | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+-----+
+|Gtk | |emf |ps |gdk + | |pdf |gdk + |ps |agg |svg |svg | | |
+|(gdk) | | | |pixbuf | | |pixbuf| | | | | | |
+| | | | | | | |* | | | | | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+-----+
+|GtkAgg | |emf |ps |agg + | |pdf |agg + |ps |agg |svg |svg | | |
+| | | | |pixbuf | | |pixbuf| | | | | | |
+| | | | | | | |* | | | | | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+-----+
+|GtkCairo| |emf |ps |cairo +| |cairo |cairo |cairo|agg |svg |svg | | |
+| | | | |pixbuf | | |* | | | | | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+-----+
+|Paint | | | | | | |libart| | | | | | |
+|(libart)| | | | | | |* | | | | | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+-----+
+|Pdf | | | | | |pdf * | | | | | | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+-----+
+|Ps | | |ps | | | | |ps * | | | | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+-----+
+|QtAgg | |emf |ps | | |pdf |agg * |ps |agg |svg |svg | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+-----+
+|Qt4Agg | |emf |ps | | |pdf |agg * |ps |agg |svg |svg | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+-----+
+|Svg | | | | | | | | | |svg *|svg | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+-----+
+|TkAgg | |emf |ps | | |pdf |agg * |ps |agg |svg |svg | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+-----+
+|Wx |wx + |emf |ps |wx + wx|wx + |pdf |wx + |ps |agg |svg |svg |wx + |wx + |
+| |wx | | | |wx | |wx * | | | | |wx |wx |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+-----+
+|WxAgg | |emf |ps | | |pdf |agg * |ps |agg |svg |svg | | |
++--------+-----+-----+-----+-------+-----+------+------+-----+-----+-----+-----+-----+-----+
* Default filetype for the backend
[1] Cairo's default filetype is specified in rcParams['cairo.format']
-[2] Cairo does not produce .eps files, and instead falls back on backend_ps.py
\ No newline at end of file
+[2] Cairo does not produce .eps files, and instead falls back on
+backend_ps.py
Modified: trunk/matplotlib/lib/matplotlib/backend_bases.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backend_bases.py 2007-09-06 18:50:08 UTC (rev 3798)
+++ trunk/matplotlib/lib/matplotlib/backend_bases.py 2007-09-06 19:35:00 UTC (rev 3799)
@@ -1081,6 +1081,7 @@
'raw': 'Raw RGBA bitmap',
'rgb': 'Raw RGBA bitmap',
'svg': 'Scalable Vector Graphics',
+ 'svgz': 'Scalable Vector Graphics'
}
# All of these print_* functions do a lazy import because
@@ -1123,7 +1124,12 @@
from backends.backend_svg import FigureCanvasSVG # lazy import
svg = self.switch_backends(FigureCanvasSVG)
return svg.print_svg(*args, **kwargs)
-
+
+ def print_svgz(self, *args, **kwargs):
+ from backends.backend_svg import FigureCanvasSVG # lazy import
+ svg = self.switch_backends(FigureCanvasSVG)
+ return svg.print_svgz(*args, **kwargs)
+
def get_supported_filetypes(self):
return self.filetypes
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_cairo.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_cairo.py 2007-09-06 18:50:08 UTC (rev 3798)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_cairo.py 2007-09-06 19:35:00 UTC (rev 3799)
@@ -19,7 +19,7 @@
"""
from __future__ import division
-import os, sys, warnings
+import os, sys, warnings, gzip
import numpy as npy
@@ -36,7 +36,7 @@
from matplotlib.backend_bases import RendererBase, GraphicsContextBase,\
FigureManagerBase, FigureCanvasBase
-from matplotlib.cbook import enumerate, izip
+from matplotlib.cbook import enumerate, izip, is_string_like
from matplotlib.figure import Figure
from matplotlib.mathtext import MathTextParser
from matplotlib.transforms import Bbox
@@ -46,10 +46,6 @@
_debug = False
#_debug = True
-# Image formats that this backend supports - for print_figure()
-IMAGE_FORMAT = ['eps', 'pdf', 'png', 'ps', 'svg']
-IMAGE_FORMAT_DEFAULT = 'png'
-
# Image::color_conv(format) for draw_image()
if sys.byteorder == 'little':
BYTE_FORMAT = 0 # BGRA
@@ -508,6 +504,9 @@
def print_svg(self, fobj, *args, **kwargs):
return self._save(fobj, 'svg', *args, **kwargs)
+ def print_svgz(self, fobj, *args, **kwargs):
+ return self._save(fobj, 'svgz', *args, **kwargs)
+
def get_default_filetype(self):
return rcParams['cairo.format']
@@ -534,10 +533,15 @@
raise RuntimeError ('cairo has not been compiled with PDF '
'support enabled')
surface = cairo.PDFSurface (fo, width_in_points, height_in_points)
- elif format == 'svg':
+ elif format in ('svg', 'svgz'):
if not cairo.HAS_SVG_SURFACE:
raise RuntimeError ('cairo has not been compiled with SVG '
'support enabled')
+ if format == 'svgz':
+ filename = fo
+ if is_string_like(fo):
+ fo = open(fo, 'wb')
+ fo = gzip.GzipFile(None, 'wb', fileobj=fo)
surface = cairo.SVGSurface (fo, width_in_points, height_in_points)
else:
warnings.warn ("unknown format: %s" % format)
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_svg.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_svg.py 2007-09-06 18:50:08 UTC (rev 3798)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_svg.py 2007-09-06 19:35:00 UTC (rev 3799)
@@ -1,6 +1,6 @@
from __future__ import division
-import os, codecs, base64, tempfile, urllib
+import os, codecs, base64, tempfile, urllib, gzip
from matplotlib import verbose, __version__, rcParams
from matplotlib.backend_bases import RendererBase, GraphicsContextBase,\
@@ -41,6 +41,7 @@
self._char_defs = {}
self.mathtext_parser = MathTextParser('SVG')
self.fontd = {}
+ self._styles = {}
svgwriter.write(svgProlog%(width,height,width,height))
def _draw_svg_element(self, element, details, gc, rgbFace):
@@ -50,9 +51,10 @@
else:
clippath = 'clip-path="url(#%s)"' % clipid
- self._svgwriter.write ('%s<%s %s %s %s/>\n' % (
+ style = self._map_style(self._get_style(gc, rgbFace))
+ self._svgwriter.write ('%s<%s class="%s" %s %s/>\n' % (
cliprect,
- element, self._get_style(gc, rgbFace), clippath, details))
+ element, style, clippath, details))
def _get_font(self, prop):
key = hash(prop)
@@ -85,8 +87,8 @@
linewidth = gc.get_linewidth()
if linewidth:
- return 'style="fill: %s; stroke: %s; stroke-width: %f; ' \
- 'stroke-linejoin: %s; stroke-linecap: %s; %s opacity: %f"' % (
+ return 'fill: %s; stroke: %s; stroke-width: %f; ' \
+ 'stroke-linejoin: %s; stroke-linecap: %s; %s opacity: %f' % (
fill,
rgb2hex(gc.get_rgb()),
linewidth,
@@ -96,11 +98,16 @@
gc.get_alpha(),
)
else:
- return 'style="fill: %s; opacity: %f"' % (\
+ return 'fill: %s; opacity: %f' % (\
fill,
gc.get_alpha(),
)
+ def _map_style(self, style):
+ return self._styles.setdefault(
+ style,
+ "_%x" % len(self._styles))
+
def _get_gc_clip_svg(self, gc):
cliprect = gc.get_clip_rectangle()
if cliprect is None:
@@ -112,11 +119,12 @@
self._clipd[key] = cliprect
x, y, w, h = cliprect
y = self.height-(y+h)
+ style = self._map_style("stroke: gray; fill: none;")
box = """\
<defs>
<clipPath id="%(key)s">
<rect x="%(x)f" y="%(y)f" width="%(w)f" height="%(h)f"
- style="stroke: gray; fill: none;"/>
+ class="%(style)s"/>
</clipPath>
</defs>
""" % locals()
@@ -286,12 +294,13 @@
svg = ''.join(svg)
else:
style = 'font-size: %f; font-family: %s; font-style: %s; fill: %s;'%(fontsize, fontfamily,fontstyle, color)
+ style_number = self._map_style(style)
if angle!=0:
transform = 'transform="translate(%f,%f) rotate(%1.1f) translate(%f,%f)"' % (x,y,-angle,-x,-y) # Inkscape doesn't support rotate(angle x y)
else: transform = ''
svg = """\
-<text style="%(style)s" x="%(x)f" y="%(y)f" %(transform)s>%(thetext)s</text>
+<text class="%(style_number)s" x="%(x)f" y="%(y)f" %(transform)s>%(thetext)s</text>
""" % locals()
self._svgwriter.write (svg)
@@ -348,8 +357,11 @@
self.open_group("mathtext")
+ style = "fill: %s" % color
+ style_number = self._map_style(style)
+
if rcParams['svg.embed_char_paths']:
- svg = ['<g style="fill: %s" transform="' % color]
+ svg = ['<g class="%s" transform="' % style_number]
if angle != 0:
svg.append('translate(%f,%f) rotate(%1.1f)'
% (x,y,-angle) )
@@ -364,7 +376,7 @@
(charid, new_x, -new_y_mtc, fontsize / self.FONT_SCALE))
svg.append('</g>\n')
else: # not rcParams['svg.embed_char_paths']
- svg = ['<text style="fill: %s" x="%f" y="%f"' % (color,x,y)]
+ svg = ['<text class="%s" x="%f" y="%f"' % (style_number, x, y)]
if angle != 0:
svg.append(' transform="translate(%f,%f) rotate(%1.1f) translate(%f,%f)"'
@@ -375,9 +387,10 @@
for font, fontsize, thetext, new_x, new_y_mtc, metrics in svg_glyphs:
new_y = - new_y_mtc
-
- svg.append('<tspan style="font-size: %f; font-family: %s"' %
- (fontsize, font.family_name))
+ style = "font-size: %f; font-family: %s" % (fontsize, font.family_name)
+ style_number = self._map_style(style)
+
+ svg.append('<tspan class="%s"' % style_number)
xadvance = metrics.advance
svg.append(' textLength="%f"' % xadvance)
@@ -399,7 +412,8 @@
svg.append('</text>\n')
if len(svg_rects):
- svg.append('<g style="fill: black; stroke: none" transform="')
+ style_number = self._map_style("fill: black; stroke: none")
+ svg.append('<g class="%s" transform="' % style_number)
if angle != 0:
svg.append('translate(%f,%f) rotate(%1.1f)'
% (x,y,-angle) )
@@ -415,12 +429,20 @@
self.close_group("mathtext")
def finish(self):
+ write = self._svgwriter.write
if len(self._char_defs):
- self._svgwriter.write('<defs id="fontpaths">\n')
+ write('<defs id="fontpaths">\n')
for path in self._char_defs.values():
- self._svgwriter.write(path)
- self._svgwriter.write('</defs>\n')
- self._svgwriter.write('</svg>\n')
+ write(path)
+ write('</defs>\n')
+ if len(self._styles):
+ write('<style type="text/css">\n')
+ styles = self._styles.items()
+ styles.sort()
+ for style, number in styles:
+ write('.%s { %s }\n' % (number, style))
+ write('</style>\n')
+ write('</svg>\n')
def flipy(self):
return True
@@ -444,14 +466,23 @@
class FigureCanvasSVG(FigureCanvasBase):
- filetypes = {'svg': 'Scalable Vector Graphics'}
+ filetypes = {'svg': 'Scalable Vector Graphics',
+ 'svgz': 'Scalable Vector Graphics'}
def print_svg(self, filename, *args, **kwargs):
+ svgwriter = codecs.open(filename, 'w', 'utf-8')
+ return self._print_svg(filename, svgwriter)
+
+ def print_svgz(self, filename, *args, **kwargs):
+ gzipwriter = gzip.GzipFile(filename, 'w')
+ svgwriter = codecs.EncodedFile(gzipwriter, 'utf-8')
+ return self._print_svg(filename, svgwriter)
+
+ def _print_svg(self, filename, svgwriter):
self.figure.dpi.set(72)
width, height = self.figure.get_size_inches()
w, h = width*72, height*72
- svgwriter = codecs.open( filename, 'w', 'utf-8' )
renderer = RendererSVG(w, h, svgwriter, filename)
self.figure.draw(renderer)
renderer.finish()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jo...@us...> - 2007-09-06 20:13:12
|
Revision: 3802
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3802&view=rev
Author: jouni
Date: 2007-09-06 13:13:11 -0700 (Thu, 06 Sep 2007)
Log Message:
-----------
A more careful reading of the pdf spec reveals that Type 1 fonts
embedded in pdf files are not actually supposed to be in pfa format,
but a similar format where the encrypted part is not encoded in
hexadecimal, and where the "fixed-content" part at the end may be
omitted. This fixes the problems with Preview.app.
Modified Paths:
--------------
trunk/matplotlib/API_CHANGES
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py
trunk/matplotlib/lib/matplotlib/type1font.py
Modified: trunk/matplotlib/API_CHANGES
===================================================================
--- trunk/matplotlib/API_CHANGES 2007-09-06 19:36:34 UTC (rev 3801)
+++ trunk/matplotlib/API_CHANGES 2007-09-06 20:13:11 UTC (rev 3802)
@@ -7,9 +7,9 @@
The file type1font.py contains a new class for Type 1 fonts.
Currently it simply reads pfa and pfb format files and stores the
- data in pfa format, which is the format for embedding Type 1 fonts
- in postscript and pdf files. In the future the class might
- actually parse the font to allow e.g. subsetting.
+ data in a way that is suitable for embedding in pdf files. In the
+ future the class might actually parse the font to allow e.g.
+ subsetting.
FT2Font now supports FT_Attach_File. In practice this can be used
to read an afm file in addition to a pfa/pfb file, to get metrics
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2007-09-06 19:36:34 UTC (rev 3801)
+++ trunk/matplotlib/CHANGELOG 2007-09-06 20:13:11 UTC (rev 3802)
@@ -1,3 +1,6 @@
+2007-09-06 Fixed a bug in the embedding of Type 1 fonts in PDF.
+ Now it doesn't crash Preview.app. - JKS
+
2007-09-06 Refactored image saving code so that all GUI backends can
save most image types. See FILETYPES for a matrix of
backends and their supported file types.
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py 2007-09-06 19:36:34 UTC (rev 3801)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py 2007-09-06 20:13:11 UTC (rev 3802)
@@ -607,13 +607,13 @@
self.writeObject(widthsObject, widths)
self.writeObject(fontdescObject, descriptor)
- fontdata = type1font.Type1Font(filename)
- len1, len2, len3 = fontdata.lengths()
+ t1font = type1font.Type1Font(filename)
self.beginStream(fontfileObject.id, None,
- { 'Length1': len1,
- 'Length2': len2,
- 'Length3': len3 })
- self.currentstream.write(fontdata.data)
+ { 'Length1': len(t1font.parts[0]),
+ 'Length2': len(t1font.parts[1]),
+ 'Length3': 0 })
+ self.currentstream.write(t1font.parts[0])
+ self.currentstream.write(t1font.parts[1])
self.endStream()
return fontdictObject
Modified: trunk/matplotlib/lib/matplotlib/type1font.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/type1font.py 2007-09-06 19:36:34 UTC (rev 3801)
+++ trunk/matplotlib/lib/matplotlib/type1font.py 2007-09-06 20:13:11 UTC (rev 3802)
@@ -1,9 +1,10 @@
"""
A class representing a Type 1 font.
-This version merely allows reading in pfa and pfb files, and stores
-the data in pfa format (which can be embedded in PostScript or PDF
-files). A more complete class might support subsetting.
+This version merely allows reading in pfa and pfb files, stores the
+data in pfa format, and allows reading the parts of the data in a
+format suitable for embedding in pdf files. A more complete class
+might support subsetting.
Usage: font = Type1Font(filename)
somefile.write(font.data) # writes out font in pfa format
@@ -23,9 +24,10 @@
def __init__(self, filename):
file = open(filename, 'rb')
try:
- self._read(file)
+ data = self._read(file)
finally:
file.close()
+ self.parts = self._split(data)
def _read(self, file):
rawdata = file.read()
@@ -33,7 +35,7 @@
self.data = rawdata
return
- self.data = ''
+ data = ''
while len(rawdata) > 0:
if not rawdata.startswith(chr(128)):
raise RuntimeError, \
@@ -46,9 +48,9 @@
rawdata = rawdata[6+length:]
if type == 1: # ASCII text: include verbatim
- self.data += segment
+ data += segment
elif type == 2: # binary data: encode in hexadecimal
- self.data += ''.join(['%02x' % ord(char)
+ data += ''.join(['%02x' % ord(char)
for char in segment])
elif type == 3: # end of file
break
@@ -56,9 +58,11 @@
raise RuntimeError, \
'Unknown segment type %d in pfb file' % type
- def lengths(self):
+ return data
+
+ def _split(self, data):
"""
- Compute the lengths of the three parts of a Type 1 font.
+ Split the Type 1 font into its three main parts.
The three parts are: (1) the cleartext part, which ends in a
eexec operator; (2) the encrypted part; (3) the fixed part,
@@ -66,28 +70,33 @@
lines, a cleartomark operator, and possibly something else.
"""
- # Cleartext part: just find the eexec and skip the eol char(s)
- idx = self.data.index('eexec')
+ # Cleartext part: just find the eexec and skip whitespace
+ idx = data.index('eexec')
idx += len('eexec')
- while self.data[idx] in ('\n', '\r'):
+ while data[idx] in ' \t\r\n':
idx += 1
len1 = idx
# Encrypted part: find the cleartomark operator and count
# zeros backward
- idx = self.data.rindex('cleartomark') - 1
+ idx = data.rindex('cleartomark') - 1
zeros = 512
- while zeros and self.data[idx] in ('0', '\n', '\r'):
- if self.data[idx] == '0':
+ while zeros and data[idx] in ('0', '\n', '\r'):
+ if data[idx] == '0':
zeros -= 1
idx -= 1
if zeros:
raise RuntimeError, 'Insufficiently many zeros in Type 1 font'
- len2 = idx - len1
- len3 = len(self.data) - idx
+ # Convert encrypted part to binary (if we read a pfb file, we
+ # may end up converting binary to hexadecimal to binary again;
+ # but if we read a pfa file, this part is already in hex, and
+ # I am not quite sure if even the pfb format guarantees that
+ # it will be in binary).
+ binary = ''.join([chr(int(data[i:i+2], 16))
+ for i in range(len1, idx, 2)])
- return len1, len2, len3
+ return data[:len1], binary, data[idx:]
if __name__ == '__main__':
import sys
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jo...@us...> - 2007-09-07 06:58:04
|
Revision: 3803
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3803&view=rev
Author: jouni
Date: 2007-09-06 23:58:00 -0700 (Thu, 06 Sep 2007)
Log Message:
-----------
Clip path support in pdf backend
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2007-09-06 20:13:11 UTC (rev 3802)
+++ trunk/matplotlib/CHANGELOG 2007-09-07 06:58:00 UTC (rev 3803)
@@ -1,3 +1,5 @@
+2007-09-07 Added clip path support to pdf backend. - JKS
+
2007-09-06 Fixed a bug in the embedding of Type 1 fonts in PDF.
Now it doesn't crash Preview.app. - JKS
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py 2007-09-06 20:13:11 UTC (rev 3802)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py 2007-09-07 06:58:00 UTC (rev 3803)
@@ -64,11 +64,9 @@
#
# Some tricky points:
#
-# 1. The clip rectangle (which could in pdf be an arbitrary path, not
-# necessarily a rectangle) can only be widened by popping from the
-# state stack. Thus the state must be pushed onto the stack before
-# narrowing the rectangle. This is taken care of by
-# GraphicsContextPdf.
+# 1. The clip path can only be widened by popping from the state
+# stack. Thus the state must be pushed onto the stack before narrowing
+# the clip path. This is taken care of by GraphicsContextPdf.
#
# 2. Sometimes it is necessary to refer to something (e.g. font,
# image, or extended graphics state, which contains the alpha value)
@@ -1072,6 +1070,7 @@
self.writePath(path, fillp)
self.endStream()
+ #@staticmethod
def pathBbox(path, lw):
path.rewind(0)
x, y = [], []
@@ -1086,25 +1085,32 @@
return min(x)-lw, min(y)-lw, max(x)+lw, max(y)+lw
pathBbox = staticmethod(pathBbox)
- def writePath(self, path, fillp):
+ #@staticmethod
+ def pathOperations(path):
path.rewind(0)
+ result = []
while True:
- code, xp, yp = path.vertex()
+ code, x, y = path.vertex()
code = code & agg.path_cmd_mask
if code == agg.path_cmd_stop:
break
elif code == agg.path_cmd_move_to:
- self.output(xp, yp, Op.moveto)
+ result += (x, y, Op.moveto)
elif code == agg.path_cmd_line_to:
- self.output(xp, yp, Op.lineto)
+ result += (x, y, Op.lineto)
elif code == agg.path_cmd_curve3:
- pass
+ pass # TODO
elif code == agg.path_cmd_curve4:
- pass
+ pass # TODO
elif code == agg.path_cmd_end_poly:
- self.output(Op.closepath)
+ result += (Op.closepath,)
else:
- print >>sys.stderr, "writePath", code, xp, yp
+ print >>sys.stderr, "pathOperations", code, xp, yp
+ return result
+ pathOperations = staticmethod(pathOperations)
+
+ def writePath(self, path, fillp):
+ self.output(*self.pathOperations(path))
if fillp:
self.output(Op.fill_stroke)
else:
@@ -1785,49 +1791,64 @@
self.parent = self.parent.parent
return [Op.grestore]
- def cliprect_cmd(self, cliprect):
+ def clip_cmd(self, cliprect, clippath):
"""Set clip rectangle. Calls self.pop() and self.push()."""
cmds = []
- while self._cliprect != cliprect and self.parent is not None:
+ # Pop graphics state until we hit the right one or the stack is empty
+ while (self._cliprect, self._clippath) != (cliprect, clippath) \
+ and self.parent is not None:
cmds.extend(self.pop())
- if self._cliprect != cliprect:
- cmds.extend(self.push() +
- [t for t in cliprect] +
- [Op.rectangle, Op.clip, Op.endpath])
+ # Unless we hit the right one, set the clip polygon
+ if (self._cliprect, self._clippath) != (cliprect, clippath):
+ cmds.append(self.push())
+ if self._cliprect != cliprect:
+ cmds.extend([t for t in cliprect] +
+ [Op.rectangle, Op.clip, Op.endpath])
+ if self._clippath != clippath:
+ cmds.extend(PdfFile.pathOperations(clippath) +
+ [Op.clip, Op.endpath])
return cmds
commands = (
- ('_cliprect', cliprect_cmd), # must come first since may pop
- ('_alpha', alpha_cmd),
- ('_capstyle', capstyle_cmd),
- ('_fillcolor', fillcolor_cmd),
- ('_joinstyle', joinstyle_cmd),
- ('_linewidth', linewidth_cmd),
- ('_dashes', dash_cmd),
- ('_rgb', rgb_cmd),
- ('_hatch', hatch_cmd), # must come after fillcolor and rgb
+ (('_cliprect', '_clippath'), clip_cmd), # must come first since may pop
+ (('_alpha',), alpha_cmd),
+ (('_capstyle',), capstyle_cmd),
+ (('_fillcolor',), fillcolor_cmd),
+ (('_joinstyle',), joinstyle_cmd),
+ (('_linewidth',), linewidth_cmd),
+ (('_dashes',), dash_cmd),
+ (('_rgb',), rgb_cmd),
+ (('_hatch',), hatch_cmd), # must come after fillcolor and rgb
)
# TODO: _linestyle
- def copy_properties(self, other):
- """Copy properties of other into self."""
- GraphicsContextBase.copy_properties(self, other)
- self._fillcolor = other._fillcolor
-
def delta(self, other):
- """Copy properties of other into self and return PDF commands
+ """
+ Copy properties of other into self and return PDF commands
needed to transform self into other.
"""
cmds = []
- for param, cmd in self.commands:
- if getattr(self, param) != getattr(other, param):
- cmds.extend(cmd(self, getattr(other, param)))
- setattr(self, param, getattr(other, param))
+ for params, cmd in self.commands:
+ ours = [ getattr(self, p) for p in params ]
+ theirs = [ getattr(other, p) for p in params ]
+ if ours != theirs:
+ cmds.extend(cmd(self, *theirs))
+ for p in params:
+ setattr(self, p, getattr(other, p))
return cmds
+ def copy_properties(self, other):
+ """
+ Copy properties of other into self.
+ """
+ GraphicsContextBase.copy_properties(self, other)
+ self._fillcolor = other._fillcolor
+
def finalize(self):
- """Make sure every pushed graphics state is popped."""
+ """
+ Make sure every pushed graphics state is popped.
+ """
cmds = []
while self.parent is not None:
cmds.extend(self.pop())
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2007-09-07 18:08:44
|
Revision: 3812
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3812&view=rev
Author: mdboom
Date: 2007-09-07 11:08:43 -0700 (Fri, 07 Sep 2007)
Log Message:
-----------
Turn svg.embed_char_paths on by default.
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/config/mplconfig.py
trunk/matplotlib/lib/matplotlib/config/rcsetup.py
trunk/matplotlib/lib/matplotlib/rcsetup.py
trunk/matplotlib/matplotlibrc.template
Modified: trunk/matplotlib/lib/matplotlib/config/mplconfig.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2007-09-07 18:07:43 UTC (rev 3811)
+++ trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2007-09-07 18:08:43 UTC (rev 3812)
@@ -101,7 +101,7 @@
class svg(TConfig):
image_inline = T.true
image_noscale = T.false
- embed_chars = T.false
+ embed_chars = T.true
class lines(TConfig):
linewidth = T.Float(1.0)
Modified: trunk/matplotlib/lib/matplotlib/config/rcsetup.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/config/rcsetup.py 2007-09-07 18:07:43 UTC (rev 3811)
+++ trunk/matplotlib/lib/matplotlib/config/rcsetup.py 2007-09-07 18:08:43 UTC (rev 3812)
@@ -466,7 +466,7 @@
'pdf.fonttype' : [3, validate_fonttype], # 3 (Type3) or 42 (Truetype)
'svg.image_inline' : [True, validate_bool], # write raster image data directly into the svg file
'svg.image_noscale' : [False, validate_bool], # suppress scaling of raster data embedded in SVG
- 'svg.embed_char_paths' : [False, validate_bool], # True to save all characters as paths in the SVG
+ 'svg.embed_char_paths' : [True, validate_bool], # True to save all characters as paths in the SVG
'plugins.directory' : ['.matplotlib_plugins', str], # where plugin directory is locate
}
Modified: trunk/matplotlib/lib/matplotlib/rcsetup.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/rcsetup.py 2007-09-07 18:07:43 UTC (rev 3811)
+++ trunk/matplotlib/lib/matplotlib/rcsetup.py 2007-09-07 18:08:43 UTC (rev 3812)
@@ -466,7 +466,7 @@
'pdf.fonttype' : [3, validate_fonttype], # 3 (Type3) or 42 (Truetype)
'svg.image_inline' : [True, validate_bool], # write raster image data directly into the svg file
'svg.image_noscale' : [False, validate_bool], # suppress scaling of raster data embedded in SVG
- 'svg.embed_char_paths' : [False, validate_bool], # True to save all characters as paths in the SVG
+ 'svg.embed_char_paths' : [True, validate_bool], # True to save all characters as paths in the SVG
'plugins.directory' : ['.matplotlib_plugins', str], # where plugin directory is locate
}
Modified: trunk/matplotlib/matplotlibrc.template
===================================================================
--- trunk/matplotlib/matplotlibrc.template 2007-09-07 18:07:43 UTC (rev 3811)
+++ trunk/matplotlib/matplotlibrc.template 2007-09-07 18:08:43 UTC (rev 3812)
@@ -292,7 +292,7 @@
# svg backend params
#svg.image_inline : True # write raster image data directly into the svg file
#svg.image_noscale : False # suppress scaling of raster data embedded in SVG
-#svg.embed_chars : False # embed character outlines in the SVG file
+#svg.embed_chars : True # embed character outlines in the SVG file
# Set the verbose flags. This controls how much information
# matplotlib gives you at runtime and where it goes. The verbosity
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2007-09-08 23:53:16
|
Revision: 3817
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3817&view=rev
Author: efiring
Date: 2007-09-08 16:53:06 -0700 (Sat, 08 Sep 2007)
Log Message:
-----------
Delete gd and paint backends.
Modified Paths:
--------------
trunk/matplotlib/API_CHANGES
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/backends/__init__.py
trunk/matplotlib/setupext.py
Removed Paths:
-------------
trunk/matplotlib/lib/matplotlib/backends/backend_gd.py
trunk/matplotlib/lib/matplotlib/backends/backend_paint.py
Modified: trunk/matplotlib/API_CHANGES
===================================================================
--- trunk/matplotlib/API_CHANGES 2007-09-07 20:43:20 UTC (rev 3816)
+++ trunk/matplotlib/API_CHANGES 2007-09-08 23:53:06 UTC (rev 3817)
@@ -1,3 +1,5 @@
+ The gd and paint backends have been deleted.
+
The errorbar method and function now accept additional kwargs
so that upper and lower limits can be indicated by capping the
bar with a caret instead of a straight line segment.
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2007-09-07 20:43:20 UTC (rev 3816)
+++ trunk/matplotlib/CHANGELOG 2007-09-08 23:53:06 UTC (rev 3817)
@@ -1,3 +1,5 @@
+2007-09-08 Eliminated gd and paint backends - EF
+
2007-09-06 .bmp file format is now longer an alias for .raw
2007-09-07 Added clip path support to pdf backend. - JKS
@@ -7,7 +9,7 @@
2007-09-06 Refactored image saving code so that all GUI backends can
save most image types. See FILETYPES for a matrix of
- backends and their supported file types.
+ backends and their supported file types.
Backend canvases should no longer write their own print_figure()
method -- instead they should write a print_xxx method for
each filetype they can output and add an entry to their
@@ -16,7 +18,7 @@
2007-09-05 Fixed Qt version reporting in setupext.py - DSD
2007-09-04 Embedding Type 1 fonts in PDF, and thus usetex support
- via dviread, sort of works. To test, enable it by
+ via dviread, sort of works. To test, enable it by
renaming _draw_tex to draw_tex. - JKS
2007-09-03 Added ability of errorbar show limits via caret or
Modified: trunk/matplotlib/lib/matplotlib/backends/__init__.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/__init__.py 2007-09-07 20:43:20 UTC (rev 3816)
+++ trunk/matplotlib/lib/matplotlib/backends/__init__.py 2007-09-08 23:53:06 UTC (rev 3817)
@@ -7,7 +7,7 @@
interactive_bk = ['GTK', 'GTKAgg', 'GTKCairo', 'FltkAgg', 'QtAgg', 'Qt4Agg',
'TkAgg', 'WX', 'WXAgg', 'CocoaAgg', 'Aqt']
-non_interactive_bk = ['Agg2', 'Agg', 'Cairo', 'EMF', 'GD', 'GDK', 'Paint',
+non_interactive_bk = ['Agg2', 'Agg', 'Cairo', 'EMF', 'GDK',
'Pdf', 'PS', 'SVG', 'Template']
all_backends = interactive_bk + non_interactive_bk
Deleted: trunk/matplotlib/lib/matplotlib/backends/backend_gd.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_gd.py 2007-09-07 20:43:20 UTC (rev 3816)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_gd.py 2007-09-08 23:53:06 UTC (rev 3817)
@@ -1,374 +0,0 @@
-"""
-A gd backend http://newcenturycomputers.net/projects/gdmodule.html
-"""
-
-
-from __future__ import division
-import sys, os, math, warnings
-
-import numpy as npy
-
-try:
- import gd
-except ImportError:
- print >>sys.stderr, 'You must first install the gd module http://newcenturycomputers.net/projects/gdmodule.html'
- sys.exit()
-
-from matplotlib.backend_bases import RendererBase, \
- GraphicsContextBase, FigureManagerBase, FigureCanvasBase
-from matplotlib import verbose
-from matplotlib._pylab_helpers import Gcf
-from matplotlib.cbook import enumerate, pieces, is_string_like
-from matplotlib.colors import colorConverter
-from matplotlib.figure import Figure
-from matplotlib.transforms import Bbox
-from matplotlib.font_manager import findfont
-# support old font names
-if (os.environ.has_key('GDFONTPATH') and not
- os.environ.has_key('TTFPATH')):
- os.environ['TTFPATH'] = os.environ['GDFONTPATH']
-
-
-
-
-PIXELS_PER_INCH = 96 # constant GD uses for screen DPI
-
-
-def round(x):
- return int(math.floor(x+0.5))
-
-
-class RendererGD(RendererBase):
- """
- The renderer handles all the drawing primitives using a graphics
- context instance that controls the colors/styles
- """
-
-
- # todo: can gd support cap and join styles?
- def __init__(self, im, dpi):
- "Initialize the renderer with a gd image instance"
- self.im = im
- self._cached = {} # a map from get_color args to colors
-
- self.width, self.height = im.size()
- self.dpi = dpi
-
-
- def get_canvas_width_height(self):
- 'return the canvas width and height in display coords'
- return self.width, self.height
-
- def get_text_width_height_descent(self, s, prop, ismath):
- """
- get the width and height in display coords of the string s
- with fontsize in points
- """
-
- size = prop.get_size_in_points()
- font = findfont(prop)
-
- scale = self.get_text_scale()
- try:
- llx, lly, lrx, lry, urx, ury, ulx, uly = \
- self.im.get_bounding_rect(
- font, scale*size, 0.0, (0,0), s)
- except ValueError:
- raise RuntimeError('Could not load font %s. Try setting TTFFONTPATH to include this font' % fontname)
-
- w = abs(lrx - llx)
- h = abs(lly - uly)
- return w, h, h
-
-
- def flipy(self):
- 'return true if y small numbers are top for renderer'
- return True
-
-
- def draw_arc(self, gc, rgbFace, x, y, width, height, angle1, angle2, rotation):
- """
- Draw an arc centered at x,y with width and height and angles
- from 0.0 to 360.0
- """
-
- center = int(x), self.height-int(y)
- wh = int(width), int(height)
- a1, a2 = int(angle1), int(angle2)
- if rgbFace is not None:
- color = self.get_gd_color( rgbFace )
- self.im.filledEllipse(
- center, wh, color)
- color = self.get_gd_color( gc.get_rgb() )
- self.im.arc(center, wh, a1, a2, color)
- self.flush_clip()
-
- def draw_line(self, gc, x1, y1, x2, y2):
- """
- Draw a single line from x1,y1 to x2,y2
- """
- self.draw_lines(gc, npy.array([x1, x2]), npy.array([y1, y2]))
-
- def draw_lines(self, gc, x, y):
- """
- x and y are equal length arrays, draw lines connecting each
- point in x, y
- """
-
- x = x.astype(npy.int16)
- y = self.height*npy.ones(y.shape, npy.int16) - y.astype(npy.int16)
- style = self._set_gd_style(gc)
- self.im.lines( zip(x,y), style)
- self.flush_clip()
-
- def draw_point(self, gc, x, y):
- """
- Draw a single point at x,y
- """
- self.im.setPixel((int(x),self.height-int(y)),
- self.get_gd_color( gc.get_rgb() ))
- self.flush_clip()
-
-
-
- def draw_polygon(self, gc, rgbFace, points):
- """
- Draw a polygon. points is a len vertices tuple, each element
- giving the x,y coords a vertex
- """
-
- edgecolor = self.get_gd_color( gc.get_rgb() )
-
- points = [(int(x), self.height-int(y)) for x,y in points]
-
-
- if rgbFace is not None:
- facecolor = self.get_gd_color( rgbFace )
- self.im.filledPolygon(points, facecolor)
- else: facecolor = None
- if edgecolor != facecolor:
- self.im.polygon(points, edgecolor)
- self.flush_clip()
-
- def draw_rectangle(self, gc, rgbFace, x, y, width, height):
- """
- Draw a rectangle at lower left x,y with width and height
- If filled=True, fill the rectangle with the gc foreground
- gc is a GraphicsContext instance
- """
-
- lb = int(x), self.height-int(y)
- ur = int(x+width), self.height-int((y+height))
- edgecolor = self.get_gd_color( gc.get_rgb() )
-
- if rgbFace is not None:
- facecolor = self.get_gd_color( rgbFace )
- self.im.filledRectangle(ur, lb, facecolor)
- else: facecolor = None
-
- if edgecolor != facecolor:
- self.im.rectangle(ur, lb, edgecolor)
- self.flush_clip()
-
- def draw_text(self, gc, x, y, s, prop, angle, ismath):
- """
- Render the text using the RendererGD instance
- """
-
- size = prop.get_size_in_points()
- font = findfont(prop)
-
- x = int(x)
- y = int(y)
-
- color = self.get_gd_color( gc.get_rgb() )
-
- angle *= math.pi/180.0
-
- scale = self.get_text_scale()
- self.im.string_ft(font, scale*size, angle,
- (x, y), s, color)
- self.flush_clip()
-
- def finish(self):
- pass
- #self.im.writePng( file('xx.png', 'w') )
-
-
- def flush_clip(self):
- imw, imh = self.im.size()
- lb = 0, 0
- ur = imw, imh
- self.im.setClip(ur, lb)
-
-
- def get_gd_color(self, rgb):
- """
- RGB is a unit RGB tuple, return a gd color
- """
-
- r,g,b = rgb
- rgbi = (int(r*255),int(g*255),int(b*255))
-
- try: return self._cached[rgbi]
- except KeyError: pass
-
- color = self.im.colorAllocate( rgbi )
-
- if color==-1:
- warnings.warn('Unable to allocate color %1.3f, %1.3f, %1.3f; using nearest neighbor' % rgb)
- color = self.im.colorClosest(rgbi)
-
- self._cached[rgbi] = color
- return color
-
-
-
-
- def get_text_scale(self):
- """
- Return the scale factor for fontsize taking screendpi and pixels per
- inch into account
- """
- return self.dpi.get()/PIXELS_PER_INCH
-
- def new_gc(self):
- """
- Return an instance of a GraphicsContextGD
- """
- return GraphicsContextGD( self.im, self )
-
- def _set_gd_style(self, gc):
- color = self.get_gd_color( gc.get_rgb() )
- offset, dashes = gc.get_dashes()
-
- if dashes is not None:
- pixels = self.points_to_pixels(dashes)
- style = []
- for on, off in pieces(pixels):
- if on<1: on = 1
- else: on = round(on)
- if off<1: off = 1
- else: off = round(off)
-
- style.extend([color]*on)
- style.extend([gd.gdTransparent]*off)
- self.im.setStyle(style)
- return gd.gdStyled
- else:
- if gc.get_antialiased():
- self.im.setAntiAliased(color)
- return gd.gdAntiAliased
- else:
- self.im.setStyle([color])
- return gd.gdStyled
-
-
- def points_to_pixels(self, points):
- """
- convert point measures to pixes using dpi and the pixels per
- inch of the display
- """
- return npy.asarray(points)*(PIXELS_PER_INCH/72.0*self.dpi.get()/72.0)
-
-
-class GraphicsContextGD(GraphicsContextBase):
- """
- The graphics context provides the color, line styles, etc... See
- the gtk and postscript backends for examples of mapping the
- graphics context attributes (cap styles, join styles, line widths,
- colors) to a particular backend. """
- def __init__(self, im, renderer):
- """
- Initialize with a gd image
- """
- GraphicsContextBase.__init__(self)
- self.im = im
- self.renderer = renderer
-
-
- def set_clip_rectangle(self, rectangle):
- GraphicsContextBase.set_clip_rectangle(self, rectangle)
- x,y,w,h = rectangle
- imw, imh = self.im.size()
- lb = int(x), imh-int(y)
- ur = int(x+w), imh-int(y+h)
- self.im.setClip(ur, lb)
-
- def set_linestyle(self, style):
- GraphicsContextBase.set_linestyle(self, style)
- offset, dashes = self.dashd[style]
- self.set_dashes(offset, dashes)
-
- def set_linewidth(self, lw):
- GraphicsContextBase.set_linewidth(self, lw)
- pixels = self.renderer.points_to_pixels(lw)
- if pixels<1: pixels = 1
- else: pixels = round(pixels)
- self.im.setThickness(pixels)
-
-########################################################################
-#
-# The following functions and classes are for matlab compatibility
-# mode (pylab) and implement figure managers, etc...
-#
-########################################################################
-
-
-def new_figure_manager(num, *args, **kwargs):
- """
- Add a new figure num (default autoincrement). For GUI
- backends, you'll need to instantiate a new window and embed
- the figure in it.
- """
- FigureClass = kwargs.pop('FigureClass', Figure)
- thisFig = FigureClass(*args, **kwargs)
- canvas = FigureCanvasGD(thisFig)
- manager = FigureManagerGD(canvas, num)
- return manager
-
-
-class FigureCanvasGD(FigureCanvasBase):
- filetypes = {'PNG': 'Portable Network Graphics'}
-
- def print_png(self, filename, *args, **kwargs):
- im = self.draw()
- im.writePng(filename)
-
- def get_default_filetype(self):
- return 'png'
-
- def draw(self):
- """
- Draw to a gd image and return the image instance
-
- """
-
- left, bottom, width, height = self.figure.bbox.get_bounds()
- im = gd.image((int(width), int(height)))
-
- if not hasattr(im, 'setAntiAliased'):
- raise RuntimeError('gd_requirements_failed')
- renderer = RendererGD(im, self.figure.dpi)
- self.figure.draw(renderer)
- renderer.finish()
-
- return im
-
-class FigureManagerGD(FigureManagerBase):
- """
- This class manages all the figures for matlab mode
- """
- pass
-
-
-
-########################################################################
-#
-# Now just provide the standard names that backend.__init__ is expecting
-#
-########################################################################
-
-FigureManager = FigureManagerGD
-
-
Deleted: trunk/matplotlib/lib/matplotlib/backends/backend_paint.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_paint.py 2007-09-07 20:43:20 UTC (rev 3816)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_paint.py 2007-09-08 23:53:06 UTC (rev 3817)
@@ -1,281 +0,0 @@
-"""
-This ia a paint (libart) backend
-
-You can select it as a backend with
-
- import matplotlib
- matplotlib.use('Paint')
-
-REQUIREMENTS
-
- backend_paint requires pypaint-0.??, which in turn requires
- libart and freetype1
-"""
-
-from __future__ import division
-import sys
-import os
-import paint
-
-import numpy as npy
-
-from matplotlib import verbose
-
-from matplotlib._pylab_helpers import Gcf
-from matplotlib.backend_bases import RendererBase,\
- GraphicsContextBase, FigureCanvasBase, FigureManagerBase
-from matplotlib.cbook import enumerate
-from matplotlib.figure import Figure
-from matplotlib.text import Text, _process_text_args
-
-from matplotlib.font_manager import findfont
-
-"""
-
- * added dpi instance to renderer so drawing could scale with dpi
-
- * added dash path - JDH
-
- * reversed the order of fill and stroke for rectangle, arc and
- polygon so edge color would be visible
-
- * adjusted circle centers
-
-"""
-
-
-
-
-
-#paint/font.c defined dpi as 96
-PIXELS_PER_INCH = 96 # a constant used to scale text with dpi
-
-
-class RendererPaint(RendererBase):
- """
- The renderer handles all the drawing primitives using a graphics
- context instance that controls the colors/styles
- """
-
- fontd = {} # cache paint font instances
-
- def __init__(self, width, height, dpi):
- """creates a new image"""
- w, h = int(width), int(height)
- self.image = paint.image(w, h)
- self.width, self.height = w, h
- self.dpi = dpi # for scaling dashes, linewidths
-
- def get_canvas_width_height(self):
- 'return the canvas width and height in display coords'
- return self.width, self.height
-
- def get_text_width_height(self, s, prop, ismath):
- """
- get the width and height in display coords of the string s
- with fontsize in points
- """
- font = self._get_paint_font(s, prop, 0.0)
- return font.textsize(s)
-
- def flipy(self):
- 'return true if y small numbers are top for renderer'
- return True
-
-
- def get_text_scale(self):
- """
- Return the scale factor for fontsize taking screendpi and pixels per
- inch into account
- """
- return self.dpi.get()/PIXELS_PER_INCH
-
-
-
- def draw_text(self, gc, x, y, s, prop, angle, ismath):
- """
- Render the text using the RendererPaint instance
- """
- font = self._get_paint_font(s, prop, angle)
-
- text_color = self.get_paint_color(gc.get_rgb())
- self.image.text(font, x, y, text_color, s)
-
- def _get_paint_font(self, s, prop, angle):
- """
- Get the paint font for text instance t, cacheing for efficiency
- """
-
- fname = findfont(prop)
- size = self.get_text_scale() * prop.get_size_in_points()
-
- props = fname, size, angle
-
- font = self.fontd.get(props)
- if font is None:
- font = paint.font(*props)
- self.fontd[props] = font
- return font
-
- def get_paint_color(self, rgb):
- """returns a paint color object based on the given rgb tuple"""
- r,g,b = rgb
- return paint.rgb(int(r*255),int(g*255),int(b*255))
-
- def draw_arc(self, gcEdge, rgbFace, x, y, width, height, angle1, angle2, rotation):
- """
- Draw an arc centered at x,y with width and height and angles
- from 0.0 to 360.0.
-
- If rgbFace is not None, fill the rectangle with it. gcEdge
- is a GraphicsContext instance
- """
- arc = paint.arc(x-0.5*width, self.height - (y-0.5*height),
- x+0.5*width, self.height - (y+0.5*height),
- angle1, angle2)
- if rgbFace:
- self.image.fill(arc, self.get_paint_color(rgbFace))
- self.image.stroke(arc, self.get_paint_color(gcEdge.get_rgb()),
- self.points_to_pixels(gcEdge.get_linewidth()))
-
-
- def draw_line(self, gc, x1, y1, x2, y2):
- """
- Draw a single line from x1,y1 to x2,y2
- """
- path = paint.line(x1, self.height - y1, x2, self.height - y2)
- path = self.dash_path(gc, path)
- self.image.stroke(path, \
- self.get_paint_color(gc.get_rgb()),
- self.points_to_pixels(gc.get_linewidth()))
-
-
- def dash_path(self, gc, path):
- """
- Add dashes to the path and return it if dashes are set
- """
- offset, dashes = gc.get_dashes()
- if dashes is not None:
-
- dashes = tuple(self.points_to_pixels(npy.asarray(dashes)))
- return path.dash(offset, dashes)
- else:
- return path
-
- def draw_lines(self, gc, x, y):
- """
- x and y are equal length arrays, draw lines connecting each
- point in x, y
- """
- assert(len(x)==len(y))
- # faster as a list comp
-
- path = [(paint.MOVETO, x[0], self.height-y[0])]
- path.extend( [ (paint.LINETO, x[i], self.height-y[i]) for i in range(1, len(x))])
-
- path = self.dash_path(gc, paint.make_path(path))
- self.image.stroke(path,
- self.get_paint_color(gc.get_rgb()),
- self.points_to_pixels(gc.get_linewidth()))
-
-
- def draw_polygon(self, gcEdge, rgbFace, points):
- """
- Draw a polygon. points is a len vertices tuple, each element
- giving the x,y coords a vertex.
-
- If rgbFace is not None, fill the rectangle with it. gcEdge
- is a GraphicsContext instance
- """
- x = [p[0] for p in points]
- y = [p[1] for p in points]
- path = [(paint.MOVETO, x[0], self.height - y[0])]
- for i in range(len(x)-1):
- path.append((paint.LINETO, x[i+1], self.height - y[i+1]))
- path.append((paint.LINETO, x[0], self.height - y[0]))
- path = paint.make_path(path)
-
- if rgbFace:
- self.image.fill(path, self.get_paint_color(rgbFace))
- self.image.stroke(path,
- self.get_paint_color(gcEdge.get_rgb()),
- self.points_to_pixels(gcEdge.get_linewidth()))
- def draw_rectangle(self, gcEdge, rgbFace, x, y, width, height):
- """
- Draw a rectangle at lower left x,y with width and height.
-
- If rgbFace is not None, fill the rectangle with it. gcEdge
- is a GraphicsContext instance
- """
- path = paint.rect(x, self.height - y, x+width, self.height - (y+height))
-
- if rgbFace:
- self.image.fill(path, self.get_paint_color(rgbFace))
- self.image.stroke(path,
- self.get_paint_color(gcEdge.get_rgb()),
- self.points_to_pixels(gcEdge.get_linewidth()))
-
- def draw_point(self, gc, x, y):
- """
- Draw a single point at x,y
- """
- self.image.stroke(
- paint.line(x, self.height - y, x, self.height - y),
- self.get_paint_color(gc.get_rgb()),
- self.points_to_pixels(gc.get_linewidth()))
-
- def points_to_pixels(self, points):
- return points*(PIXELS_PER_INCH/72.0*self.dpi.get()/72.0)
-
-
-
-class FigureCanvasPaint(FigureCanvasBase):
-
- def draw(self):
- """
- Render the figure using RendererPaint instance renderer
- """
- t1,t2,width,height = self.figure.bbox.get_bounds()
- renderer = RendererPaint(width,height, self.figure.dpi)
- self.figure.draw(renderer)
- return renderer
-
- filetypes = {'png': 'Portable Network Graphics'}
-
- def print_png(self, filename, *args, **kwargs):
- renderer = self.draw()
- renderer.image.write_png(filename)
-
- def get_default_filetype(self):
- return 'png'
-
-########################################################################
-#
-# The following functions and classes are for matlab compatibility
-# mode (pylab) and implement window/figure managers,
-# etc...
-#
-########################################################################
-
-
-def new_figure_manager_paint(num, *args, **kwargs):
- """
- Add a new figure num (default autoincrement). For GUI
- backends, you'll need to instantiate a new window and embed
- the figure in it.
- """
- FigureClass = kwargs.pop('FigureClass', Figure)
- thisFig = FigureClass(*args, **kwargs)
- canvas = FigureCanvasPaint(thisFig)
- manager = FigureManagerBase(canvas, num)
- return manager
-
-
-########################################################################
-#
-# Now just provide the standard names that backend.__init__ is expecting
-#
-########################################################################
-new_figure_manager = new_figure_manager_paint
-
-
Modified: trunk/matplotlib/setupext.py
===================================================================
--- trunk/matplotlib/setupext.py 2007-09-07 20:43:20 UTC (rev 3816)
+++ trunk/matplotlib/setupext.py 2007-09-08 23:53:06 UTC (rev 3817)
@@ -130,7 +130,7 @@
def print_line(*args, **kwargs):
pass
print_status = print_message = print_raw = print_line
-
+
class CleanUpFile:
"""CleanUpFile deletes the specified filename when self is destroyed."""
def __init__(self, name):
@@ -174,7 +174,7 @@
has_pkgconfig.cache = (status == 0)
return has_pkgconfig.cache
has_pkgconfig.cache = None
-
+
def get_pkgconfig(module,
packages,
flags="--libs --cflags",
@@ -189,7 +189,7 @@
'-l': 'libraries',
'-D': 'define_macros',
'-U': 'undef_macros'}
-
+
status, output = commands.getstatusoutput(
"%s %s %s" % (pkg_config_exec, flags, packages))
if status == 0:
@@ -247,7 +247,7 @@
", ".join(["'%s'" % x for x in module.include_dirs]))
return True
-
+
def check_for_libpng():
module = Extension("test", [])
get_pkgconfig(module, 'libpng')
@@ -260,7 +260,7 @@
", ".join(["'%s'" % x for x in module.include_dirs]))
return True
-
+
def add_base_flags(module):
incdirs = filter(os.path.exists,
[os.path.join(p, 'include') for p in basedir[sys.platform] ])
@@ -318,7 +318,7 @@
return False
else:
print_status("Cairo", cairo.version)
-
+
def check_for_numpy():
gotit = False
try:
@@ -357,16 +357,12 @@
# put these later for correct link order
module.libraries.extend(std_libs)
-def add_gd_flags(module):
- 'Add the module flags to build extensions which use gd'
- module.libraries.append('gd')
-
def add_ft2font_flags(module):
'Add the module flags to ft2font extension'
if not get_pkgconfig(module, 'freetype2'):
module.libraries.extend(['freetype', 'z'])
add_base_flags(module)
-
+
basedirs = module.include_dirs[:] # copy the list to avoid inf loop!
for d in basedirs:
module.include_dirs.append(os.path.join(d, 'freetype2'))
@@ -381,7 +377,7 @@
if os.path.exists(p): module.library_dirs.append(p)
else:
add_base_flags(module)
-
+
if sys.platform == 'win32' and win32_compiler == 'mingw32':
module.libraries.append('gw32c')
@@ -417,7 +413,7 @@
def ver2str(tup):
return ".".join([str(x) for x in tup])
-
+
if gotit:
import gobject
if hasattr(gobject, 'pygobject_version'):
@@ -432,7 +428,7 @@
if explanation is not None:
print_message(explanation)
-
+
return gotit
def add_pygtk_flags(module):
@@ -459,26 +455,26 @@
])
add_base_flags(module)
-
+
if not os.environ.has_key('PKG_CONFIG_PATH'):
# If Gtk+ is installed, pkg-config is required to be installed
os.environ['PKG_CONFIG_PATH'] = 'C:\GTK\lib\pkgconfig'
-
- pygtkIncludes = getoutput('pkg-config --cflags-only-I pygtk-2.0').split()
- gtkIncludes = getoutput('pkg-config --cflags-only-I gtk+-2.0').split()
- includes = pygtkIncludes + gtkIncludes
- module.include_dirs.extend([include[2:] for include in includes])
-
- pygtkLinker = getoutput('pkg-config --libs pygtk-2.0').split()
- gtkLinker = getoutput('pkg-config --libs gtk+-2.0').split()
+
+ pygtkIncludes = getoutput('pkg-config --cflags-only-I pygtk-2.0').split()
+ gtkIncludes = getoutput('pkg-config --cflags-only-I gtk+-2.0').split()
+ includes = pygtkIncludes + gtkIncludes
+ module.include_dirs.extend([include[2:] for include in includes])
+
+ pygtkLinker = getoutput('pkg-config --libs pygtk-2.0').split()
+ gtkLinker = getoutput('pkg-config --libs gtk+-2.0').split()
linkerFlags = pygtkLinker + gtkLinker
-
+
module.libraries.extend(
[flag[2:] for flag in linkerFlags if flag.startswith('-l')])
-
+
module.library_dirs.extend(
[flag[2:] for flag in linkerFlags if flag.startswith('-L')])
-
+
module.extra_link_args.extend(
[flag for flag in linkerFlags if not
(flag.startswith('-l') or flag.startswith('-L'))])
@@ -544,7 +540,7 @@
if explanation is not None:
print_message(explanation)
return gotit
-
+
def find_wx_config():
"""If the WX_CONFIG environment variable has been set, returns it value.
Otherwise, search for `wx-config' in the PATH directories and return the
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2007-09-09 22:41:38
|
Revision: 3819
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3819&view=rev
Author: efiring
Date: 2007-09-09 15:41:36 -0700 (Sun, 09 Sep 2007)
Log Message:
-----------
Factored plotting part of pylab.py into pyplot.py
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/boilerplate.py
trunk/matplotlib/examples/rc_traits.py
trunk/matplotlib/lib/matplotlib/__init__.py
trunk/matplotlib/lib/matplotlib/config/mplconfig.py
trunk/matplotlib/lib/matplotlib/config/rcsetup.py
trunk/matplotlib/lib/matplotlib/mlab.py
trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf
trunk/matplotlib/lib/matplotlib/pylab.py
Added Paths:
-----------
trunk/matplotlib/lib/matplotlib/pyplot.py
Removed Paths:
-------------
trunk/matplotlib/examples/gdtest.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2007-09-09 00:41:17 UTC (rev 3818)
+++ trunk/matplotlib/CHANGELOG 2007-09-09 22:41:36 UTC (rev 3819)
@@ -1,3 +1,12 @@
+2007-09-09 Split out the plotting part of pylab and put it in
+ pyplot.py; removed numerix from the remaining pylab.py,
+ which imports everything from pyplot.py. The intention
+ is that apart from cleanups, the result of importing
+ from pylab is nearly unchanged, but there is the
+ new alternative of importing from pyplot to get
+ the state-engine graphics without all the numeric
+ functions. - EF
+
2007-09-08 Eliminated gd and paint backends - EF
2007-09-06 .bmp file format is now longer an alias for .raw
@@ -8,12 +17,12 @@
Now it doesn't crash Preview.app. - JKS
2007-09-06 Refactored image saving code so that all GUI backends can
- save most image types. See FILETYPES for a matrix of
- backends and their supported file types.
- Backend canvases should no longer write their own print_figure()
- method -- instead they should write a print_xxx method for
- each filetype they can output and add an entry to their
- class-scoped filetypes dictionary. - MGD
+ save most image types. See FILETYPES for a matrix of
+ backends and their supported file types.
+ Backend canvases should no longer write their own print_figure()
+ method -- instead they should write a print_xxx method for
+ each filetype they can output and add an entry to their
+ class-scoped filetypes dictionary. - MGD
2007-09-05 Fixed Qt version reporting in setupext.py - DSD
Modified: trunk/matplotlib/boilerplate.py
===================================================================
--- trunk/matplotlib/boilerplate.py 2007-09-09 00:41:17 UTC (rev 3818)
+++ trunk/matplotlib/boilerplate.py 2007-09-09 22:41:36 UTC (rev 3819)
@@ -29,7 +29,7 @@
return ret
if Axes.%(func)s.__doc__ is not None:
%(func)s.__doc__ = dedent(Axes.%(func)s.__doc__) + \"\"\"
-Addition kwargs: hold = [True|False] overrides default hold state\"\"\"
+Additional kwargs: hold = [True|False] overrides default hold state\"\"\"
"""
_fmtmisc = """\
@@ -74,6 +74,8 @@
'plot',
'plot_date',
'psd',
+ 'quiver',
+ 'quiverkey',
'scatter',
'semilogx',
'semilogy',
@@ -82,8 +84,6 @@
'stem',
'step',
'vlines',
- 'quiver',
- 'quiverkey',
'xcorr',
)
@@ -104,7 +104,6 @@
'pcolormesh' : 'gci._current = ret',
'imshow' : 'gci._current = ret',
'spy' : 'gci._current = ret',
- 'quiver2' : 'gci._current = ret',
'quiver' : 'gci._current = ret',
'specgram' : 'gci._current = ret[-1]',
@@ -129,11 +128,13 @@
# This function was autogenerated by boilerplate.py. Do not edit as
# changes will be lost
def %(name)s():
- 'set the default colormap to %(name)s and apply to current image if any. See help(colormaps) for more information'
+ '''
+ set the default colormap to %(name)s and apply to current image if any.
+ See help(colormaps) for more information
+ '''
rc('image', cmap='%(name)s')
im = gci()
-
if im is not None:
im.set_cmap(cm.%(name)s)
draw_if_interactive()
Deleted: trunk/matplotlib/examples/gdtest.py
===================================================================
--- trunk/matplotlib/examples/gdtest.py 2007-09-09 00:41:17 UTC (rev 3818)
+++ trunk/matplotlib/examples/gdtest.py 2007-09-09 22:41:36 UTC (rev 3819)
@@ -1,34 +0,0 @@
-#!/usr/bin/env python
-import matplotlib
-matplotlib.use('GD')
-from pylab import *
-
-def f(t):
- s1 = cos(2*pi*t)
- e1 = exp(-t)
- return multiply(s1,e1)
-
-t1 = arange(0.0, 5.0, .1)
-t2 = arange(0.0, 5.0, 0.02)
-t3 = arange(0.0, 2.0, 0.01)
-
-
-if 1:
- subplot(211)
- l = plot(t1, f(t1), 'k-^')
- setp(l, 'markerfacecolor', 'r')
- xlim(0,5)
- title('A tale of 2 subplots', fontsize=12)
- ylabel('Signal 1', fontsize=10)
-
- subplot(212)
- l = plot(t1, f(t1), 'k->')
- xlim(0,5)
- ylabel('Signal 2', fontsize=10)
- xlabel('time (s)', fontsize=10, fontname='Courier')
-
-ax = gca()
-
-
-#savefig('gdtest', dpi=150)
-show()
Modified: trunk/matplotlib/examples/rc_traits.py
===================================================================
--- trunk/matplotlib/examples/rc_traits.py 2007-09-09 00:41:17 UTC (rev 3818)
+++ trunk/matplotlib/examples/rc_traits.py 2007-09-09 22:41:36 UTC (rev 3819)
@@ -128,8 +128,8 @@
antialiased = flexible_true_trait
timezones = 'UTC', 'US/Central', 'ES/Eastern' # fixme: and many more
-backends = ('GTKAgg', 'Cairo', 'FltkAgg', 'GD', 'GDK', 'GTK', 'Agg',
- 'GTKCairo', 'Paint', 'PS', 'SVG', 'Template', 'TkAgg',
+backends = ('GTKAgg', 'Cairo', 'FltkAgg', 'GDK', 'GTK', 'Agg',
+ 'GTKCairo', 'PS', 'SVG', 'Template', 'TkAgg',
'WX')
class RC(traits.HasTraits):
Modified: trunk/matplotlib/lib/matplotlib/__init__.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/__init__.py 2007-09-09 00:41:17 UTC (rev 3818)
+++ trunk/matplotlib/lib/matplotlib/__init__.py 2007-09-09 22:41:36 UTC (rev 3819)
@@ -530,16 +530,16 @@
class RcParams(dict):
-
+
"""A dictionary object including validation
-
+
validating functions are defined and associated with rc parameters in
rcsetup.py
"""
-
+
validate = dict([ (key, converter) for key, (default, converter) in \
defaultParams.iteritems() ])
-
+
def __setitem__(self, key, val):
try:
if key in _deprecated_map.keys():
@@ -620,7 +620,7 @@
ret['datapath'] = get_data_path()
verbose.report('loaded rc file %s'%fname)
-
+
return ret
Modified: trunk/matplotlib/lib/matplotlib/config/mplconfig.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2007-09-09 00:41:17 UTC (rev 3818)
+++ trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2007-09-09 22:41:36 UTC (rev 3819)
@@ -39,7 +39,7 @@
key = val optional comment
val should be valid python syntax, just as you would use when setting
- properties using rcParams. This should become more obvious by inspecting
+ properties using rcParams. This should become more obvious by inspecting
the default values listed herein.
Colors: for the color values below, you can either use
@@ -50,7 +50,7 @@
- a legal html color name, eg red, blue, darkslategray
Interactivity: see http://matplotlib.sourceforge.net/interactive.html.
-
+
### CONFIGURATION BEGINS HERE ###
"""
@@ -61,15 +61,15 @@
numerix = T.Trait('numpy', 'numpy', 'numeric', 'numarray')
maskedarray = T.false
units = T.false
-
+
class backend(TConfig):
"""Valid backends are: 'GTKAgg', 'GTKCairo', 'QtAgg', 'Qt4Agg',
'TkAgg', 'Agg', 'Cairo', 'PS', 'PDF', 'SVG'"""
use = T.Trait('TkAgg', mplT.BackendHandler())
-
+
class cairo(TConfig):
format = T.Trait('png', 'png', 'ps', 'pdf', 'svg')
-
+
class tk(TConfig):
"""
window_focus : Maintain shell focus for TkAgg
@@ -78,7 +78,7 @@
window_focus = T.false
pythoninspect = T.false
-
+
class ps(TConfig):
papersize = T.Trait('letter', 'auto', 'letter', 'legal', 'ledger',
'A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7',
@@ -87,22 +87,22 @@
'B8', 'B9', 'B10')
useafm = T.false
fonttype = T.Trait(3, 42)
-
+
class distiller(TConfig):
use = T.Trait(None, None, 'ghostscript', 'xpdf', False)
resolution = T.Float(6000)
-
+
class pdf(TConfig):
compression = T.Range(0, 9, 6)
fonttype = T.Trait(3, 42)
inheritcolor = T.false
use14corefonts = T.false
-
+
class svg(TConfig):
image_inline = T.true
image_noscale = T.false
embed_chars = T.true
-
+
class lines(TConfig):
linewidth = T.Float(1.0)
linestyle = T.Trait('-','--','-.', ':', 'steps', '', ' ', None)
@@ -122,10 +122,10 @@
linewidth = T.Float(1.0)
facecolor = T.Trait('blue', mplT.ColorHandler())
edgecolor = T.Trait('black', mplT.ColorHandler())
- antialiased = T.true
+ antialiased = T.true
class font(TConfig):
- family = T.Trait('sans-serif', 'sans-serif', 'serif', 'cursive',
+ family = T.Trait('sans-serif', 'sans-serif', 'serif', 'cursive',
'fantasy', 'monospace')
style = T.Trait('normal', 'normal', 'italic', 'oblique')
variant = T.Trait('normal', 'normal', 'small-caps')
@@ -136,16 +136,16 @@
'expanded', 'extra-expanded', 'ultra-expanded',
'wider', 'narrower')
size = T.Float(12.0)
- serif = T.ListStr(["Bitstream Vera Serif", "New Century Schoolbook",
- "Century Schoolbook L", "Utopia", "ITC Bookman", "Bookman",
- "Nimbus Roman No9 L", "Times New Roman", "Times", "Palatino",
+ serif = T.ListStr(["Bitstream Vera Serif", "New Century Schoolbook",
+ "Century Schoolbook L", "Utopia", "ITC Bookman", "Bookman",
+ "Nimbus Roman No9 L", "Times New Roman", "Times", "Palatino",
"Charter", "serif"])
- sans_serif = T.ListStr(["Bitstream Vera Sans", "Lucida Grande", "Verdana",
- "Geneva", "Lucid", "Arial", "Helvetica", "Avant Garde",
+ sans_serif = T.ListStr(["Bitstream Vera Sans", "Lucida Grande", "Verdana",
+ "Geneva", "Lucid", "Arial", "Helvetica", "Avant Garde",
"sans-serif"])
- cursive = T.ListStr(["Apple Chancery", "Textile", "Zapf Chancery", "Sand",
+ cursive = T.ListStr(["Apple Chancery", "Textile", "Zapf Chancery", "Sand",
"cursive"])
- fantasy = T.ListStr(["Comic Sans MS", "Chicago", "Charcoal", "Impact", "Western",
+ fantasy = T.ListStr(["Comic Sans MS", "Chicago", "Charcoal", "Impact", "Western",
"fantasy"])
monospace = T.ListStr(["Bitstream Vera Sans Mono", "Andale Mono", "Nimbus Mono L",
"Courier New", "Courier", "Fixed", "Terminal", "monospace"])
@@ -153,12 +153,12 @@
class text(TConfig):
color = T.Trait('black',mplT.ColorHandler())
usetex = T.false
-
+
class latex(TConfig):
unicode = T.false
preamble = T.ListStr([])
dvipnghack = T.false
-
+
class mathtext(TConfig):
cal = T.Trait('cursive' , mplT.FontconfigPatternHandler())
rm = T.Trait('serif' , mplT.FontconfigPatternHandler())
@@ -182,16 +182,16 @@
'large', 'x-large', 'xx-large', T.Float)
labelcolor = T.Trait('black', mplT.ColorHandler())
axisbelow = T.false
-
+
class formatter(TConfig):
limits = T.List(T.Float, [-7, 7], minlen=2, maxlen=2)
-
+
class xticks(TConfig):
color = T.Trait('black', mplT.ColorHandler())
labelsize = T.Trait('small', 'xx-small', 'x-small', 'small', 'medium',
'large', 'x-large', 'xx-large', T.Float)
direction = T.Trait('in', 'out')
-
+
class major(TConfig):
size = T.Float(4)
pad = T.Float(4)
@@ -205,7 +205,7 @@
labelsize = T.Trait('small', 'xx-small', 'x-small', 'small', 'medium',
'large', 'x-large', 'xx-large', T.Float)
direction = T.Trait('in', 'out')
-
+
class major(TConfig):
size = T.Float(4)
pad = T.Float(4)
@@ -220,8 +220,8 @@
linewidth = T.Float(0.5)
class legend(TConfig):
- loc = T.Trait('upper right', 'best', 'upper right', 'upper left',
- 'lower left', 'lower right', 'right', 'center left',
+ loc = T.Trait('upper right', 'best', 'upper right', 'upper left',
+ 'lower left', 'lower right', 'right', 'center left',
'center right', 'lower center', 'upper center', 'center')
isaxes = T.true
numpoints = T.Int(3)
@@ -264,26 +264,26 @@
class contour(TConfig):
negative_linestyle = T.Trait('dashed', 'dashed', 'solid')
-
+
class savefig(TConfig):
dpi = T.Float(100)
facecolor = T.Trait('white', mplT.ColorHandler())
edgecolor = T.Trait('white', mplT.ColorHandler())
orientation = T.Trait('portrait', 'portrait', 'landscape')
-
+
class verbose(TConfig):
level = T.Trait('silent', 'silent', 'helpful', 'debug', 'debug-annoying')
fileo = T.Trait('sys.stdout', 'sys.stdout', T.File)
class RcParamsWrapper(dict):
-
+
"""A backwards-compatible interface to a traited config object
"""
-
+
def __init__(self, tconfig):
self.tconfig = tconfig
-
+
self.tconfig_map = {
'backend' : (self.tconfig.backend, 'use'),
'numerix' : (self.tconfig, 'numerix'),
@@ -337,7 +337,7 @@
'text.latex.unicode' : (self.tconfig.text.latex, 'unicode'),
'text.latex.preamble' : (self.tconfig.text.latex, 'preamble'),
'text.dvipnghack' : (self.tconfig.text.latex, 'dvipnghack'),
-
+
'mathtext.cal' : (self.tconfig.mathtext, 'cal'),
'mathtext.rm' : (self.tconfig.mathtext, 'rm'),
'mathtext.tt' : (self.tconfig.mathtext, 'tt'),
@@ -455,7 +455,7 @@
def keys(self):
return self.tconfig_map.keys()
-
+
def has_key(self, val):
return self.tconfig_map.has_key(val)
@@ -466,7 +466,7 @@
except AttributeError:
for key, val in arg:
self[key] = val
-
+
for key in kwargs:
self[key] = kwargs[key]
Modified: trunk/matplotlib/lib/matplotlib/config/rcsetup.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/config/rcsetup.py 2007-09-09 00:41:17 UTC (rev 3818)
+++ trunk/matplotlib/lib/matplotlib/config/rcsetup.py 2007-09-09 22:41:36 UTC (rev 3819)
@@ -70,8 +70,8 @@
return fonttype
validate_backend = ValidateInStrings('backend',[
- 'Agg2', 'Agg', 'Aqt', 'Cairo', 'CocoaAgg', 'EMF', 'GD', 'GDK',
- 'GTK', 'GTKAgg', 'GTKCairo', 'FltkAgg', 'Paint', 'Pdf', 'PS',
+ 'Agg2', 'Agg', 'Aqt', 'Cairo', 'CocoaAgg', 'EMF', 'GDK',
+ 'GTK', 'GTKAgg', 'GTKCairo', 'FltkAgg', 'Pdf', 'PS',
'QtAgg', 'Qt4Agg', 'SVG', 'Template', 'TkAgg', 'WX', 'WXAgg',
], ignorecase=True)
@@ -143,7 +143,7 @@
if len(s)==6 and s.isalnum(): # looks like hex
return '#' + s
-
+
if len(s)==7 and s.startswith('#') and s[1:].isalnum():
return s
@@ -198,11 +198,11 @@
return float(s)
except ValueError:
raise ValueError('not a valid font size')
-
+
def validate_font_properties(s):
parse_fontconfig_pattern(s)
return s
-
+
validate_verbose = ValidateInStrings('verbose',[
'silent', 'helpful', 'debug', 'debug-annoying',
])
@@ -367,7 +367,7 @@
'mathtext.sf' : ['sans\-serif', validate_font_properties],
'mathtext.use_cm' : [True, validate_bool],
'mathtext.fallback_to_cm' : [True, validate_bool],
-
+
'image.aspect' : ['equal', validate_aspect], # equal, auto, a number
'image.interpolation' : ['bilinear', str],
'image.cmap' : ['jet', str], # one of gray, jet, etc
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2007-09-09 00:41:17 UTC (rev 3818)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2007-09-09 22:41:36 UTC (rev 3819)
@@ -1937,7 +1937,7 @@
return npy.max(npy.sum(npy.absolute((npy.transpose(x))), axis=0))
elif y=='fro':
xx = npy.dot(x.transpose(), x)
- return npy.sqrt(asum(npy.diag(xx), axis=0))
+ return npy.sqrt(npy.sum(npy.diag(xx), axis=0))
else:
raise ValueError('Second argument not permitted for matrices')
Modified: trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf
===================================================================
--- trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf 2007-09-09 00:41:17 UTC (rev 3818)
+++ trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf 2007-09-09 22:41:36 UTC (rev 3819)
@@ -3,32 +3,32 @@
# This is a sample matplotlib configuration file. It should be placed
# in HOME/.matplotlib/matplotlibrc (unix/linux like systems) and
# C:\Documents and Settings\yourname\.matplotlib (win32 systems)
-#
+#
# By default, the installer will overwrite the existing file in the install
# path, so if you want to preserve yours, please move it to your HOME dir and
# set the environment variable if necessary.
-#
+#
# This file is best viewed in a editor which supports ini or conf mode syntax
# highlighting.
-#
+#
# Blank lines, or lines starting with a comment symbol, are ignored,
# as are trailing comments. Other lines must have the format
-#
+#
# key = val optional comment
-#
+#
# val should be valid python syntax, just as you would use when setting
-# properties using rcParams. This should become more obvious by inspecting
+# properties using rcParams. This should become more obvious by inspecting
# the default values listed herein.
-#
+#
# Colors: for the color values below, you can either use
# - a matplotlib color string, such as r, k, or b
# - an rgb tuple, such as (1.0, 0.5, 0.0)
# - a hex string, such as #ff00ff or ff00ff
# - a scalar grayscale intensity such as 0.75
# - a legal html color name, eg red, blue, darkslategray
-#
+#
# Interactivity: see http://matplotlib.sourceforge.net/interactive.html.
-#
+#
# ### CONFIGURATION BEGINS HERE ###
# a value of type 'str'
@@ -42,7 +42,7 @@
# 'Africa/Abidjan' or 'Africa/Accra' or 'Africa/Addis_Ababa' or 'Africa/Algiers'
# or 'Africa/Asmara' or 'Africa/Asmera' or 'Africa/Bamako' or 'Africa/Bangui' o
# r 'Africa/Banjul' or 'Africa/Bissau' or 'Africa/Blantyre' or 'Africa/Brazzavil
-# <...snipped 10590 chars...>
+# <...snipped 10590 chars...>
# or 'Turkey' or 'UCT' or 'US/Alaska' or 'US/Aleutian' or 'US/Arizona' or 'US/Ce
# ntral' or 'US/East-Indiana' or 'US/Eastern' or 'US/Hawaii' or 'US/Indiana-Star
# ke' or 'US/Michigan' or 'US/Mountain' or 'US/Pacific' or 'US/Pacific-New' or '
@@ -72,14 +72,14 @@
# name like 'orange', a hex color like '#efefef', a grayscale intensity
# like '0.5', or an RGBA tuple (1,0,0,1)
labelcolor = 'black'
- # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium'
+ # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium'
# or 'large' or 'x-large' or 'xx-large'
labelsize = 'medium'
# a value of type 'float'
linewidth = 1.0
# one of 0, on, false, 1, no, n, y, off, yes, true
polargrid = True
- # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium'
+ # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium'
# or 'large' or 'x-large' or 'xx-large'
titlesize = 'large'
@@ -191,7 +191,7 @@
serif = ['Bitstream Vera Serif', 'New Century Schoolbook', 'Century Schoolbook L', 'Utopia', 'ITC Bookman', 'Bookman', 'Nimbus Roman No9 L', 'Times New Roman', 'Times', 'Palatino', 'Charter', 'serif']
# a value of type 'float'
size = 12.0
- # 'ultra-condensed' or 'extra-condensed' or 'condensed' or 'semi-condensed'
+ # 'ultra-condensed' or 'extra-condensed' or 'condensed' or 'semi-condensed'
# or 'normal' or 'semi-expanded' or 'expanded' or 'extra-expanded' or 'ultra
# -expanded' or 'wider' or 'narrower'
stretch = 'normal'
@@ -218,11 +218,11 @@
aspect = 'equal'
# 'Accent' or 'Accent_r' or 'Blues' or 'Blues_r' or 'BrBG' or 'BrBG_r' or 'B
# uGn' or 'BuGn_r' or 'BuPu' or 'BuPu_r' or 'Dark2' or 'Dark2_r' or 'GnBu' o
- # r 'GnBu_r' or 'Greens' or 'Greens_r' or 'Greys' or 'Greys_r' or 'OrRd' or
- # <...snipped 1010 chars...>
- # ist_stern' or 'gist_stern_r' or 'gist_yarg' or 'gist_yarg_r' or 'gray' or
+ # r 'GnBu_r' or 'Greens' or 'Greens_r' or 'Greys' or 'Greys_r' or 'OrRd' or
+ # <...snipped 1010 chars...>
+ # ist_stern' or 'gist_stern_r' or 'gist_yarg' or 'gist_yarg_r' or 'gray' or
# 'gray_r' or 'hot' or 'hot_r' or 'hsv' or 'hsv_r' or 'jet' or 'jet_r' or 'p
- # ink' or 'pink_r' or 'prism' or 'prism_r' or 'spectral' or 'spectral_r' or
+ # ink' or 'pink_r' or 'prism' or 'prism_r' or 'spectral' or 'spectral_r' or
# 'spring' or 'spring_r' or 'summer' or 'summer_r' or 'winter' or 'winter_r'
cmap = 'jet'
# 'bilinear' or 'nearest' or 'bicubic' or 'spline16' or 'spline36' or 'hanni
@@ -237,7 +237,7 @@
[legend]
# a value of type 'float'
axespad = 0.02
- # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium'
+ # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium'
# or 'large' or 'x-large' or 'xx-large'
fontsize = 'medium'
# a value of type 'float'
@@ -362,7 +362,7 @@
color = 'black'
# 'in' or 'out'
direction = 'in'
- # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium'
+ # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium'
# or 'large' or 'x-large' or 'xx-large'
labelsize = 'small'
@@ -385,7 +385,7 @@
color = 'black'
# 'in' or 'out'
direction = 'in'
- # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium'
+ # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium'
# or 'large' or 'x-large' or 'xx-large'
labelsize = 'small'
@@ -399,4 +399,4 @@
# a value of type 'float'
pad = 4.0
# a value of type 'float'
- size = 2.0
\ No newline at end of file
+ size = 2.0
Modified: trunk/matplotlib/lib/matplotlib/pylab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/pylab.py 2007-09-09 00:41:17 UTC (rev 3818)
+++ trunk/matplotlib/lib/matplotlib/pylab.py 2007-09-09 22:41:36 UTC (rev 3819)
@@ -124,7 +124,7 @@
fliplr - flip the rows of a matrix up/down
flipud - flip the columns of a matrix left/right
linspace - a linear spaced vector of N values from min to max inclusive
- logspace - a log spaced vector of N values from min to max inclusive
+ logspace - a log spaced vector of N values from min to max inclusive
meshgrid - repeat x and y to make regular matrices
ones - an array of ones
rand - an array from the uniform distribution [0,1]
@@ -198,54 +198,21 @@
exception of those in mlab.py provided by matplotlib.
"""
import sys, warnings
-import cm
-import _pylab_helpers
-import mlab #so I can override hist, psd, etc...
-from axes import Axes, PolarAxes
-import backends
from cbook import flatten, is_string_like, exception_to_str, popd, \
silent_list, iterable, enumerate, dedent
-from colors import Normalize, normalize # latter for backwards compat.
-from cm import get_cmap
-from figure import Figure, figaspect
-import image
-from matplotlib import rcParams, rcParamsDefault, get_backend
-from backend_bases import FigureCanvasBase
-from artist import getp, get
-from artist import setp as _setp
+import matplotlib.numerix as nx
+import numpy as npy
+from matplotlib import mpl # pulls in most modules
-import matplotlib.cbook as cbook
-from matplotlib.mlab import csv2rec
-
-# a hack to keep old versions of ipython working with mpl after bug
-# fix #1209354
-if 'IPython.Shell' in sys.modules:
- from backends import new_figure_manager, draw_if_interactive, show
-else:
- from backends import pylab_setup
- new_figure_manager, draw_if_interactive, show = pylab_setup()
-
-
-
-from image import imread as _imread
-from lines import Line2D
-from text import Text, Annotation
-from patches import Polygon, Rectangle, Circle, Arrow
-from transforms import blend_xy_sep_transform
-from widgets import SubplotTool, Button, Slider, Widget
-
-import numerix as nx
-
-import numpy as npy
-from matplotlib import mpl
# catch more than an import error here, since the src could fail too,
# eg a bad pytz install. I don't want to break all of matplotlib for
# date support
try:
- from dates import date2num, num2date, datestr2num, strpdate2num, drange,\
+ from matplotlib.dates import date2num, num2date,\
+ datestr2num, strpdate2num, drange,\
epoch2num, num2epoch, mx2num,\
DateFormatter, IndexDateFormatter, DateLocator,\
RRuleLocator, YearLocator, MonthLocator, WeekdayLocator,\
@@ -256,24 +223,16 @@
__dates_all__ = []
pass
else:
- import dates
- __dates_all__ = dates.__all__
+ import matplotlib.dates
+ __dates_all__ = matplotlib.dates.__all__
-from ticker import TickHelper, Formatter, FixedFormatter, NullFormatter,\
- FuncFormatter, FormatStrFormatter, ScalarFormatter,\
- LogFormatter, LogFormatterExponent, LogFormatterMathtext,\
- Locator, IndexLocator, FixedLocator, NullLocator,\
- LinearLocator, LogLocator, AutoLocator, MultipleLocator,\
- MaxNLocator
-import ticker
-import matplotlib
# bring all the symbols in so folks can import them from
# pylab in one fell swoop
-from numerix import array, zeros, shape, rank, size, fromstring,\
+from numpy.oldnumeric import array, zeros, shape, rank, size, fromstring,\
take, put, putmask, reshape, repeat, choose, searchsorted,\
- asum, cumsum, product, cumproduct, alltrue, sometrue, allclose,\
+ cumsum, product, cumproduct, alltrue, sometrue, allclose,\
arrayrange, arange, asarray, convolve, swapaxes, concatenate,\
transpose, sort, argsort, argmax, argmin, innerproduct, dot,\
outerproduct, resize, indices, fromfunction, diagonal, trace,\
@@ -287,28 +246,32 @@
cosh, arccosh, arcsinh, arctanh, cross_correlate,\
pi, ArrayType, matrixmultiply
-from numerix import Int8, UInt8, Int16, UInt16, Int32, UInt32, Float32,\
+from numpy.oldnumeric import sum as asum
+
+from numpy.oldnumeric import Int8, UInt8, Int16, UInt16, Int32, UInt32, Float32,\
Float64, Complex32, Complex64, Float, Int, Complex
-from matplotlib.numerix.fft import fft
-from matplotlib.numerix.linear_algebra import inverse, eigenvectors
+from numpy.fft import fft # Why just fft?
+from numpy.linalg import inv as inverse
+from numpy.oldnumeric.linear_algebra import eigenvectors
+ # not quite the same as linalg.eig
-#from matplotlib.numerix.mlab import rand,randn,eye,tri,diag,fliplr,flipud,rot90,tril,triu,ptp,mean,msort,median,std,cumsum,prod,cumprod,trapz,diff,cov,corrcoef,squeeze,kaiser,blackman,bartlett,hanning,hamming,sinc,eig,svd,angle,roots,amin, amax
pymin, pymax = min, max
-from matplotlib.numerix.mlab import *
+from numpy.oldnumeric.mlab import *
min, max = pymin, pymax
+from numpy import amin, amax
from matplotlib.mlab import window_hanning, window_none,\
conv, detrend, detrend_mean, detrend_none, detrend_linear,\
- corrcoef, polyfit, polyval, vander, entropy, normpdf,\
+ polyfit, polyval, entropy, normpdf,\
levypdf, find, trapz, prepca, fix, rem, norm, orth, rank,\
sqrtm, prctile, center_matrix, rk4, exp_safe, amap,\
sum_flat, mean_flat, rms_flat, l1norm, l2norm, norm, frange,\
diagonal_matrix, base_repr, binary_repr, log2, ispower2,\
bivariate_normal, load, save, stineman_interp
-from numpy import meshgrid, linspace, logspace
+from numpy import meshgrid, linspace, logspace, corrcoef, vander
"""
problem syms
@@ -326,2283 +289,7 @@
sign
"""
+from matplotlib.pyplot import *
-from colorbar import colorbar_doc
-def colorbar(mappable = None, cax=None,**kw):
- if mappable is None:
- mappable = gci()
- ret = gcf().colorbar(mappable, cax = cax, **kw)
- draw_if_interactive()
- return ret
-colorbar.__doc__ = colorbar_doc
-def colors():
- """
- This is a do nothing function to provide you with help on how
- matplotlib handles colors.
-
- Commands which take color arguments can use several formats to
- specify the colors. For the basic builtin colors, you can use a
- single letter
-
- b : blue
- g : green
- r : red
- c : cyan
- m : magenta
- y : yellow
- k : black
- w : white
-
-
- For a greater range of colors, you have two options. You can
- specify the color using an html hex string, as in
-
- color = '#eeefff'
-
- or you can pass an R,G,B tuple, where each of R,G,B are in the
- r...
[truncated message content] |
|
From: <ef...@us...> - 2007-09-10 01:42:43
|
Revision: 3820
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3820&view=rev
Author: efiring
Date: 2007-09-09 18:42:39 -0700 (Sun, 09 Sep 2007)
Log Message:
-----------
Numpification and cleanup of examples
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/examples/animation_blit.py
trunk/matplotlib/examples/animation_blit_fltk.py
trunk/matplotlib/examples/animation_blit_qt.py
trunk/matplotlib/examples/animation_blit_qt4.py
trunk/matplotlib/examples/animation_blit_tk.py
trunk/matplotlib/examples/animation_blit_wx.py
trunk/matplotlib/examples/backend_driver.py
trunk/matplotlib/examples/clippedline.py
trunk/matplotlib/examples/collections_demo.py
trunk/matplotlib/examples/color_by_yvalue.py
trunk/matplotlib/examples/contourf_demo.py
trunk/matplotlib/examples/data_helper.py
trunk/matplotlib/examples/dynamic_demo_wx.py
trunk/matplotlib/examples/dynamic_image_wxagg.py
trunk/matplotlib/examples/dynamic_image_wxagg2.py
trunk/matplotlib/examples/embedding_in_gtk.py
trunk/matplotlib/examples/embedding_in_gtk2.py
trunk/matplotlib/examples/embedding_in_gtk3.py
trunk/matplotlib/examples/embedding_in_qt.py
trunk/matplotlib/examples/embedding_in_qt4.py
trunk/matplotlib/examples/embedding_in_tk.py
trunk/matplotlib/examples/embedding_in_tk2.py
trunk/matplotlib/examples/embedding_in_wx.py
trunk/matplotlib/examples/embedding_in_wx2.py
trunk/matplotlib/examples/embedding_in_wx3.py
trunk/matplotlib/examples/embedding_in_wx4.py
trunk/matplotlib/examples/gtk_spreadsheet.py
trunk/matplotlib/examples/histogram_demo_canvasagg.py
trunk/matplotlib/examples/image_masked.py
trunk/matplotlib/examples/mathtext_wx.py
trunk/matplotlib/examples/mpl_with_glade.py
trunk/matplotlib/examples/multi_image.py
trunk/matplotlib/examples/pcolor_nonuniform.py
trunk/matplotlib/examples/polar_bar.py
trunk/matplotlib/examples/polar_demo.py
trunk/matplotlib/examples/polar_legend.py
trunk/matplotlib/examples/poly_editor.py
trunk/matplotlib/examples/printing_in_wx.py
trunk/matplotlib/examples/pythonic_matplotlib.py
trunk/matplotlib/examples/scatter_masked.py
trunk/matplotlib/examples/strip_chart_demo.py
trunk/matplotlib/examples/tex_demo.py
trunk/matplotlib/examples/tex_unicode_demo.py
trunk/matplotlib/examples/vline_demo.py
trunk/matplotlib/examples/webapp_demo.py
trunk/matplotlib/examples/wxcursor_demo.py
Removed Paths:
-------------
trunk/matplotlib/examples/anim_tk.py
trunk/matplotlib/examples/image_demo_na.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/CHANGELOG 2007-09-10 01:42:39 UTC (rev 3820)
@@ -5,7 +5,9 @@
from pylab is nearly unchanged, but there is the
new alternative of importing from pyplot to get
the state-engine graphics without all the numeric
- functions. - EF
+ functions.
+ Numpified examples; deleted two that were obsolete;
+ modified some to use pyplot. - EF
2007-09-08 Eliminated gd and paint backends - EF
Deleted: trunk/matplotlib/examples/anim_tk.py
===================================================================
--- trunk/matplotlib/examples/anim_tk.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/anim_tk.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -1,49 +0,0 @@
-# deprecated - this example is no longer needed. Follow the model of
-# anim.py to use interaction = True to avoid all the cruft of timers,
-# callbacks and the likes used here
-
-#!/usr/bin/env python2.3
-
-import matplotlib
-matplotlib.use('TkAgg')
-import pylab
-
-#import Tkinter as Tk
-import matplotlib.numerix as numerix
-fig = pylab.figure(1)
-ind = numerix.arange(60)
-
-
-
-x_tmp=[]
-for i in range(100):
- x_tmp.append(numerix.sin((ind+i)*numerix.pi/15.0))
-
-X=numerix.array(x_tmp)
-
-
-lines = pylab.plot(X[:,0],'o')
-
-manager = pylab.get_current_fig_manager()
-
-def updatefig(*args):
- updatefig.count += 1
- lines[0].set_ydata(X[:,updatefig.count%60])
- manager.canvas.draw()
- return updatefig.count
-updatefig.count=-1
-
-def run(*args):
- print 'called run'
-
- import time
- tstart = time.time()
- while 1:
- cnt = updatefig()
- if cnt==100: break
- print 'elapsed', 100.0/(time.time() - tstart)
-
-import Tkinter as Tk
-manager.window.after(10, run)
-manager.show()
-Tk.mainloop()
Modified: trunk/matplotlib/examples/animation_blit.py
===================================================================
--- trunk/matplotlib/examples/animation_blit.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/animation_blit.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -10,7 +10,7 @@
import matplotlib
matplotlib.use('GTKAgg')
-import matplotlib.numerix as nx
+import numpy as npy
import pylab as p
@@ -21,8 +21,8 @@
p.grid() # to ensure proper background restore
# create the initial line
-x = nx.arange(0,2*nx.pi,0.01)
-line, = p.plot(x, nx.sin(x), animated=True, lw=2)
+x = npy.arange(0,2*npy.pi,0.01)
+line, = p.plot(x, npy.sin(x), animated=True, lw=2)
# for profiling
tstart = time.time()
@@ -34,7 +34,7 @@
# restore the clean slate background
canvas.restore_region(update_line.background)
# update the data
- line.set_ydata(nx.sin(x+update_line.cnt/10.0))
+ line.set_ydata(npy.sin(x+update_line.cnt/10.0))
# just draw the animated artist
try:
ax.draw_artist(line)
Modified: trunk/matplotlib/examples/animation_blit_fltk.py
===================================================================
--- trunk/matplotlib/examples/animation_blit_fltk.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/animation_blit_fltk.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -3,7 +3,7 @@
import matplotlib
matplotlib.use('FltkAgg')
import pylab as p
-import matplotlib.numerix as nx
+import numpy as nx
import time
Modified: trunk/matplotlib/examples/animation_blit_qt.py
===================================================================
--- trunk/matplotlib/examples/animation_blit_qt.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/animation_blit_qt.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -15,7 +15,7 @@
ITERS = 1000
import pylab as p
-import matplotlib.numerix as nx
+import numpy as npy
import time
class BlitQT(QObject):
@@ -27,8 +27,8 @@
self.cnt = 0
# create the initial line
- self.x = nx.arange(0,2*nx.pi,0.01)
- self.line, = p.plot(self.x, nx.sin(self.x), animated=True, lw=2)
+ self.x = npy.arange(0,2*npy.pi,0.01)
+ self.line, = p.plot(self.x, npy.sin(self.x), animated=True, lw=2)
self.background = None
@@ -39,7 +39,7 @@
# restore the clean slate background
self.canvas.restore_region(self.background)
# update the data
- self.line.set_ydata(nx.sin(self.x+self.cnt/10.0))
+ self.line.set_ydata(npy.sin(self.x+self.cnt/10.0))
# just draw the animated artist
self.ax.draw_artist(self.line)
# just redraw the axes rectangle
Modified: trunk/matplotlib/examples/animation_blit_qt4.py
===================================================================
--- trunk/matplotlib/examples/animation_blit_qt4.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/animation_blit_qt4.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -10,7 +10,7 @@
ITERS = 1000
import pylab as p
-import matplotlib.numerix as nx
+import numpy as npy
import time
class BlitQT(QtCore.QObject):
@@ -22,8 +22,8 @@
self.cnt = 0
# create the initial line
- self.x = nx.arange(0,2*nx.pi,0.01)
- self.line, = p.plot(self.x, nx.sin(self.x), animated=True, lw=2)
+ self.x = npy.arange(0,2*npy.pi,0.01)
+ self.line, = p.plot(self.x, npy.sin(self.x), animated=True, lw=2)
self.background = None
@@ -34,7 +34,7 @@
# restore the clean slate background
self.canvas.restore_region(self.background)
# update the data
- self.line.set_ydata(nx.sin(self.x+self.cnt/10.0))
+ self.line.set_ydata(npy.sin(self.x+self.cnt/10.0))
# just draw the animated artist
self.ax.draw_artist(self.line)
# just redraw the axes rectangle
Modified: trunk/matplotlib/examples/animation_blit_tk.py
===================================================================
--- trunk/matplotlib/examples/animation_blit_tk.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/animation_blit_tk.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -6,7 +6,7 @@
import sys
import pylab as p
-import matplotlib.numerix as nx
+import numpy as npy
import time
ax = p.subplot(111)
@@ -14,8 +14,8 @@
# create the initial line
-x = nx.arange(0,2*nx.pi,0.01)
-line, = p.plot(x, nx.sin(x), animated=True, lw=2)
+x = npy.arange(0,2*npy.pi,0.01)
+line, = p.plot(x, npy.sin(x), animated=True, lw=2)
def run(*args):
background = canvas.copy_from_bbox(ax.bbox)
@@ -26,7 +26,7 @@
# restore the clean slate background
canvas.restore_region(background)
# update the data
- line.set_ydata(nx.sin(x+run.cnt/10.0))
+ line.set_ydata(npy.sin(x+run.cnt/10.0))
# just draw the animated artist
ax.draw_artist(line)
# just redraw the axes rectangle
Modified: trunk/matplotlib/examples/animation_blit_wx.py
===================================================================
--- trunk/matplotlib/examples/animation_blit_wx.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/animation_blit_wx.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -12,7 +12,7 @@
import wx
import sys
import pylab as p
-import matplotlib.numerix as nx
+import numpy as npy
import time
@@ -30,8 +30,8 @@
p.grid() # to ensure proper background restore
# create the initial line
-x = nx.arange(0,2*nx.pi,0.01)
-line, = p.plot(x, nx.sin(x), animated=True, lw=2)
+x = npy.arange(0,2*npy.pi,0.01)
+line, = p.plot(x, npy.sin(x), animated=True, lw=2)
# for profiling
tstart = time.time()
@@ -46,7 +46,7 @@
# restore the clean slate background
canvas.restore_region(update_line.background)
# update the data
- line.set_ydata(nx.sin(x+update_line.cnt/10.0))
+ line.set_ydata(npy.sin(x+update_line.cnt/10.0))
# just draw the animated artist
ax.draw_artist(line)
# just redraw the axes rectangle
Modified: trunk/matplotlib/examples/backend_driver.py
===================================================================
--- trunk/matplotlib/examples/backend_driver.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/backend_driver.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -42,7 +42,6 @@
'histogram_demo.py',
'image_demo.py',
'image_demo2.py',
- 'image_demo_na.py',
'image_masked.py',
'image_origin.py',
'invert_axes.py',
@@ -158,7 +157,7 @@
if __name__ == '__main__':
times = {}
- default_backends = ['Agg', 'PS', 'SVG', 'Template']
+ default_backends = ['Agg', 'PS', 'SVG', 'PDF', 'Template']
if sys.platform == 'win32':
python = r'c:\Python24\python.exe'
else:
Modified: trunk/matplotlib/examples/clippedline.py
===================================================================
--- trunk/matplotlib/examples/clippedline.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/clippedline.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -4,7 +4,7 @@
"""
from matplotlib.lines import Line2D
-import matplotlib.numerix as nx
+import numpy as npy
from pylab import figure, show
class ClippedLine(Line2D):
@@ -19,13 +19,13 @@
def set_data(self, *args, **kwargs):
Line2D.set_data(self, *args, **kwargs)
- self.xorig = nx.array(self._x)
- self.yorig = nx.array(self._y)
+ self.xorig = npy.array(self._x)
+ self.yorig = npy.array(self._y)
def draw(self, renderer):
xlim = self.ax.get_xlim()
- ind0, ind1 = nx.searchsorted(self.xorig, xlim)
+ ind0, ind1 = npy.searchsorted(self.xorig, xlim)
self._x = self.xorig[ind0:ind1]
self._y = self.yorig[ind0:ind1]
N = len(self._x)
@@ -43,8 +43,8 @@
fig = figure()
ax = fig.add_subplot(111, autoscale_on=False)
-t = nx.arange(0.0, 100.0, 0.01)
-s = nx.sin(2*nx.pi*t)
+t = npy.arange(0.0, 100.0, 0.01)
+s = npy.sin(2*npy.pi*t)
line = ClippedLine(ax, t, s, color='g', ls='-', lw=2)
ax.add_line(line)
ax.set_xlim(10,30)
Modified: trunk/matplotlib/examples/collections_demo.py
===================================================================
--- trunk/matplotlib/examples/collections_demo.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/collections_demo.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -17,10 +17,10 @@
'''
-import pylab as P
+import matplotlib.pyplot as P
from matplotlib import collections, axes, transforms
from matplotlib.colors import colorConverter
-import matplotlib.numerix as N
+import numpy as N
nverts = 50
npts = 100
@@ -33,8 +33,8 @@
spiral = zip(xx,yy)
# Make some offsets
-xo = P.randn(npts)
-yo = P.randn(npts)
+xo = N.random.randn(npts)
+yo = N.random.randn(npts)
xyo = zip(xo, yo)
# Make a list of colors cycling through the rgbcmyk series.
@@ -90,7 +90,7 @@
a = fig.add_subplot(2,2,3)
col = collections.RegularPolyCollection(fig.dpi, 7,
- sizes = P.fabs(xx)*10, offsets=xyo,
+ sizes = N.fabs(xx)*10, offsets=xyo,
transOffset=a.transData)
a.add_collection(col, autolim=True)
trans = transforms.scale_transform(fig.dpi/transforms.Value(72.),
@@ -111,12 +111,12 @@
ncurves = 20
offs = (0.1, 0.0)
-yy = P.linspace(0, 2*N.pi, nverts)
-ym = P.amax(yy)
+yy = N.linspace(0, 2*N.pi, nverts)
+ym = N.amax(yy)
xx = (0.2 + (ym-yy)/ym)**2 * N.cos(yy-0.4) * 0.5
segs = []
for i in range(ncurves):
- xxx = xx + 0.02*P.randn(nverts)
+ xxx = xx + 0.02*N.random.randn(nverts)
curve = zip(xxx, yy*100)
segs.append(curve)
Modified: trunk/matplotlib/examples/color_by_yvalue.py
===================================================================
--- trunk/matplotlib/examples/color_by_yvalue.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/color_by_yvalue.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -1,7 +1,7 @@
# use masked arrays to plot a line with different colors by y-value
-import matplotlib.numerix.ma as ma
-from matplotlib.numerix import logical_or
-from pylab import plot, show, arange, sin, pi
+import matplotlib.numerix.npyma as ma
+from numpy import logical_or, arange, sin, pi
+from matplotlib.pyplot import plot, show
t = arange(0.0, 2.0, 0.01)
s = sin(2*pi*t)
Modified: trunk/matplotlib/examples/contourf_demo.py
===================================================================
--- trunk/matplotlib/examples/contourf_demo.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/contourf_demo.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -1,6 +1,6 @@
#!/usr/bin/env python
from pylab import *
-import matplotlib.numerix.ma as ma
+import matplotlib.numerix.npyma as ma
origin = 'lower'
#origin = 'upper'
Modified: trunk/matplotlib/examples/data_helper.py
===================================================================
--- trunk/matplotlib/examples/data_helper.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/data_helper.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -1,7 +1,8 @@
#!/usr/bin/env python
# Some functions to load a return data for the plot demos
-from matplotlib.numerix import fromstring, argsort, take, array, resize
+from numpy import fromstring, argsort, take, array, resize
+
def get_two_stock_data():
"""
load stock time and price data for two stocks The return values
Modified: trunk/matplotlib/examples/dynamic_demo_wx.py
===================================================================
--- trunk/matplotlib/examples/dynamic_demo_wx.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/dynamic_demo_wx.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -63,7 +63,7 @@
from matplotlib.figure import Figure
from matplotlib.axes import Subplot
-import matplotlib.numerix as numpy
+import numpy
from wx import *
Modified: trunk/matplotlib/examples/dynamic_image_wxagg.py
===================================================================
--- trunk/matplotlib/examples/dynamic_image_wxagg.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/dynamic_image_wxagg.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -12,26 +12,13 @@
import matplotlib
matplotlib.use('WXAgg')
-# jdh: you need to control Numeric vs numarray with numerix, otherwise
-# matplotlib may be using numeric under the hood and while you are
-# using numarray and this isn't efficient. Also, if you use
-# numerix=numarray, it is important to compile matplotlib for numarray
-# by setting NUMERIX = 'numarray' in setup.py before building
from matplotlib import rcParams
-##rcParams['numerix'] = 'numarray'
-
-
-# jdh: you can import cm directly, you don't need to go via
-# pylab
import matplotlib.cm as cm
from matplotlib.backends.backend_wxagg import Toolbar, FigureCanvasWxAgg
-# jdh: you don't need a figure manager in the GUI - this class was
-# designed for the pylab interface
-
from matplotlib.figure import Figure
-import matplotlib.numerix as numerix
+import numpy as npy
import wx
@@ -75,12 +62,12 @@
# jdh you can add a subplot directly from the fig rather than
# the fig manager
a = self.fig.add_subplot(111)
- self.x = numerix.arange(120.0)*2*numerix.pi/120.0
+ self.x = npy.arange(120.0)*2*npy.pi/120.0
self.x.resize((100,120))
- self.y = numerix.arange(100.0)*2*numerix.pi/100.0
+ self.y = npy.arange(100.0)*2*npy.pi/100.0
self.y.resize((120,100))
- self.y = numerix.transpose(self.y)
- z = numerix.sin(self.x) + numerix.cos(self.y)
+ self.y = npy.transpose(self.y)
+ z = npy.sin(self.x) + npy.cos(self.y)
self.im = a.imshow( z, cmap=cm.jet)#, interpolation='nearest')
def GetToolBar(self):
@@ -89,9 +76,9 @@
return self.toolbar
def onTimer(self, evt):
- self.x += numerix.pi/15
- self.y += numerix.pi/20
- z = numerix.sin(self.x) + numerix.cos(self.y)
+ self.x += npy.pi/15
+ self.y += npy.pi/20
+ z = npy.sin(self.x) + npy.cos(self.y)
self.im.set_array(z)
self.canvas.draw()
#self.canvas.gui_repaint() # jdh wxagg_draw calls this already
Modified: trunk/matplotlib/examples/dynamic_image_wxagg2.py
===================================================================
--- trunk/matplotlib/examples/dynamic_image_wxagg2.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/dynamic_image_wxagg2.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -12,24 +12,14 @@
import matplotlib
matplotlib.use('WXAgg')
-# jdh: you need to control Numeric vs numarray with numerix, otherwise
-# matplotlib may be using numeric under the hood and while you are
-# using numarray and this isn't efficient. Also, if you use
-# numerix=numarray, it is important to compile matplotlib for numarray
-# by setting NUMERIX = 'numarray' in setup.py before building
from matplotlib import rcParams
import numpy as npy
-# jdh: you can import cm directly, you don't need to go via
-# pylab
import matplotlib.cm as cm
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
from matplotlib.backends.backend_wx import NavigationToolbar2Wx
-# jdh: you don't need a figure manager in the GUI - this class was
-# designed for the pylab interface
-
from matplotlib.figure import Figure
from wx import *
Modified: trunk/matplotlib/examples/embedding_in_gtk.py
===================================================================
--- trunk/matplotlib/examples/embedding_in_gtk.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/embedding_in_gtk.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -8,7 +8,7 @@
from matplotlib.axes import Subplot
from matplotlib.figure import Figure
-from matplotlib.numerix import arange, sin, pi
+from numpy import arange, sin, pi
# uncomment to select /GTK/GTKAgg/GTKCairo
from matplotlib.backends.backend_gtk import FigureCanvasGTK as FigureCanvas
Modified: trunk/matplotlib/examples/embedding_in_gtk2.py
===================================================================
--- trunk/matplotlib/examples/embedding_in_gtk2.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/embedding_in_gtk2.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -7,7 +7,7 @@
from matplotlib.axes import Subplot
from matplotlib.figure import Figure
-from matplotlib.numerix import arange, sin, pi
+from numpy import arange, sin, pi
# uncomment to select /GTK/GTKAgg/GTKCairo
from matplotlib.backends.backend_gtk import FigureCanvasGTK as FigureCanvas
Modified: trunk/matplotlib/examples/embedding_in_gtk3.py
===================================================================
--- trunk/matplotlib/examples/embedding_in_gtk3.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/embedding_in_gtk3.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -7,7 +7,7 @@
from matplotlib.axes import Subplot
from matplotlib.figure import Figure
-from matplotlib.numerix import arange, sin, pi
+from numpy import arange, sin, pi
# uncomment to select /GTK/GTKAgg/GTKCairo
#from matplotlib.backends.backend_gtk import FigureCanvasGTK as FigureCanvas
Modified: trunk/matplotlib/examples/embedding_in_qt.py
===================================================================
--- trunk/matplotlib/examples/embedding_in_qt.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/embedding_in_qt.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -11,7 +11,7 @@
import sys, os, random
from qt import *
-from matplotlib.numerix import arange, sin, pi
+from numpy import arange, sin, pi
from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
Modified: trunk/matplotlib/examples/embedding_in_qt4.py
===================================================================
--- trunk/matplotlib/examples/embedding_in_qt4.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/embedding_in_qt4.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -12,7 +12,7 @@
import sys, os, random
from PyQt4 import QtGui, QtCore
-from matplotlib.numerix import arange, sin, pi
+from numpy import arange, sin, pi
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
Modified: trunk/matplotlib/examples/embedding_in_tk.py
===================================================================
--- trunk/matplotlib/examples/embedding_in_tk.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/embedding_in_tk.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -2,7 +2,7 @@
import matplotlib
matplotlib.use('TkAgg')
-from matplotlib.numerix import arange, sin, pi
+from numpy import arange, sin, pi
from matplotlib.axes import Subplot
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
Modified: trunk/matplotlib/examples/embedding_in_tk2.py
===================================================================
--- trunk/matplotlib/examples/embedding_in_tk2.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/embedding_in_tk2.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -2,7 +2,7 @@
import matplotlib
matplotlib.use('TkAgg')
-from matplotlib.numerix import arange, sin, pi
+from numpy import arange, sin, pi
from matplotlib.axes import Subplot
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
Modified: trunk/matplotlib/examples/embedding_in_wx.py
===================================================================
--- trunk/matplotlib/examples/embedding_in_wx.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/embedding_in_wx.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -44,7 +44,7 @@
from matplotlib.figure import Figure
from matplotlib.axes import Subplot
-import matplotlib.numerix as numpy
+import numpy
from wx import *
Modified: trunk/matplotlib/examples/embedding_in_wx2.py
===================================================================
--- trunk/matplotlib/examples/embedding_in_wx2.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/embedding_in_wx2.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -4,7 +4,7 @@
toolbar - comment out the setA_toolbar line for no toolbar
"""
-from matplotlib.numerix import arange, sin, pi
+from numpy import arange, sin, pi
import matplotlib
Modified: trunk/matplotlib/examples/embedding_in_wx3.py
===================================================================
--- trunk/matplotlib/examples/embedding_in_wx3.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/embedding_in_wx3.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -25,8 +25,6 @@
from matplotlib.backends.backend_wxagg import Toolbar, FigureCanvasWxAgg
from matplotlib.figure import Figure
import numpy as npy
-import matplotlib.numerix.mlab as mlab
-from matplotlib.mlab import meshgrid
from wx import *
from wx.xrc import *
@@ -61,11 +59,11 @@
x = npy.arange(120.0)*2*npy.pi/60.0
y = npy.arange(100.0)*2*npy.pi/50.0
- self.x, self.y = meshgrid(x, y)
+ self.x, self.y = npy.meshgrid(x, y)
z = npy.sin(self.x) + npy.cos(self.y)
self.im = a.imshow( z, cmap=cm.jet)#, interpolation='nearest')
- zmax = mlab.max(mlab.max(z))-ERR_TOL
+ zmax = npy.amax(z) - ERR_TOL
ymax_i, xmax_i = npy.nonzero(z >= zmax)
if self.im.origin == 'upper':
ymax_i = z.shape[0]-ymax_i
@@ -84,7 +82,7 @@
z = npy.sin(self.x) + npy.cos(self.y)
self.im.set_array(z)
- zmax = mlab.max(mlab.max(z))-ERR_TOL
+ zmax = npy.amax(z) - ERR_TOL
ymax_i, xmax_i = npy.nonzero(z >= zmax)
if self.im.origin == 'upper':
ymax_i = z.shape[0]-ymax_i
Modified: trunk/matplotlib/examples/embedding_in_wx4.py
===================================================================
--- trunk/matplotlib/examples/embedding_in_wx4.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/embedding_in_wx4.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -4,7 +4,7 @@
toolbar
"""
-from matplotlib.numerix import arange, sin, pi
+from numpy import arange, sin, pi
import matplotlib
@@ -19,7 +19,7 @@
from matplotlib.backends.backend_wx import _load_bitmap
from matplotlib.figure import Figure
-from matplotlib.numerix.mlab import rand
+from numpy.random import rand
from wx import *
Modified: trunk/matplotlib/examples/gtk_spreadsheet.py
===================================================================
--- trunk/matplotlib/examples/gtk_spreadsheet.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/gtk_spreadsheet.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -14,15 +14,13 @@
matplotlib.use('GTKAgg') # or 'GTK'
from matplotlib.backends.backend_gtk import FigureCanvasGTK as FigureCanvas
-#from matplotlib.numerix import rand
-from matplotlib.numerix.random_array import random
+from numpy.random import random
from matplotlib.figure import Figure
class DataManager(gtk.Window):
numRows, numCols = 20,10
- #data = rand(numRows, numCols)
data = random((numRows, numCols))
def __init__(self):
Modified: trunk/matplotlib/examples/histogram_demo_canvasagg.py
===================================================================
--- trunk/matplotlib/examples/histogram_demo_canvasagg.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/histogram_demo_canvasagg.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -13,7 +13,8 @@
from matplotlib.figure import Figure
from matplotlib.axes import Subplot
from matplotlib.mlab import normpdf
-from matplotlib.numerix.mlab import randn
+from numpy.random import randn
+import numpy
fig = Figure(figsize=(5,4), dpi=100)
ax = fig.add_subplot(111)
@@ -42,14 +43,14 @@
s = canvas.tostring_rgb() # save this and convert to bitmap as needed
-# get the figure dimensions for creating bitmaps or numeric arrays,
+# get the figure dimensions for creating bitmaps or numpy arrays,
# etc.
l,b,w,h = fig.bbox.get_bounds()
w, h = int(w), int(h)
if 0:
- # convert to a Numeric array
- X = fromstring(s, UInt8)
+ # convert to a numpy array
+ X = numpy.fromstring(s, numpy.uint8)
X.shape = h, w, 3
if 0:
Deleted: trunk/matplotlib/examples/image_demo_na.py
===================================================================
--- trunk/matplotlib/examples/image_demo_na.py 2007-09-09 22:41:36 UTC (rev 3819)
+++ trunk/matplotlib/examples/image_demo_na.py 2007-09-10 01:42:39 UTC (rev 3820)
@@ -1,40 +0,0 @@
-#!/usr/bin/env python
-from matplotlib import rcParams
-rcParams['numerix'] = 'numarray'
-
-from pylab import *
-
-
-def bivariate_normal(X, Y, sigmax=1.0, sigmay=1.0,
- mux=0.0, muy=0.0, sigmaxy=0.0):
- """
- Bivariate gaussan distribution for equal shape X, Y
-
- http://mathworld.wolfram.com/BivariateNormalDistribution.html
- """
- Xmu = X-mux
- Ymu = Y-muy
-
- rho = sigmaxy/(sigmax*sigmay)
- z = (1.0/sigmax**2)*Xmu**2 + (1.0/sigmay)*Ymu**2 - (2*rho/(sigmax*sigmay))*Xmu*Ymu
- return 1.0/(2*pi*sigmax*sigmay*(1-rho**2)) * exp( -1/(2*(1-rho**2))*z)
-
-
-delta = 0.025
-x = arange(-3.0, 3.0, delta)
-y = arange(-3.0, 3.0, delta)
-X,Y = meshgrid(x, y)
-Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
-Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
-
-# difference of Gaussians
-im = imshow(Z2-Z1)
-
-# set the interpolation method: 'nearest', 'bilinear', 'bicubic' and much more
-im.set_interpolation('bilinear')
-
-
-axis('off')
-#savefig('test')
-show()
-
Modified: trunk/matplotlib/examples/image_mas...
[truncated message content] |
|
From: <jd...@us...> - 2007-09-12 20:37:47
|
Revision: 3844
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3844&view=rev
Author: jdh2358
Date: 2007-09-12 13:37:41 -0700 (Wed, 12 Sep 2007)
Log Message:
-----------
fixed a bar units bug
Modified Paths:
--------------
trunk/matplotlib/API_CHANGES
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/artist.py
trunk/matplotlib/lib/matplotlib/axes.py
trunk/matplotlib/lib/matplotlib/axis.py
trunk/matplotlib/lib/matplotlib/mlab.py
trunk/matplotlib/lib/matplotlib/patches.py
Added Paths:
-----------
trunk/matplotlib/examples/units/bar_demo2.py
Modified: trunk/matplotlib/API_CHANGES
===================================================================
--- trunk/matplotlib/API_CHANGES 2007-09-12 20:25:17 UTC (rev 3843)
+++ trunk/matplotlib/API_CHANGES 2007-09-12 20:37:41 UTC (rev 3844)
@@ -1,3 +1,5 @@
+ Made skiprows=1 the default on csv2rec
+
The gd and paint backends have been deleted.
The errorbar method and function now accept additional kwargs
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2007-09-12 20:25:17 UTC (rev 3843)
+++ trunk/matplotlib/CHANGELOG 2007-09-12 20:37:41 UTC (rev 3844)
@@ -1,3 +1,7 @@
+2007-09-12 Fixed a Axes.bar unit bug - JDH
+
+2007-09-10 Made skiprows=1 the default on csv2rec - JDH
+
2007-09-09 Split out the plotting part of pylab and put it in
pyplot.py; removed numerix from the remaining pylab.py,
which imports everything from pyplot.py. The intention
Added: trunk/matplotlib/examples/units/bar_demo2.py
===================================================================
--- trunk/matplotlib/examples/units/bar_demo2.py (rev 0)
+++ trunk/matplotlib/examples/units/bar_demo2.py 2007-09-12 20:37:41 UTC (rev 3844)
@@ -0,0 +1,34 @@
+"""
+plot using a variety of cm vs inches conversions. The example shows
+how default unit instrospection works (ax1), how various keywords can
+be used to set the x and y units to override the defaults (ax2, ax3,
+ax4) and how one can set the xlimits using scalars (ax3, current units
+assumed) or units (conversions applied to get the numbers to current
+units)
+
+"""
+from basic_units import cm, inch
+from pylab import figure, show, nx
+
+cms = cm *nx.arange(0, 10, 2)
+bottom=0*cm
+width=0.8*cm
+
+fig = figure()
+
+ax1 = fig.add_subplot(2,2,1)
+ax1.bar(cms, cms, bottom=bottom)
+
+ax2 = fig.add_subplot(2,2,2)
+ax2.bar(cms, cms, bottom=bottom, width=width, xunits=cm, yunits=inch)
+
+ax3 = fig.add_subplot(2,2,3)
+ax3.bar(cms, cms, bottom=bottom, width=width, xunits=inch, yunits=cm)
+ax3.set_xlim(3, 6) # scalars are interpreted in current units
+
+ax4 = fig.add_subplot(2,2,4)
+ax4.bar(cms, cms, bottom=bottom, width=width, xunits=inch, yunits=inch)
+#fig.savefig('simple_conversion_plot.png')
+ax4.set_xlim(3*cm, 6*cm) # cm are converted to inches
+
+show()
Modified: trunk/matplotlib/lib/matplotlib/artist.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/artist.py 2007-09-12 20:25:17 UTC (rev 3843)
+++ trunk/matplotlib/lib/matplotlib/artist.py 2007-09-12 20:37:41 UTC (rev 3844)
@@ -51,7 +51,7 @@
self._remove_method = None
def remove(self):
- '''
+ """
Remove the artist from the figure if possible. The effect will not
be visible until the figure is redrawn, e.g., with ax.draw_idle().
Call ax.relim() to update the axes limits if desired.
@@ -60,7 +60,7 @@
was added to axes with autolim=True.
Note: there is no support for removing the artist's legend entry.
- '''
+ """
# There is no method to set the callback. Instead the parent should set
# the _remove_method attribute directly. This would be a protected
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2007-09-12 20:25:17 UTC (rev 3843)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2007-09-12 20:37:41 UTC (rev 3844)
@@ -1198,23 +1198,27 @@
def _process_unit_info(self, xdata=None, ydata=None, kwargs=None):
'look for unit kwargs and update the axis instances as necessary'
- if self.xaxis is None or self.xaxis is None: return
+ if self.xaxis is None or self.yaxis is None: return
-
+ #print 'processing', self.get_geometry()
if xdata is not None:
self.xaxis.update_units(xdata)
+ #print '\tset from xdata', self.xaxis.units
if ydata is not None:
self.yaxis.update_units(ydata)
+ #print '\tset from ydata', self.yaxis.units
# process kwargs 2nd since these will override default units
if kwargs is not None:
xunits = kwargs.pop( 'xunits', self.xaxis.units)
if xunits!=self.xaxis.units:
+ #print '\tkw setting xunits', xunits
self.xaxis.set_units(xunits)
yunits = kwargs.pop('yunits', self.yaxis.units)
if yunits!=self.yaxis.units:
+ #print '\tkw setting yunits', yunits
self.yaxis.set_units(yunits)
def in_axes(self, xwin, ywin):
@@ -3114,11 +3118,13 @@
else:
raise ValueError, 'invalid orientation: %s' % orientation
- left = npy.asarray(left)
- height = npy.asarray(height)
- width = npy.asarray(width)
- bottom = npy.asarray(bottom)
+ # do not convert to array here as unit info is lost
+ #left = npy.asarray(left)
+ #height = npy.asarray(height)
+ #width = npy.asarray(width)
+ #bottom = npy.asarray(bottom)
+
if len(linewidth) == 1: linewidth = linewidth * nbars
# if color looks like a color string, an RGB tuple or a
@@ -3161,14 +3167,14 @@
# lets do some conversions now
if self.xaxis is not None:
xconv = self.xaxis.converter
- if ( xconv ):
+ if xconv is not None:
units = self.xaxis.get_units()
left = xconv.convert( left, units )
width = xconv.convert( width, units )
if self.yaxis is not None:
yconv = self.yaxis.converter
- if ( yconv ):
+ if yconv is not None :
units = self.yaxis.get_units()
bottom = yconv.convert( bottom, units )
height = yconv.convert( height, units )
@@ -3208,12 +3214,14 @@
if xerr is not None or yerr is not None:
if orientation == 'vertical':
- x = left + 0.5*width
- y = bottom + height
+ # using list comps rather than arrays to preserve unit info
+ x = [l+0.5*w for l, w in zip(left, width)]
+ y = [b+h for b,h in zip(bottom, height)]
elif orientation == 'horizontal':
- x = left + width
- y = bottom + 0.5*height
+ # using list comps rather than arrays to preserve unit info
+ x = [l+w for l,w in zip(left, width)]
+ y = [b+0.5*h for b,h in zip(bottom, height)]
self.errorbar(
x, y,
Modified: trunk/matplotlib/lib/matplotlib/axis.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axis.py 2007-09-12 20:25:17 UTC (rev 3843)
+++ trunk/matplotlib/lib/matplotlib/axis.py 2007-09-12 20:37:41 UTC (rev 3844)
@@ -828,7 +828,7 @@
return x
ret = self.converter.convert(x, self.units)
- #print 'convert_units converting: units=%s, converter=%s, in=%s, out=%s'%(self.units, self.converter, x, ret)
+ #print 'convert_units converting: axis=%s, units=%s, converter=%s, in=%s, out=%s'%(self, self.units, self.converter, x, ret)
return ret
def set_units(self, u):
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2007-09-12 20:25:17 UTC (rev 3843)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2007-09-12 20:37:41 UTC (rev 3844)
@@ -1253,9 +1253,9 @@
if r==1 or c==1:
X.shape = max(r,c),
if unpack: return X.transpose()
- return X
+ else: return X
-def csv2rec(fname, comments='#', skiprows=0, checkrows=5, delimiter=',',
+def csv2rec(fname, comments='#', skiprows=1, checkrows=5, delimiter=',',
converterd=None, names=None, missing=None):
"""
Load data from comma/space/tab delimited file in fname into a
Modified: trunk/matplotlib/lib/matplotlib/patches.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/patches.py 2007-09-12 20:25:17 UTC (rev 3843)
+++ trunk/matplotlib/lib/matplotlib/patches.py 2007-09-12 20:37:41 UTC (rev 3844)
@@ -77,6 +77,8 @@
if len(kwargs): artist.setp(self, **kwargs)
__init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
+
+
def contains(self, mouseevent):
"""Test whether the mouse event occurred in the patch.
@@ -347,7 +349,6 @@
Return the vertices of the rectangle
"""
x, y = self.xy
-
left, right = self.convert_xunits((x, x + self.width))
bottom, top = self.convert_yunits((y, y + self.height))
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jo...@us...> - 2007-09-13 06:29:33
|
Revision: 3845
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3845&view=rev
Author: jouni
Date: 2007-09-12 23:29:14 -0700 (Wed, 12 Sep 2007)
Log Message:
-----------
More work on dviread and usetex in pdf. It is more usable now,
so I am renaming the method from _draw_tex to draw_tex.
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py
trunk/matplotlib/lib/matplotlib/dviread.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2007-09-12 20:37:41 UTC (rev 3844)
+++ trunk/matplotlib/CHANGELOG 2007-09-13 06:29:14 UTC (rev 3845)
@@ -1,3 +1,6 @@
+2007-09-13 The usetex support in the pdf backend is more usable now,
+ so I am enabling it. - JKS
+
2007-09-12 Fixed a Axes.bar unit bug - JDH
2007-09-10 Made skiprows=1 the default on csv2rec - JDH
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py 2007-09-12 20:37:41 UTC (rev 3844)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py 2007-09-13 06:29:14 UTC (rev 3845)
@@ -527,7 +527,7 @@
widths.append(afmdata.get_width_from_char_name(ch))
except KeyError:
matplotlib.verbose.report(
- 'No width for %s in %s' % (ch, fullname), 'debug')
+ 'No width for %s in %s' % (ch, fullname), 'debug-annoying')
widths.append(0)
differencesArray = [ Name(ch) for ch in enc ]
@@ -561,7 +561,7 @@
except KeyError:
matplotlib.verbose.report(
'No name for glyph %d in %s' % (ch, fullname),
- 'debug')
+ 'debug-annoying')
need_idx = True
@@ -1449,9 +1449,7 @@
# Pop off the global transformation
self.file.output(Op.grestore)
- def _draw_tex(self, gc, x, y, s, prop, angle):
- # Rename to draw_tex to enable
-
+ def draw_tex(self, gc, x, y, s, prop, angle):
texmanager = self.get_texmanager()
fontsize = prop.get_size_in_points()
dvifile = texmanager.make_dvi(s, fontsize)
@@ -1494,7 +1492,7 @@
elt[3][-1] += next[3][0]
elt[4] += next[4]-next[1]
else:
- elt[3] += [offset, next[3][0]]
+ elt[3] += [offset*1000.0/dvifont.size, next[3][0]]
elt[4] = next[4]
del seq[i+1]
continue
Modified: trunk/matplotlib/lib/matplotlib/dviread.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/dviread.py 2007-09-12 20:37:41 UTC (rev 3844)
+++ trunk/matplotlib/lib/matplotlib/dviread.py 2007-09-13 06:29:14 UTC (rev 3845)
@@ -84,16 +84,22 @@
e = 0 # zero depth
else: # glyph
x,y,font,g,w = elt
- h = (font.scale * font.tfm.height[g]) >> 20
- e = (font.scale * font.tfm.depth[g]) >> 20
+ h = _mul2012(font._scale, font._tfm.height[g])
+ e = _mul2012(font._scale, font._tfm.depth[g])
minx = min(minx, x)
miny = min(miny, y - h)
maxx = max(maxx, x + w)
maxy = max(maxy, y + e)
maxy_pure = max(maxy_pure, y)
+ if self.dpi is None:
+ # special case for ease of debugging: output raw dvi coordinates
+ return mpl_cbook.Bunch(text=self.text, boxes=self.boxes,
+ width=maxx-minx, height=maxy_pure-miny,
+ descent=maxy-maxy_pure)
+
d = self.dpi / (72.27 * 2**16) # from TeX's "scaled points" to dpi units
- text = [ ((x-minx)*d, (maxy-y)*d, DviFont(f), g, w*d)
+ text = [ ((x-minx)*d, (maxy-y)*d, f, g, w*d)
for (x,y,f,g,w) in self.text ]
boxes = [ ((x-minx)*d, (maxy-y)*d, h*d, w*d) for (x,y,h,w) in self.boxes ]
@@ -110,11 +116,11 @@
while True:
byte = ord(self.file.read(1))
self._dispatch(byte)
- if self.state == _dvistate.inpage:
- matplotlib.verbose.report(
- 'Dvi._read: after %d at %f,%f' %
- (byte, self.h, self.v),
- 'debug-annoying')
+# if self.state == _dvistate.inpage:
+# matplotlib.verbose.report(
+# 'Dvi._read: after %d at %f,%f' %
+# (byte, self.h, self.v),
+# 'debug-annoying')
if byte == 140: # end of page
return True
if self.state == _dvistate.post_post: # end of file
@@ -225,21 +231,11 @@
# I think we can assume this is constant
self.state = _dvistate.outer
- def _width_of(self, char, font):
- width = font.tfm.width.get(char, None)
- if width is not None:
- return (width * font.scale) >> 20
-
- matplotlib.verbose.report(
- 'No width for char %d in font %s' % (char, font.name),
- 'debug')
- return 0
-
def _set_char(self, char):
if self.state != _dvistate.inpage:
raise ValueError, "misplaced set_char in dvi file"
self._put_char(char)
- self.h += self._width_of(char, self.fonts[self.f])
+ self.h += self.fonts[self.f]._width_of(char)
def _set_rule(self, a, b):
if self.state != _dvistate.inpage:
@@ -251,20 +247,33 @@
if self.state != _dvistate.inpage:
raise ValueError, "misplaced put_char in dvi file"
font = self.fonts[self.f]
- if font.vf is None:
+ if font._vf is None:
self.text.append((self.h, self.v, font, char,
- self._width_of(char, font)))
+ font._width_of(char)))
+# matplotlib.verbose.report(
+# 'Dvi._put_char: %d,%d %d' %(self.h, self.v, char),
+# 'debug-annoying')
else:
- self.text.extend([(self.h + x, self.v + y, f, g, w)
- for x, y, f, g, w in font.vf[char].text])
- self.boxes.extend([(self.h + x, self.v + y, a, b)
- for x, y, a, b in font.vf[char].boxes])
+ scale = font._scale
+ for x, y, f, g, w in font._vf[char].text:
+ newf = DviFont(scale=_mul2012(scale, f._scale),
+ tfm=f._tfm, texname=f.texname, vf=f._vf)
+ self.text.append((self.h + _mul2012(x, scale),
+ self.v + _mul2012(y, scale),
+ newf, g, newf._width_of(g)))
+ self.boxes.extend([(self.h + _mul2012(x, scale),
+ self.v + _mul2012(y, scale),
+ _mul2012(a, scale), _mul2012(b, scale))
+ for x, y, a, b in font._vf[char].boxes])
def _put_rule(self, a, b):
if self.state != _dvistate.inpage:
raise ValueError, "misplaced put_rule in dvi file"
if a > 0 and b > 0:
self.boxes.append((self.h, self.v, a, b))
+# matplotlib.verbose.report(
+# 'Dvi._put_rule: %d,%d %d,%d' % (self.h, self.v, a, b),
+# 'debug-annoying')
def _nop(self):
pass
@@ -357,7 +366,7 @@
vf = _vffile(n[-l:])
- self.fonts[k] = mpl_cbook.Bunch(scale=s, tfm=tfm, name=n, vf=vf)
+ self.fonts[k] = DviFont(scale=s, tfm=tfm, texname=n, vf=vf)
def _post(self):
if self.state != _dvistate.outer:
@@ -370,17 +379,20 @@
raise NotImplementedError
class DviFont(object):
- __slots__ = ('texname', 'size')
+ """
+ Object that holds a font's texname and size and supports comparison.
+ There are also internal attributes (for use by dviread.py) that
+ are _not_ used for comparison.
- def __init__(self, f):
- """
- Object that holds a font's texname and size and supports comparison.
+ The size is in Adobe points (converted from TeX points).
+ """
+ __slots__ = ('texname', 'size', '_scale', '_vf', '_tfm')
- The size is in Adobe points (converted from TeX points).
- """
+ def __init__(self, scale, tfm, texname, vf):
+ self._scale, self._tfm, self.texname, self._vf = \
+ scale, tfm, texname, vf
# TODO: would it make more sense to have the size in dpi units?
- self.texname = f.name
- self.size = f.scale * (72.0 / (72.27 * 2**16))
+ self.size = scale * (72.0 / (72.27 * 2**16))
def __eq__(self, other):
return self.__class__ == other.__class__ and \
@@ -389,6 +401,16 @@
def __ne__(self, other):
return not self.__eq__(other)
+ def _width_of(self, char):
+ width = self._tfm.width.get(char, None)
+ if width is not None:
+ return _mul2012(width, self._scale)
+
+ matplotlib.verbose.report(
+ 'No width for char %d in font %s' % (char, self.texname),
+ 'debug')
+ return 0
+
class Vf(Dvi):
"""
A virtual font (*.vf file) containing subroutines for dvi files.
@@ -465,7 +487,8 @@
raise ValueError, "pre command in middle of vf file"
if i != 202:
raise ValueError, "Unknown vf format %d" % i
- matplotlib.verbose.report('vf file comment: ' + x, 'debug')
+ if len(x):
+ matplotlib.verbose.report('vf file comment: ' + x, 'debug')
self.state = _dvistate.outer
# cs = checksum, ds = design size
@@ -474,7 +497,7 @@
if self._first_font is None:
self._first_font = k
-def fix2comp(num):
+def _fix2comp(num):
"""
Convert from two's complement to negative.
"""
@@ -484,6 +507,13 @@
else:
return num
+def _mul2012(num1, num2):
+ """
+ Multiply two numbers in 20.12 fixed point format.
+ """
+ # Separated into a function because >> has surprising precedence
+ return (num1*num2) >> 20
+
class Tfm(object):
"""
A TeX Font Metric file. This implementation covers only the bare
@@ -497,6 +527,7 @@
(this is a dict because indexing may not start from 0)
height[i], depth[i]: height and depth of character #i
"""
+ __slots__ = ('checksum', 'design_size', 'width', 'height', 'depth')
def __init__(self, filename):
matplotlib.verbose.report('opening tfm file ' + filename, 'debug')
@@ -525,9 +556,9 @@
[ struct.unpack('!%dI' % (len(x)/4), x)
for x in (widths, heights, depths) ]
for i in range(ec-bc):
- self.width[bc+i] = fix2comp(widths[ord(char_info[4*i])])
- self.height[bc+i] = fix2comp(heights[ord(char_info[4*i+1]) >> 4])
- self.depth[bc+i] = fix2comp(depths[ord(char_info[4*i+1]) & 0xf])
+ self.width[bc+i] = _fix2comp(widths[ord(char_info[4*i])])
+ self.height[bc+i] = _fix2comp(heights[ord(char_info[4*i+1]) >> 4])
+ self.depth[bc+i] = _fix2comp(depths[ord(char_info[4*i+1]) & 0xf])
class PsfontsMap(object):
@@ -552,6 +583,7 @@
the pdf-related files perhaps only avoid the "Base 14" pdf fonts.
But the user may have configured these files differently.
"""
+ __slots__ = ('_font',)
def __init__(self, filename):
self._font = {}
@@ -627,7 +659,17 @@
encoding=encoding, filename=filename)
class Encoding(object):
+ """
+ Parses a *.enc file referenced from a psfonts.map style file.
+ The format this class understands is a very limited subset of
+ PostScript.
+ Usage (subject to change):
+ for name in Encoding(filename):
+ whatever(name)
+ """
+ __slots__ = ('encoding',)
+
def __init__(self, filename):
file = open(filename, 'rt')
try:
@@ -694,6 +736,10 @@
return result
+# With multiple text objects per figure (e.g. tick labels) we may end
+# up reading the same tfm and vf files many times, so we implement a
+# simple cache. TODO: is this worth making persistent?
+
_tfmcache = {}
_vfcache = {}
@@ -721,19 +767,22 @@
if __name__ == '__main__':
- matplotlib.verbose.set_level('debug')
- dvi = Dvi('foo.dvi', 72)
+ import sys
+ matplotlib.verbose.set_level('debug-annoying')
+ fname = sys.argv[1]
+ try: dpi = float(sys.argv[2])
+ except IndexError: dpi = None
+ dvi = Dvi(fname, dpi)
fontmap = PsfontsMap(find_tex_file('pdftex.map'))
- for text,boxes in dvi:
+ for page in dvi:
print '=== new page ==='
fPrev = None
- for x,y,f,c in text:
- texname = dvi.fonts[f].name
- print x,y,c,chr(c),texname
+ for x,y,f,c,w in page.text:
if f != fPrev:
- print 'font', texname, '=', fontmap[texname].__dict__
+ print 'font', f.texname, 'scaled', f._scale/pow(2.0,20)
fPrev = f
- for x,y,w,h in boxes:
+ print x,y,c, 32 <= c < 128 and chr(c) or '.', w
+ for x,y,w,h in page.boxes:
print x,y,'BOX',w,h
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ds...@us...> - 2007-09-21 15:33:21
|
Revision: 3871
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3871&view=rev
Author: dsdale
Date: 2007-09-21 08:33:18 -0700 (Fri, 21 Sep 2007)
Log Message:
-----------
changed cbooks reversed to agree with the python builtin
Modified Paths:
--------------
trunk/matplotlib/API_CHANGES
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/cbook.py
Modified: trunk/matplotlib/API_CHANGES
===================================================================
--- trunk/matplotlib/API_CHANGES 2007-09-20 18:02:51 UTC (rev 3870)
+++ trunk/matplotlib/API_CHANGES 2007-09-21 15:33:18 UTC (rev 3871)
@@ -1,3 +1,8 @@
+ Changed cbook.reversed so it yields a tuple rather than a
+ (index, tuple). This agrees with the python reversed builtin,
+ and cbook only defines reversed if python doesnt provide the
+ builtin.
+
Made skiprows=1 the default on csv2rec
The gd and paint backends have been deleted.
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2007-09-20 18:02:51 UTC (rev 3870)
+++ trunk/matplotlib/CHANGELOG 2007-09-21 15:33:18 UTC (rev 3871)
@@ -1,3 +1,6 @@
+2007-09-21 Changed cbook.reversed to yield the same result as the
+ python reversed builtin - DSD
+
2007-09-13 The usetex support in the pdf backend is more usable now,
so I am enabling it. - JKS
Modified: trunk/matplotlib/lib/matplotlib/cbook.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/cbook.py 2007-09-20 18:02:51 UTC (rev 3870)
+++ trunk/matplotlib/lib/matplotlib/cbook.py 2007-09-21 15:33:18 UTC (rev 3871)
@@ -482,7 +482,7 @@
enumerate() is new in Python 2.3
"""
for i in range(len(seq)-1,-1,-1):
- yield i, seq[i]
+ yield seq[i]
# use itertools.izip if available, else use python version
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2007-10-01 07:06:44
|
Revision: 3904
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3904&view=rev
Author: efiring
Date: 2007-10-01 00:06:43 -0700 (Mon, 01 Oct 2007)
Log Message:
-----------
Fixed bug in updating dataLim when an axis is reversed
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/src/_transforms.cpp
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2007-09-30 20:47:55 UTC (rev 3903)
+++ trunk/matplotlib/CHANGELOG 2007-10-01 07:06:43 UTC (rev 3904)
@@ -1,3 +1,10 @@
+2007-09-30 Modified update* methods of Bbox and Interval so they
+ work with reversed axes. Prior to this, trying to
+ set the ticks on a reversed axis failed with an
+ uninformative error message. - EF
+
+2007-09-30 Applied patches to axes3d to fix index error problem - EF
+
2007-09-24 Applied Eike Welk's patch reported on mpl-dev on 2007-09-22
Fixes a bug with multiple plot windows in the qt backend,
ported the changes to backend_qt4 as well - DSD
@@ -2,3 +9,3 @@
-2007-09-21 Changed cbook.reversed to yield the same result as the
+2007-09-21 Changed cbook.reversed to yield the same result as the
python reversed builtin - DSD
Modified: trunk/matplotlib/src/_transforms.cpp
===================================================================
--- trunk/matplotlib/src/_transforms.cpp 2007-09-30 20:47:55 UTC (rev 3903)
+++ trunk/matplotlib/src/_transforms.cpp 2007-10-01 07:06:43 UTC (rev 3904)
@@ -159,12 +159,19 @@
double minx = _val1->val();
double maxx = _val2->val();
+ int reversed = 0;
+ if (minx > maxx) {
+ reversed = 1;
+ double tmp = minx;
+ minx = maxx;
+ maxx = tmp;
+ }
double thisval;
thisval = Py::Float(vals[0]);
- if (ignore) {
+ if (ignore) {
minx = thisval;
maxx = thisval;
}
@@ -176,9 +183,13 @@
_minpos->update(thisval);
}
-
- _val1->set_api(minx);
- _val2->set_api(maxx);
+ if (reversed) {
+ _val1->set_api(maxx);
+ _val2->set_api(minx);
+ } else {
+ _val1->set_api(minx);
+ _val2->set_api(maxx);
+ }
return Py::Object();
}
@@ -459,8 +470,24 @@
double minx = _ll->xval();
double maxx = _ur->xval();
+ int xreversed = 0;
+ if (minx > maxx) {
+ xreversed = 1;
+ double tmp = minx;
+ minx = maxx;
+ maxx = tmp;
+ }
+
+
double miny = _ll->yval();
double maxy = _ur->yval();
+ int yreversed = 0;
+ if (miny > maxy) {
+ yreversed = 1;
+ double tmp = miny;
+ miny = maxy;
+ maxy = tmp;
+ }
Py::Tuple tup;
if (ignore) {
@@ -482,11 +509,22 @@
if (y>maxy) maxy=y;
}
+ if (xreversed) {
+ _ll->x_api()->set_api(maxx);
+ _ur->x_api()->set_api(minx);
+ } else {
+ _ll->x_api()->set_api(minx);
+ _ur->x_api()->set_api(maxx);
+ }
- _ll->x_api()->set_api(minx);
- _ll->y_api()->set_api(miny);
- _ur->x_api()->set_api(maxx);
- _ur->y_api()->set_api(maxy);
+ if (yreversed) {
+ _ll->y_api()->set_api(maxy);
+ _ur->y_api()->set_api(miny);
+ } else {
+ _ll->y_api()->set_api(miny);
+ _ur->y_api()->set_api(maxy);
+ }
+
return Py::Object();
}
@@ -519,8 +557,24 @@
double minx = _ll->xval();
double maxx = _ur->xval();
+ int xreversed = 0;
+ if (minx > maxx) {
+ xreversed = 1;
+ double tmp = minx;
+ minx = maxx;
+ maxx = tmp;
+ }
+
+
double miny = _ll->yval();
double maxy = _ur->yval();
+ int yreversed = 0;
+ if (miny > maxy) {
+ yreversed = 1;
+ double tmp = miny;
+ miny = maxy;
+ maxy = tmp;
+ }
double thisx, thisy;
//don't use current bounds on first update
@@ -550,10 +604,21 @@
Py_XDECREF(xyin);
if (ngood) {
- _ll->x_api()->set_api(minx);
- _ll->y_api()->set_api(miny);
- _ur->x_api()->set_api(maxx);
- _ur->y_api()->set_api(maxy);
+ if (xreversed) {
+ _ll->x_api()->set_api(maxx);
+ _ur->x_api()->set_api(minx);
+ } else {
+ _ll->x_api()->set_api(minx);
+ _ur->x_api()->set_api(maxx);
+ }
+
+ if (yreversed) {
+ _ll->y_api()->set_api(maxy);
+ _ur->y_api()->set_api(miny);
+ } else {
+ _ll->y_api()->set_api(miny);
+ _ur->y_api()->set_api(maxy);
+ }
}
return Py::Object();
}
@@ -594,8 +659,24 @@
double minx = _ll->xval();
double maxx = _ur->xval();
+ int xreversed = 0;
+ if (minx > maxx) {
+ xreversed = 1;
+ double tmp = minx;
+ minx = maxx;
+ maxx = tmp;
+ }
+
+
double miny = _ll->yval();
double maxy = _ur->yval();
+ int yreversed = 0;
+ if (miny > maxy) {
+ yreversed = 1;
+ double tmp = miny;
+ miny = maxy;
+ maxy = tmp;
+ }
double thisx, thisy;
//don't use current bounds on first update
@@ -627,10 +708,21 @@
Py_XDECREF(y);
- _ll->x_api()->set_api(minx);
- _ll->y_api()->set_api(miny);
- _ur->x_api()->set_api(maxx);
- _ur->y_api()->set_api(maxy);
+ if (xreversed) {
+ _ll->x_api()->set_api(maxx);
+ _ur->x_api()->set_api(minx);
+ } else {
+ _ll->x_api()->set_api(minx);
+ _ur->x_api()->set_api(maxx);
+ }
+
+ if (yreversed) {
+ _ll->y_api()->set_api(maxy);
+ _ur->y_api()->set_api(miny);
+ } else {
+ _ll->y_api()->set_api(miny);
+ _ur->y_api()->set_api(maxy);
+ }
return Py::Object();
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2007-10-02 08:30:38
|
Revision: 3907
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3907&view=rev
Author: efiring
Date: 2007-10-02 01:30:29 -0700 (Tue, 02 Oct 2007)
Log Message:
-----------
matplotlib.use() raises an exception if called too late
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/__init__.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2007-10-01 11:53:52 UTC (rev 3906)
+++ trunk/matplotlib/CHANGELOG 2007-10-02 08:30:29 UTC (rev 3907)
@@ -1,3 +1,6 @@
+2007-10-01 Made matplotlib.use() raise an exception if called after
+ backends has been imported.
+
2007-09-30 Modified update* methods of Bbox and Interval so they
work with reversed axes. Prior to this, trying to
set the ticks on a reversed axis failed with an
Modified: trunk/matplotlib/lib/matplotlib/__init__.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/__init__.py 2007-10-01 11:53:52 UTC (rev 3906)
+++ trunk/matplotlib/lib/matplotlib/__init__.py 2007-10-02 08:30:29 UTC (rev 3907)
@@ -716,6 +716,9 @@
except:
from config import rcParams, rcdefaults
+_use_error_msg = """ matplotlib.use() must be called *before* pylab
+or matplotlib.backends is imported for the first time."""
+
def use(arg):
"""
Set the matplotlib backend to one of the known backends.
@@ -732,6 +735,8 @@
for the first time; or, if you are not using pylab, it must
be called before importing matplotlib.backends.
"""
+ if 'matplotlib.backends' in sys.modules:
+ raise RuntimeError(_use_error_msg)
be_parts = arg.split('.')
name = validate_backend(be_parts[0])
rcParams['backend'] = name
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ds...@us...> - 2007-10-05 18:56:16
|
Revision: 3923
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3923&view=rev
Author: dsdale
Date: 2007-10-05 11:56:10 -0700 (Fri, 05 Oct 2007)
Log Message:
-----------
remove generator expressions from texmanager and mpltraits
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/config/mpltraits.py
trunk/matplotlib/lib/matplotlib/texmanager.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2007-10-05 18:30:39 UTC (rev 3922)
+++ trunk/matplotlib/CHANGELOG 2007-10-05 18:56:10 UTC (rev 3923)
@@ -1,3 +1,6 @@
+2007-10-05 remove generator expressions from texmanager and mpltraits.
+ generator expressions are not supported by python-2.3 - DSD
+
2007-10-01 Made matplotlib.use() raise an exception if called after
backends has been imported.
Modified: trunk/matplotlib/lib/matplotlib/config/mpltraits.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/config/mpltraits.py 2007-10-05 18:30:39 UTC (rev 3922)
+++ trunk/matplotlib/lib/matplotlib/config/mpltraits.py 2007-10-05 18:56:10 UTC (rev 3923)
@@ -46,7 +46,7 @@
def info(self):
be = self.backends.keys()
be.sort
- return "one of %s"% ', '.join('%s'%i for i in be)
+ return "one of %s"% ', '.join(['%s'%i for i in be])
class BoolHandler(T.TraitHandler):
@@ -73,7 +73,7 @@
return self.error(object, name, value)
def info(self):
- return "one of %s"% ', '.join('%s'%i for i in self.bools.keys())
+ return "one of %s"% ', '.join(['%s'%i for i in self.bools.keys()])
flexible_true = T.Trait(True, BoolHandler())
flexible_false = T.Trait(False, BoolHandler())
Modified: trunk/matplotlib/lib/matplotlib/texmanager.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/texmanager.py 2007-10-05 18:30:39 UTC (rev 3922)
+++ trunk/matplotlib/lib/matplotlib/texmanager.py 2007-10-05 18:56:10 UTC (rev 3923)
@@ -110,7 +110,7 @@
_rc_cache = None
_rc_cache_keys = ('text.latex.preamble', )\
- + tuple('font.'+n for n in ('family', ) + font_families)
+ + tuple(['font.'+n for n in ('family', ) + font_families])
def __init__(self):
@@ -125,7 +125,7 @@
fontconfig = [self.font_family]
for font_family, font_family_attr in \
- ((ff, ff.replace('-', '_')) for ff in self.font_families):
+ [(ff, ff.replace('-', '_')) for ff in self.font_families]:
for font in rcParams['font.'+font_family]:
if font.lower() in self.font_info:
found_font = self.font_info[font.lower()]
@@ -163,7 +163,7 @@
def get_font_config(self):
"Reinitializes self if rcParams self depends on have changed."
if self._rc_cache is None:
- self._rc_cache = dict((k,None) for k in self._rc_cache_keys)
+ self._rc_cache = dict([(k,None) for k in self._rc_cache_keys])
changed = [par for par in self._rc_cache_keys if rcParams[par] != \
self._rc_cache[par]]
if changed:
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2007-10-08 12:45:25
|
Revision: 3927
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3927&view=rev
Author: mdboom
Date: 2007-10-08 05:45:23 -0700 (Mon, 08 Oct 2007)
Log Message:
-----------
Save image resolution in the PNG file.
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/backends/backend_agg.py
trunk/matplotlib/lib/matplotlib/backends/backend_gtkagg.py
trunk/matplotlib/src/_backend_agg.cpp
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_agg.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_agg.py 2007-10-05 22:11:32 UTC (rev 3926)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_agg.py 2007-10-08 12:45:23 UTC (rev 3927)
@@ -415,5 +415,5 @@
def print_png(self, filename, *args, **kwargs):
self.draw()
- self.get_renderer()._renderer.write_png(str(filename))
+ self.get_renderer()._renderer.write_png(str(filename), self.figure.dpi.get())
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_gtkagg.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_gtkagg.py 2007-10-05 22:11:32 UTC (rev 3926)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_gtkagg.py 2007-10-08 12:45:23 UTC (rev 3927)
@@ -97,6 +97,8 @@
0, 0, 0, 0, w, h)
if DEBUG: print 'FigureCanvasGTKAgg.done'
+ def print_png(self, filename, *args, **kwargs):
+ return FigureCanvasAgg.print_png(self, filename, *args, **kwargs)
"""\
Traceback (most recent call last):
Modified: trunk/matplotlib/src/_backend_agg.cpp
===================================================================
--- trunk/matplotlib/src/_backend_agg.cpp 2007-10-05 22:11:32 UTC (rev 3926)
+++ trunk/matplotlib/src/_backend_agg.cpp 2007-10-08 12:45:23 UTC (rev 3927)
@@ -2283,7 +2283,7 @@
{
_VERBOSE("RendererAgg::write_png");
- args.verify_length(1);
+ args.verify_length(1, 2);
FILE *fp;
Py::Object o = Py::Object(args[0]);
@@ -2344,6 +2344,13 @@
width, height, 8,
PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
+
+ // Save the dpi of the image in the file
+ if (args.size() == 2) {
+ double dpi = Py::Float(args[1]);
+ size_t dots_per_meter = (size_t)(dpi / (2.54 / 100.0));
+ png_set_pHYs(png_ptr, info_ptr, dots_per_meter, dots_per_meter, PNG_RESOLUTION_METER);
+ }
// this a a color image!
sig_bit.gray = 0;
@@ -2619,7 +2626,7 @@
add_varargs_method("write_rgba", &RendererAgg::write_rgba,
"write_rgba(fname)");
add_varargs_method("write_png", &RendererAgg::write_png,
- "write_png(fname)");
+ "write_png(fname, dpi=None)");
add_varargs_method("tostring_rgb", &RendererAgg::tostring_rgb,
"s = tostring_rgb()");
add_varargs_method("tostring_argb", &RendererAgg::tostring_argb,
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2007-10-14 19:00:52
|
Revision: 3941
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3941&view=rev
Author: jdh2358
Date: 2007-10-14 12:00:50 -0700 (Sun, 14 Oct 2007)
Log Message:
-----------
added ellipse compare script
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/backends/backend_agg.py
trunk/matplotlib/lib/matplotlib/backends/backend_ps.py
Added Paths:
-----------
trunk/matplotlib/unit/ellipse_compare.py
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_agg.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_agg.py 2007-10-14 14:16:48 UTC (rev 3940)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_agg.py 2007-10-14 19:00:50 UTC (rev 3941)
@@ -143,7 +143,7 @@
"""
if __debug__: verbose.report('RendererAgg.draw_arc', 'debug-annoying')
self._renderer.draw_ellipse(
- gcEdge, rgbFace, x, y, width/2, height/2, rotation) # ellipse takes radius
+ gcEdge, rgbFace, x, y, width/2., height/2., rotation) # ellipse takes radius
def draw_line(self, gc, x1, y1, x2, y2):
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_ps.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_ps.py 2007-10-14 14:16:48 UTC (rev 3940)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_ps.py 2007-10-14 19:00:50 UTC (rev 3941)
@@ -882,7 +882,7 @@
"""
# local variable eliminates all repeated attribute lookups
write = self._pswriter.write
-
+ write('gsave\n')
if debugPS and command:
write("% "+command+"\n")
@@ -915,7 +915,7 @@
write("stroke\n")
if cliprect:
write("grestore\n")
-
+ write('grestore\n')
def push_gc(self, gc, store=1):
"""
Push the current onto stack, with the exception of the clip box, which
Added: trunk/matplotlib/unit/ellipse_compare.py
===================================================================
--- trunk/matplotlib/unit/ellipse_compare.py (rev 0)
+++ trunk/matplotlib/unit/ellipse_compare.py 2007-10-14 19:00:50 UTC (rev 3941)
@@ -0,0 +1,53 @@
+"""
+Compare the ellipse generated with arcs versus a polygonal approximation
+"""
+import numpy as npy
+from matplotlib import patches
+from pylab import figure, show
+
+xcenter, ycenter = 0.38, 0.52
+#xcenter, ycenter = 0., 0.
+width, height = 1e-1, 3e-1
+angle = -30
+
+theta = npy.arange(0.0, 360.0, 1.0)*npy.pi/180.0
+x = width/2. * npy.cos(theta)
+y = height/2. * npy.sin(theta)
+
+rtheta = angle*npy.pi/180.
+R = npy.array([
+ [npy.cos(rtheta), -npy.sin(rtheta)],
+ [npy.sin(rtheta), npy.cos(rtheta)],
+ ])
+
+
+x, y = npy.dot(R, npy.array([x, y]))
+x += xcenter
+y += ycenter
+
+fig = figure()
+ax = fig.add_subplot(211, aspect='auto')
+ax.fill(x, y, alpha=0.2, facecolor='yellow')
+
+e1 = patches.Ellipse((xcenter, ycenter), width, height,
+ angle=angle, linewidth=2, fill=False)
+
+ax.add_artist(e1)
+
+ax = fig.add_subplot(212, aspect='equal')
+ax.fill(x, y, alpha=0.2, facecolor='yellow')
+e2 = patches.Ellipse((xcenter, ycenter), width, height,
+ angle=angle, linewidth=2, fill=False)
+
+
+ax.add_artist(e2)
+ax.autoscale_view()
+
+
+ax.set_xlim(0.2, .5)
+ax.set_ylim(0.3, 0.7)
+
+#fig.savefig('ellipse_compare.png')
+#fig.savefig('ellipse_compare.ps')
+
+show()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2007-10-15 20:00:56
|
Revision: 3949
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3949&view=rev
Author: jdh2358
Date: 2007-10-15 13:00:54 -0700 (Mon, 15 Oct 2007)
Log Message:
-----------
fixed an aspect=auto problem with bezier ellipse approx
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/boilerplate.py
trunk/matplotlib/lib/matplotlib/backends/backend_ps.py
trunk/matplotlib/lib/matplotlib/cbook.py
trunk/matplotlib/lib/matplotlib/mlab.py
trunk/matplotlib/lib/matplotlib/patches.py
trunk/matplotlib/src/_backend_agg.cpp
trunk/matplotlib/src/_transforms.cpp
trunk/matplotlib/unit/ellipse_compare.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2007-10-15 14:03:19 UTC (rev 3948)
+++ trunk/matplotlib/CHANGELOG 2007-10-15 20:00:54 UTC (rev 3949)
@@ -1,3 +1,12 @@
+2007-10-15 Fixed a bug in patches.Ellipse that was broken for
+ aspect='auto'. Scale free ellipses now work properly for
+ equal and auto on Agg and PS, and they fall back on a
+ polygonal approximation for nonlinear transformations until
+ we convince oursleves that the spline approximation holds
+ for nonlinear transformations. Added
+ unit/ellipse_compare.py to compare spline with vertex
+ approx for both aspects. JDH
+
2007-10-05 remove generator expressions from texmanager and mpltraits.
generator expressions are not supported by python-2.3 - DSD
Modified: trunk/matplotlib/boilerplate.py
===================================================================
--- trunk/matplotlib/boilerplate.py 2007-10-15 14:03:19 UTC (rev 3948)
+++ trunk/matplotlib/boilerplate.py 2007-10-15 20:00:54 UTC (rev 3949)
@@ -2,10 +2,9 @@
# file is pasted into pylab.py. We did try to do this the smart way,
# with callable functions and new.function, but could never get the
# docstrings right for python2.2. See
-# http://groups-beta.google.com/group/comp.lang.python/messages/1b14640f3a4ad3dc,b3d7453af21e5f82,17739e70ac6f710c,9d5291fce29cbbb1,c5b578e4ffc6af28,056ff270daa2f414?thread_id=dcd63ec13096a0f6&mode=thread
+# http://groups.google.com/group/comp.lang.python/browse_frm/thread/dcd63ec13096a0f6/1b14640f3a4ad3dc?#1b14640f3a4ad3dc
-
# note we check for __doc__ is not None since py2exe optimize removes
# the docstrings
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_ps.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_ps.py 2007-10-15 14:03:19 UTC (rev 3948)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_ps.py 2007-10-15 20:00:54 UTC (rev 3949)
@@ -329,7 +329,7 @@
size = prop.get_size_in_points()
font.set_size(size, 72.0)
return font
-
+
def draw_arc(self, gc, rgbFace, x, y, width, height, angle1, angle2, rotation):
"""
Draw an arc centered at x,y with width and height and angles
@@ -340,7 +340,7 @@
"""
ps = '%f %f translate\n%f rotate\n%f %f translate\n%s ellipse' % \
(x, y, rotation, -x, -y, _nums_to_str(angle1, angle2, 0.5*width, 0.5*height, x, y))
- self._draw_ps(ps, gc, rgbFace, "arc")
+ self._draw_ps(ps, gc, None, "arc")
def _rgba(self, im):
return im.as_rgba_str()
@@ -519,9 +519,42 @@
end += step
if cliprect: write('grestore\n')
- def draw_path(self,gc,rgbFace,path,trans):
- pass
+ def draw_path(self, gc, rgbFace, path):
+ ps_cmd = []
+ ps_cmd.append('newpath')
+
+ while 1:
+ code, xp, yp = path.vertex()
+
+ #print code, xp, yp
+
+ if code == agg.path_cmd_stop:
+ ps_cmd.append('closepath') # Hack, path_cmd_end_poly not found
+ break
+ elif code == agg.path_cmd_move_to:
+ ps_cmd.append('%g %g m' % (xp,yp))
+ elif code == agg.path_cmd_line_to:
+ ps_cmd.append('%g %g l' % (xp,yp))
+ elif code == agg.path_cmd_curve3:
+ pass
+ elif code == agg.path_cmd_curve4:
+ verts = [xp, yp]
+ verts.extend(path.vertex()[1:])
+ verts.extend(path.vertex()[1:])
+ ps_cmd.append('%g %g %g %g %g %g curveto'%tuple(verts))
+ elif code == agg.path_cmd_end_poly:
+ ps_cmd.append('closepath')
+ elif code == agg.path_cmd_mask:
+ pass
+ else:
+ pass
+ #print code
+
+ ps = '\n'.join(ps_cmd)
+
+ self._draw_ps(ps, gc, rgbFace, "custom_path")
+
def draw_lines(self, gc, x, y, transform):
"""
x and y are npy.equal length arrays, draw lines connecting each
@@ -883,6 +916,7 @@
# local variable eliminates all repeated attribute lookups
write = self._pswriter.write
write('gsave\n')
+
if debugPS and command:
write("% "+command+"\n")
@@ -916,6 +950,7 @@
if cliprect:
write("grestore\n")
write('grestore\n')
+
def push_gc(self, gc, store=1):
"""
Push the current onto stack, with the exception of the clip box, which
@@ -1581,5 +1616,15 @@
0 0 1 5 3 roll arc
setmatrix
closepath
- } bind def"""
+ } bind def""",
+ """/unitcircle {
+ newpath
+-1. 0. moveto
+-1.0 0.552284749831 -0.552284749831 1.0 0.0 1.0 curveto
+0.552284749831 1.0 1.0 0.552284749831 1.0 0.0 curveto
+1.0 -0.552284749831 0.552284749831 -1.0 0.0 -1.0 curveto
+-0.552284749831 -1.0 -1.0 -0.552284749831 -1.0 0.0 curveto
+closepath
+ } bind def""",
+
]
Modified: trunk/matplotlib/lib/matplotlib/cbook.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/cbook.py 2007-10-15 14:03:19 UTC (rev 3948)
+++ trunk/matplotlib/lib/matplotlib/cbook.py 2007-10-15 20:00:54 UTC (rev 3949)
@@ -230,17 +230,18 @@
except TypeError: return False
else: return True
-def to_filehandle(fname):
+def to_filehandle(fname, flag='r'):
"""
fname can be a filename or a file handle. Support for gzipped
- files is automatic, if the filename ends in .gz
+ files is automatic, if the filename ends in .gz. flag is a
+ read/write flag for file
"""
if is_string_like(fname):
if fname.endswith('.gz'):
import gzip
- fh = gzip.open(fname)
+ fh = gzip.open(fname, flag)
else:
- fh = file(fname)
+ fh = file(fname, flag)
elif hasattr(fname, 'seek'):
fh = fname
else:
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2007-10-15 14:03:19 UTC (rev 3948)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2007-10-15 20:00:54 UTC (rev 3949)
@@ -809,6 +809,8 @@
If p is a scalar, the largest value of x less than or equal
to the p percentage point in the sequence is returned.
"""
+
+
x = npy.ravel(x)
x.sort()
Nx = len(x)
@@ -1282,7 +1284,10 @@
converterd, if not None, is a dictionary mapping column number or
munged column name to a converter function
- See examples/loadrec.py
+ names, if not None, is a list of header names. In this case, no
+ header will be read from the file
+
+ if no rows are found, None is returned See examples/loadrec.py
"""
if converterd is None:
@@ -1291,9 +1296,42 @@
import dateutil.parser
parsedate = dateutil.parser.parse
+
fh = cbook.to_filehandle(fname)
- reader = csv.reader(fh, delimiter=delimiter)
+
+ class FH:
+ """
+ for space delimited files, we want different behavior than
+ comma or tab. Generally, we want multiple spaces to be
+ treated as a single separator, whereas with comma and tab we
+ want multiple commas to return multiple (empty) fields. The
+ join/strip trick below effects this
+ """
+ def __init__(self, fh):
+ self.fh = fh
+
+ def close(self):
+ self.fh.close()
+
+ def seek(self, arg):
+ self.fh.seek(arg)
+
+ def fix(self, s):
+ return ' '.join(s.split())
+
+
+ def next(self):
+ return self.fix(self.fh.next())
+
+ def __iter__(self):
+ for line in self.fh:
+ yield self.fix(line)
+
+ if delimiter==' ':
+ fh = FH(fh)
+
+ reader = csv.reader(fh, delimiter=delimiter)
def process_skiprows(reader):
if skiprows:
for i, row in enumerate(reader):
@@ -1388,9 +1426,131 @@
rows.append([func(val) for func, val in zip(converters, row)])
fh.close()
+ if not len(rows):
+ return None
r = npy.rec.fromrecords(rows, names=names)
return r
+
+def rec2csv(r, fname, delimiter=','):
+ """
+ Save the data from numpy record array r into a comma/space/tab
+ delimited file. The record array dtype names will be used for
+ column headers.
+
+
+ fname - can be a filename or a file handle. Support for gzipped
+ files is automatic, if the filename ends in .gz
+ """
+ fh = cbook.to_filehandle(fname, 'w')
+ writer = csv.writer(fh, delimiter=delimiter)
+ header = r.dtype.names
+ writer.writerow(header)
+ for row in r:
+ writer.writerow(map(str, row))
+ fh.close()
+
+# some record array helpers
+def rec_append_field(rec, name, arr, dtype=None):
+ 'return a new record array with field name populated with data from array arr'
+ arr = npy.asarray(arr)
+ if dtype is None:
+ dtype = arr.dtype
+ newdtype = npy.dtype(rec.dtype.descr + [(name, dtype)])
+ newrec = npy.empty(rec.shape, dtype=newdtype)
+ for field in rec.dtype.fields:
+ newrec[field] = rec[field]
+ newrec[name] = arr
+ return newrec.view(npy.recarray)
+
+
+def rec_drop_fields(rec, names):
+ 'return a new numpy record array with fields in names dropped'
+
+ names = set(names)
+ Nr = len(rec)
+
+ newdtype = npy.dtype([(name, rec.dtype[name]) for name in rec.dtype.names
+ if name not in names])
+
+ newrec = npy.empty(Nr, dtype=newdtype)
+ for field in newdtype.names:
+ newrec[field] = rec[field]
+
+ return newrec.view(npy.recarray)
+
+
+def rec_join(key, r1, r2):
+ """
+ join record arrays r1 and r2 on key; key is a tuple of field
+ names. if r1 and r2 have equal values on all the keys in the key
+ tuple, then their fields will be merged into a new record array
+ containing the union of the fields of r1 and r2
+ """
+
+ for name in key:
+ if name not in r1.dtype.names:
+ raise ValueError('r1 does not have key field %s'%name)
+ if name not in r2.dtype.names:
+ raise ValueError('r2 does not have key field %s'%name)
+
+ def makekey(row):
+ return tuple([row[name] for name in key])
+
+
+ names = list(r1.dtype.names) + [name for name in r2.dtype.names if name not in set(r1.dtype.names)]
+
+
+
+ r1d = dict([(makekey(row),i) for i,row in enumerate(r1)])
+ r2d = dict([(makekey(row),i) for i,row in enumerate(r2)])
+
+ r1keys = set(r1d.keys())
+ r2keys = set(r2d.keys())
+
+ keys = r1keys & r2keys
+
+ r1ind = [r1d[k] for k in keys]
+ r2ind = [r2d[k] for k in keys]
+
+
+ r1 = r1[r1ind]
+ r2 = r2[r2ind]
+
+ r2 = rec_drop_fields(r2, r1.dtype.names)
+
+
+ def key_desc(name):
+ 'if name is a string key, use the larger size of r1 or r2 before merging'
+ dt1 = r1.dtype[name]
+ if dt1.type != npy.string_:
+ return (name, dt1.descr[0][1])
+
+ dt2 = r1.dtype[name]
+ assert dt2==dt1
+ if dt1.num>dt2.num:
+ return (name, dt1.descr[0][1])
+ else:
+ return (name, dt2.descr[0][1])
+
+
+
+ keydesc = [key_desc(name) for name in key]
+
+ newdtype = npy.dtype(keydesc +
+ [desc for desc in r1.dtype.descr if desc[0] not in key ] +
+ [desc for desc in r2.dtype.descr if desc[0] not in key ] )
+
+
+ newrec = npy.empty(len(r1), dtype=newdtype)
+ for field in r1.dtype.names:
+ newrec[field] = r1[field]
+
+ for field in r2.dtype.names:
+ newrec[field] = r2[field]
+
+ return newrec.view(npy.recarray)
+
def slopes(x,y):
"""
SLOPES calculate the slope y'(x) Given data vectors X and Y SLOPES
Modified: trunk/matplotlib/lib/matplotlib/patches.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/patches.py 2007-10-15 14:03:19 UTC (rev 3948)
+++ trunk/matplotlib/lib/matplotlib/patches.py 2007-10-15 20:00:54 UTC (rev 3949)
@@ -11,8 +11,9 @@
import matplotlib.nxutils as nxutils
import matplotlib.mlab as mlab
import matplotlib.artist as artist
+from matplotlib import transforms as mtrans
+import agg
-
# these are not available for the object inspector until after the
# class is build so we define an initial set here for the init
# function and they will be overridden after object defn
@@ -749,6 +750,32 @@
"""
A scale-free ellipse
"""
+ offset = 4.0 * (npy.sqrt(2) - 1) / 3.0
+
+ circle = npy.array([
+ [-1.0, 0.0],
+
+ [-1.0, offset],
+ [-offset, 1.0],
+ [0.0, 1.0],
+
+ [offset, 1.0],
+ [1.0, offset],
+ [1.0, 0.0],
+
+ [1.0, -offset],
+ [offset, -1.0],
+ [0.0, -1.0],
+
+ [-offset, -1.0],
+ [-1.0, -offset],
+ [-1.0, 0.0],
+
+ [-1.0, 0.0]
+ ],
+ npy.float_)
+
+
def __str__(self):
return "Ellipse(%d,%d;%dx%d)"%(self.center[0],self.center[1],self.width,self.height)
@@ -777,14 +804,29 @@
return inside,{}
def get_verts(self):
- x,y = self.center
- l,r = x-self.width/2.0, x+self.width/2.0
- b,t = y-self.height/2.0, y+self.height/2.0
- x,l,r = self.convert_xunits((x,l,r))
- y,b,t = self.convert_yunits((y,b,t))
- verts = ((x,y), (l,y), (x,t), (r,y), (x,b))
- return npy.array(verts, npy.float)
+ xcenter, ycenter = self.center
+
+ width, height = self.width, self.height
+ angle = self.angle
+
+ theta = npy.arange(0.0, 360.0, 1.0)*npy.pi/180.0
+ x = width/2. * npy.cos(theta)
+ y = height/2. * npy.sin(theta)
+
+ rtheta = angle*npy.pi/180.
+ R = npy.array([
+ [npy.cos(rtheta), -npy.sin(rtheta)],
+ [npy.sin(rtheta), npy.cos(rtheta)],
+ ])
+
+
+ x, y = npy.dot(R, npy.array([x, y]))
+ x += xcenter
+ y += ycenter
+
+ return zip(x, y)
+
def draw(self, renderer):
if not self.get_visible(): return
#renderer.open_group('patch')
@@ -803,35 +845,72 @@
if self._hatch:
gc.set_hatch(self._hatch )
- tverts = self.get_transform().seq_xy_tups(self.get_verts())
- # center is first vert
- # take the abs since we do not want a negative width or height as this
- # will cause the renderer to misbehave.
- width = abs(tverts[3,0] - tverts[1,0])
- height = abs(tverts[2,1] - tverts[4,1])
+ offset = self.offset
- # we also have to transform the angle, do this using polar coordinates
- # convert to radians
- angle = self.angle * math.pi / 180.0
+
- # convert the angle to polar coordinates (Assume r = 1.0)
- anglex = math.cos(angle)
- angley = math.sin(angle)
+ if not hasattr(renderer, 'draw_path'):
+ verbose.report('patches.Ellipse renderer does not support path drawing; falling back on vertex approximation for nonlinear transformation')
+ renderer.draw_polygon(gc, rgbFace, self.get_verts())
+ return
+
- # transform the angle vertex and the origin
- angle_verts = npy.array(((anglex, angley), (0.0, 0.0)), npy.float)
- angle_verts = self.get_transform().seq_xy_tups(angle_verts)
+ x, y = self.center
+ theta = self.angle * npy.pi/180.
+ T = npy.array([
+ [1, 0, x],
+ [0, 1, y],
+ [0, 0, 1]])
- # get the new x and y coords (from the origin)
- anglex = angle_verts[0, 0] - angle_verts[1, 0]
- angley = angle_verts[0, 1] - angle_verts[1, 1]
+ S = npy.array([
+ [self.width/2., 0, 0],
+ [0, self.height/2., 0],
+ [0, 0, 1]])
- # convert back to an angle (in degrees)
- angle = math.atan2(angley, anglex) * 180.0 / math.pi
- renderer.draw_arc(gc, rgbFace, tverts[0,0], tverts[0,1],
- width, height, 0.0, 360.0, angle)
+
+ # rotate by theta
+ R = npy.array([
+ [npy.cos(theta), -npy.sin(theta), 0],
+ [npy.sin(theta), npy.cos(theta), 0],
+ [0, 0, 1]])
+ # transform unit circle into ellipse
+ E = npy.dot(T, npy.dot(R, S))
+
+
+ # Apply the display affine
+ sx, b, c, sy, tx, ty = self.get_transform().as_vec6_val()
+
+ # display coords
+ D = npy.array([
+ [sx, b, tx],
+ [c, sy, ty],
+ [0, 0, 1]], npy.float_)
+
+ M = npy.dot(D,E)
+
+ C = npy.ones((3, len(self.circle)))
+ C[0:2,:] = self.circle.T
+
+ ellipse = npy.dot(M, C).T[:,:2]
+
+ path = agg.path_storage()
+ path.move_to(*ellipse[0])
+ verts = ellipse[1:4].flat
+ path.curve4(*verts)
+ verts = ellipse[4:7].flat
+ path.curve4(*verts)
+ verts = ellipse[7:10].flat
+ path.curve4(*verts)
+ verts = ellipse[10:13].flat
+ path.curve4(*verts)
+ path.close_polygon()
+
+ renderer.draw_path(gc, rgbFace, path)
+
+
+
class Circle(Ellipse):
"""
A circle patch
Modified: trunk/matplotlib/src/_backend_agg.cpp
===================================================================
--- trunk/matplotlib/src/_backend_agg.cpp 2007-10-15 14:03:19 UTC (rev 3948)
+++ trunk/matplotlib/src/_backend_agg.cpp 2007-10-15 20:00:54 UTC (rev 3949)
@@ -2052,7 +2052,7 @@
theRasterizer->reset_clipping();
_VERBOSE("RendererAgg::draw_path");
- args.verify_length(4);
+ args.verify_length(3);
GCAgg gc = GCAgg(args[0], dpi);
facepair_t face = _get_rgba_face(args[1], gc.alpha);
@@ -2064,43 +2064,20 @@
throw Py::TypeError("Could not convert path_storage");
- Transformation* mpltransform = static_cast<Transformation*>(args[3].ptr());
- double a, b, c, d, tx, ty;
- try {
- mpltransform->affine_params_api(&a, &b, &c, &d, &tx, &ty);
- }
- catch(...) {
- throw Py::ValueError("Domain error on affine_params_api in RendererAgg::draw_path");
- }
-
- agg::trans_affine xytrans = agg::trans_affine(a,b,c,d,tx,ty);
-
double heightd = double(height);
- agg::path_storage tpath; // the mpl transformed path
- bool needNonlinear = mpltransform->need_nonlinear_api();
+ agg::path_storage tpath; // the flipped path
size_t Nx = path->total_vertices();
double x, y;
unsigned cmd;
bool curvy = false;
for (size_t i=0; i<Nx; i++) {
+
+ if (cmd==agg::path_cmd_curve3 || cmd==agg::path_cmd_curve4) curvy=true;
cmd = path->vertex(i, &x, &y);
- if (cmd==agg::path_cmd_curve3 || cmd==agg::path_cmd_curve4) curvy=true;
- if (needNonlinear)
- try {
- mpltransform->nonlinear_only_api(&x, &y);
- }
- catch (...) {
- throw Py::ValueError("Domain error on nonlinear_only_api in RendererAgg::draw_path");
-
- }
-
- //use agg's transformer?
- xytrans.transform(&x, &y);
- y = heightd - y; //flipy
- tpath.add_vertex(x,y,cmd);
+ tpath.add_vertex(x, heightd-y, cmd);
}
-
+ set_clipbox_rasterizer(gc.cliprect);
_fill_and_stroke(tpath, gc, face, curvy);
return Py::Object();
Modified: trunk/matplotlib/src/_transforms.cpp
===================================================================
--- trunk/matplotlib/src/_transforms.cpp 2007-10-15 14:03:19 UTC (rev 3948)
+++ trunk/matplotlib/src/_transforms.cpp 2007-10-15 20:00:54 UTC (rev 3949)
@@ -1974,6 +1974,7 @@
*ty = _ty->val();
}
+
Py::Object
Affine::as_vec6(const Py::Tuple &args) {
_VERBOSE("Affine::as_vec6");
Modified: trunk/matplotlib/unit/ellipse_compare.py
===================================================================
--- trunk/matplotlib/unit/ellipse_compare.py 2007-10-15 14:03:19 UTC (rev 3948)
+++ trunk/matplotlib/unit/ellipse_compare.py 2007-10-15 20:00:54 UTC (rev 3949)
@@ -27,27 +27,22 @@
fig = figure()
ax = fig.add_subplot(211, aspect='auto')
-ax.fill(x, y, alpha=0.2, facecolor='yellow')
+ax.fill(x, y, alpha=0.2, facecolor='yellow', edgecolor='yellow', linewidth=1, zorder=1)
e1 = patches.Ellipse((xcenter, ycenter), width, height,
- angle=angle, linewidth=2, fill=False)
+ angle=angle, linewidth=2, fill=False, zorder=2)
-ax.add_artist(e1)
+ax.add_patch(e1)
ax = fig.add_subplot(212, aspect='equal')
-ax.fill(x, y, alpha=0.2, facecolor='yellow')
+ax.fill(x, y, alpha=0.2, facecolor='green', edgecolor='green', zorder=1)
e2 = patches.Ellipse((xcenter, ycenter), width, height,
- angle=angle, linewidth=2, fill=False)
+ angle=angle, linewidth=2, fill=False, zorder=2)
-ax.add_artist(e2)
-ax.autoscale_view()
+ax.add_patch(e2)
-
-ax.set_xlim(0.2, .5)
-ax.set_ylim(0.3, 0.7)
-
#fig.savefig('ellipse_compare.png')
-#fig.savefig('ellipse_compare.ps')
+fig.savefig('ellipse_compare')
show()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2007-10-16 13:46:01
|
Revision: 3954
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3954&view=rev
Author: jdh2358
Date: 2007-10-16 06:45:59 -0700 (Tue, 16 Oct 2007)
Log Message:
-----------
restored unit support for ellipses -- and added examples/units/ellipse_with_units.py
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/patches.py
Added Paths:
-----------
trunk/matplotlib/examples/units/ellipse_with_units.py
Added: trunk/matplotlib/examples/units/ellipse_with_units.py
===================================================================
--- trunk/matplotlib/examples/units/ellipse_with_units.py (rev 0)
+++ trunk/matplotlib/examples/units/ellipse_with_units.py 2007-10-16 13:45:59 UTC (rev 3954)
@@ -0,0 +1,49 @@
+"""
+Compare the ellipse generated with arcs versus a polygonal approximation
+"""
+from basic_units import cm
+import numpy as npy
+from matplotlib import patches
+from pylab import figure, show
+
+xcenter, ycenter = 0.38*cm, 0.52*cm
+#xcenter, ycenter = 0., 0.
+width, height = 1e-1*cm, 3e-1*cm
+angle = -30
+
+theta = npy.arange(0.0, 360.0, 1.0)*npy.pi/180.0
+x = 0.5 * width * npy.cos(theta)
+y = 0.5 * height * npy.sin(theta)
+
+rtheta = angle*npy.pi/180.
+R = npy.array([
+ [npy.cos(rtheta), -npy.sin(rtheta)],
+ [npy.sin(rtheta), npy.cos(rtheta)],
+ ])
+
+
+x, y = npy.dot(R, npy.array([x, y]))
+x += xcenter
+y += ycenter
+
+fig = figure()
+ax = fig.add_subplot(211, aspect='auto')
+ax.fill(x, y, alpha=0.2, facecolor='yellow', edgecolor='yellow', linewidth=1, zorder=1)
+
+e1 = patches.Ellipse((xcenter, ycenter), width, height,
+ angle=angle, linewidth=2, fill=False, zorder=2)
+
+ax.add_patch(e1)
+
+ax = fig.add_subplot(212, aspect='equal')
+ax.fill(x, y, alpha=0.2, facecolor='green', edgecolor='green', zorder=1)
+e2 = patches.Ellipse((xcenter, ycenter), width, height,
+ angle=angle, linewidth=2, fill=False, zorder=2)
+
+
+ax.add_patch(e2)
+
+#fig.savefig('ellipse_compare.png')
+fig.savefig('ellipse_compare')
+
+show()
Modified: trunk/matplotlib/lib/matplotlib/patches.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/patches.py 2007-10-16 12:28:49 UTC (rev 3953)
+++ trunk/matplotlib/lib/matplotlib/patches.py 2007-10-16 13:45:59 UTC (rev 3954)
@@ -820,6 +820,8 @@
[npy.sin(rtheta), npy.cos(rtheta)],
])
+ x = self.convert_xunits(x)
+ y = self.convert_yunits(y)
x, y = npy.dot(R, npy.array([x, y]))
x += xcenter
@@ -845,10 +847,7 @@
if self._hatch:
gc.set_hatch(self._hatch )
- offset = self.offset
-
-
if not hasattr(renderer, 'draw_path'):
verbose.report('patches.Ellipse renderer does not support path drawing; falling back on vertex approximation for nonlinear transformation')
renderer.draw_polygon(gc, rgbFace, self.get_verts())
@@ -856,15 +855,23 @@
x, y = self.center
+ x = self.convert_xunits(x)
+ y = self.convert_yunits(y)
+
theta = self.angle * npy.pi/180.
T = npy.array([
[1, 0, x],
[0, 1, y],
[0, 0, 1]])
+ w, h = self.width/2, self.height/2.
+ w = self.convert_xunits(w)
+ h = self.convert_yunits(h)
+
+
S = npy.array([
- [self.width/2., 0, 0],
- [0, self.height/2., 0],
+ [w, 0, 0],
+ [0, h, 0],
[0, 0, 1]])
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|