You can subscribe to this list here.
| 2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
(115) |
Aug
(120) |
Sep
(137) |
Oct
(170) |
Nov
(461) |
Dec
(263) |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2008 |
Jan
(120) |
Feb
(74) |
Mar
(35) |
Apr
(74) |
May
(245) |
Jun
(356) |
Jul
(240) |
Aug
(115) |
Sep
(78) |
Oct
(225) |
Nov
(98) |
Dec
(271) |
| 2009 |
Jan
(132) |
Feb
(84) |
Mar
(74) |
Apr
(56) |
May
(90) |
Jun
(79) |
Jul
(83) |
Aug
(296) |
Sep
(214) |
Oct
(76) |
Nov
(82) |
Dec
(66) |
| 2010 |
Jan
(46) |
Feb
(58) |
Mar
(51) |
Apr
(77) |
May
(58) |
Jun
(126) |
Jul
(128) |
Aug
(64) |
Sep
(50) |
Oct
(44) |
Nov
(48) |
Dec
(54) |
| 2011 |
Jan
(68) |
Feb
(52) |
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(1) |
| 2018 |
Jan
|
Feb
|
Mar
|
Apr
|
May
(1) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
|
From: <ef...@us...> - 2009-07-31 05:22:49
|
Revision: 7312
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7312&view=rev
Author: efiring
Date: 2009-07-31 05:22:37 +0000 (Fri, 31 Jul 2009)
Log Message:
-----------
Removed the colormap data caching--it was trying to solve a non-problem.
Upon installation, the colormap data in _cm.py is compiled into _cm.pyc,
and importing that takes negligible time.
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/cm.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2009-07-31 02:48:18 UTC (rev 7311)
+++ trunk/matplotlib/CHANGELOG 2009-07-31 05:22:37 UTC (rev 7312)
@@ -1,7 +1,6 @@
2009-07-30 Add set_cmap and register_cmap, and improve get_cmap,
to provide convenient handling of user-generated
- colormaps. Reorganized _cm and cm modules, and added
- caching of the color data to reduce startup time. - EF
+ colormaps. Reorganized _cm and cm modules. - EF
2009-07-28 Quiver speed improved, thanks to tip by Ray Speth. -EF
Modified: trunk/matplotlib/lib/matplotlib/cm.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/cm.py 2009-07-31 02:48:18 UTC (rev 7311)
+++ trunk/matplotlib/lib/matplotlib/cm.py 2009-07-31 05:22:37 UTC (rev 7312)
@@ -1,44 +1,20 @@
"""
-This module contains the instantiations of color mapping classes
+This module provides a large set of colormaps, functions for
+registering new colormaps and for getting a colormap by name,
+and a mixin class for adding color mapping functionality.
+
"""
+
import os
-try:
- import cPickle as pickle
-except ImportError:
- import pickle
-
import numpy as np
from numpy import ma
import matplotlib as mpl
import matplotlib.colors as colors
import matplotlib.cbook as cbook
+from matplotlib._cm import datad
-LUTSIZE = mpl.rcParams['image.lut']
-_cmcache = os.path.join(mpl.get_configdir(), 'colormaps.cache')
-
-loaded = False
-try:
- c = open(_cmcache)
- datad = pickle.load(c)
- c.close()
- mpl.verbose.report("Using colormaps from %s" % _cmcache)
- loaded = True
-except:
- mpl.verbose.report("Could not load colormaps from %s" % _cmcache)
-
-if not loaded:
- from matplotlib._cm import datad
-
- try:
- c = open(_cmcache, 'w')
- pickle.dump(datad, c, 2)
- c.close()
- mpl.verbose.report("New colormap cache in %s" % _cmcache)
- except:
- mpl.verbose.report("Failed to generate colormap cache")
-
cmap_d = dict()
# reverse all the colormaps.
@@ -51,7 +27,10 @@
data_r[key] = valnew
return data_r
+LUTSIZE = mpl.rcParams['image.lut']
+
_cmapnames = datad.keys() # need this list because datad is changed in loop
+
for cmapname in _cmapnames:
cmapname_r = cmapname+'_r'
cmapdat_r = revcmap(datad[cmapname])
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2009-07-31 02:48:25
|
Revision: 7311
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7311&view=rev
Author: efiring
Date: 2009-07-31 02:48:18 +0000 (Fri, 31 Jul 2009)
Log Message:
-----------
Cache the color data to reduce startup time.
Also, cmap kwargs now accept colormap names as strings.
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/_cm.py
trunk/matplotlib/lib/matplotlib/axes.py
trunk/matplotlib/lib/matplotlib/cm.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2009-07-30 21:50:10 UTC (rev 7310)
+++ trunk/matplotlib/CHANGELOG 2009-07-31 02:48:18 UTC (rev 7311)
@@ -1,6 +1,7 @@
2009-07-30 Add set_cmap and register_cmap, and improve get_cmap,
to provide convenient handling of user-generated
- colormaps. - EF
+ colormaps. Reorganized _cm and cm modules, and added
+ caching of the color data to reduce startup time. - EF
2009-07-28 Quiver speed improved, thanks to tip by Ray Speth. -EF
Modified: trunk/matplotlib/lib/matplotlib/_cm.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/_cm.py 2009-07-30 21:50:10 UTC (rev 7310)
+++ trunk/matplotlib/lib/matplotlib/_cm.py 2009-07-31 02:48:18 UTC (rev 7311)
@@ -1,25 +1,15 @@
"""
-Color data and pre-defined cmap objects.
+Nothing here but dictionaries for generating LinearSegmentedColormaps,
+and a dictionary of these dictionaries.
-This is a helper for cm.py, originally part of that file.
-Separating the data (this file) from cm.py makes both easier
-to deal with.
-
-Objects visible in cm.py are the individual cmap objects ('autumn',
-etc.) and a dictionary, 'datad', including all of these objects.
"""
-import matplotlib as mpl
-import matplotlib.colors as colors
-LUTSIZE = mpl.rcParams['image.lut']
-
_binary_data = {
'red' : ((0., 1., 1.), (1., 0., 0.)),
'green': ((0., 1., 1.), (1., 0., 0.)),
'blue' : ((0., 1., 1.), (1., 0., 0.))
}
-
_bone_data = {'red': ((0., 0., 0.),(1.0, 1.0, 1.0)),
'green': ((0., 0., 0.),(1.0, 1.0, 1.0)),
'blue': ((0., 0., 0.),(1.0, 1.0, 1.0))}
@@ -379,44 +369,6 @@
(1.0, 0.80, 0.80)]}
-autumn = colors.LinearSegmentedColormap('autumn', _autumn_data, LUTSIZE)
-bone = colors.LinearSegmentedColormap('bone ', _bone_data, LUTSIZE)
-binary = colors.LinearSegmentedColormap('binary ', _binary_data, LUTSIZE)
-cool = colors.LinearSegmentedColormap('cool', _cool_data, LUTSIZE)
-copper = colors.LinearSegmentedColormap('copper', _copper_data, LUTSIZE)
-flag = colors.LinearSegmentedColormap('flag', _flag_data, LUTSIZE)
-gray = colors.LinearSegmentedColormap('gray', _gray_data, LUTSIZE)
-hot = colors.LinearSegmentedColormap('hot', _hot_data, LUTSIZE)
-hsv = colors.LinearSegmentedColormap('hsv', _hsv_data, LUTSIZE)
-jet = colors.LinearSegmentedColormap('jet', _jet_data, LUTSIZE)
-pink = colors.LinearSegmentedColormap('pink', _pink_data, LUTSIZE)
-prism = colors.LinearSegmentedColormap('prism', _prism_data, LUTSIZE)
-spring = colors.LinearSegmentedColormap('spring', _spring_data, LUTSIZE)
-summer = colors.LinearSegmentedColormap('summer', _summer_data, LUTSIZE)
-winter = colors.LinearSegmentedColormap('winter', _winter_data, LUTSIZE)
-spectral = colors.LinearSegmentedColormap('spectral', _spectral_data, LUTSIZE)
-
-
-
-datad = {
- 'autumn': _autumn_data,
- 'bone': _bone_data,
- 'binary': _binary_data,
- 'cool': _cool_data,
- 'copper': _copper_data,
- 'flag': _flag_data,
- 'gray' : _gray_data,
- 'hot': _hot_data,
- 'hsv': _hsv_data,
- 'jet' : _jet_data,
- 'pink': _pink_data,
- 'prism': _prism_data,
- 'spring': _spring_data,
- 'summer': _summer_data,
- 'winter': _winter_data,
- 'spectral': _spectral_data
- }
-
# 34 colormaps based on color specifications and designs
# developed by Cynthia Brewer (http://colorbrewer.org).
# The ColorBrewer palettes have been included under the terms
@@ -5859,48 +5811,26 @@
0.0078431377187371254, 0.0078431377187371254), (1.0,
0.0039215688593685627, 0.0039215688593685627)]}
-Accent = colors.LinearSegmentedColormap('Accent', _Accent_data, LUTSIZE)
-Blues = colors.LinearSegmentedColormap('Blues', _Blues_data, LUTSIZE)
-BrBG = colors.LinearSegmentedColormap('BrBG', _BrBG_data, LUTSIZE)
-BuGn = colors.LinearSegmentedColormap('BuGn', _BuGn_data, LUTSIZE)
-BuPu = colors.LinearSegmentedColormap('BuPu', _BuPu_data, LUTSIZE)
-Dark2 = colors.LinearSegmentedColormap('Dark2', _Dark2_data, LUTSIZE)
-GnBu = colors.LinearSegmentedColormap('GnBu', _GnBu_data, LUTSIZE)
-Greens = colors.LinearSegmentedColormap('Greens', _Greens_data, LUTSIZE)
-Greys = colors.LinearSegmentedColormap('Greys', _Greys_data, LUTSIZE)
-Oranges = colors.LinearSegmentedColormap('Oranges', _Oranges_data, LUTSIZE)
-OrRd = colors.LinearSegmentedColormap('OrRd', _OrRd_data, LUTSIZE)
-Paired = colors.LinearSegmentedColormap('Paired', _Paired_data, LUTSIZE)
-Pastel1 = colors.LinearSegmentedColormap('Pastel1', _Pastel1_data, LUTSIZE)
-Pastel2 = colors.LinearSegmentedColormap('Pastel2', _Pastel2_data, LUTSIZE)
-PiYG = colors.LinearSegmentedColormap('PiYG', _PiYG_data, LUTSIZE)
-PRGn = colors.LinearSegmentedColormap('PRGn', _PRGn_data, LUTSIZE)
-PuBu = colors.LinearSegmentedColormap('PuBu', _PuBu_data, LUTSIZE)
-PuBuGn = colors.LinearSegmentedColormap('PuBuGn', _PuBuGn_data, LUTSIZE)
-PuOr = colors.LinearSegmentedColormap('PuOr', _PuOr_data, LUTSIZE)
-PuRd = colors.LinearSegmentedColormap('PuRd', _PuRd_data, LUTSIZE)
-Purples = colors.LinearSegmentedColormap('Purples', _Purples_data, LUTSIZE)
-RdBu = colors.LinearSegmentedColormap('RdBu', _RdBu_data, LUTSIZE)
-RdGy = colors.LinearSegmentedColormap('RdGy', _RdGy_data, LUTSIZE)
-RdPu = colors.LinearSegmentedColormap('RdPu', _RdPu_data, LUTSIZE)
-RdYlBu = colors.LinearSegmentedColormap('RdYlBu', _RdYlBu_data, LUTSIZE)
-RdYlGn = colors.LinearSegmentedColormap('RdYlGn', _RdYlGn_data, LUTSIZE)
-Reds = colors.LinearSegmentedColormap('Reds', _Reds_data, LUTSIZE)
-Set1 = colors.LinearSegmentedColormap('Set1', _Set1_data, LUTSIZE)
-Set2 = colors.LinearSegmentedColormap('Set2', _Set2_data, LUTSIZE)
-Set3 = colors.LinearSegmentedColormap('Set3', _Set3_data, LUTSIZE)
-Spectral = colors.LinearSegmentedColormap('Spectral', _Spectral_data, LUTSIZE)
-YlGn = colors.LinearSegmentedColormap('YlGn', _YlGn_data, LUTSIZE)
-YlGnBu = colors.LinearSegmentedColormap('YlGnBu', _YlGnBu_data, LUTSIZE)
-YlOrBr = colors.LinearSegmentedColormap('YlOrBr', _YlOrBr_data, LUTSIZE)
-YlOrRd = colors.LinearSegmentedColormap('YlOrRd', _YlOrRd_data, LUTSIZE)
-gist_earth = colors.LinearSegmentedColormap('gist_earth', _gist_earth_data, LUTSIZE)
-gist_gray = colors.LinearSegmentedColormap('gist_gray', _gist_gray_data, LUTSIZE)
-gist_heat = colors.LinearSegmentedColormap('gist_heat', _gist_heat_data, LUTSIZE)
-gist_ncar = colors.LinearSegmentedColormap('gist_ncar', _gist_ncar_data, LUTSIZE)
-gist_rainbow = colors.LinearSegmentedColormap('gist_rainbow', _gist_rainbow_data, LUTSIZE)
-gist_stern = colors.LinearSegmentedColormap('gist_stern', _gist_stern_data, LUTSIZE)
-gist_yarg = colors.LinearSegmentedColormap('gist_yarg', _gist_yarg_data, LUTSIZE)
+datad = {
+ 'autumn': _autumn_data,
+ 'bone': _bone_data,
+ 'binary': _binary_data,
+ 'cool': _cool_data,
+ 'copper': _copper_data,
+ 'flag': _flag_data,
+ 'gray' : _gray_data,
+ 'hot': _hot_data,
+ 'hsv': _hsv_data,
+ 'jet' : _jet_data,
+ 'pink': _pink_data,
+ 'prism': _prism_data,
+ 'spring': _spring_data,
+ 'summer': _summer_data,
+ 'winter': _winter_data,
+ 'spectral': _spectral_data
+ }
+
+
datad['Accent']=_Accent_data
datad['Blues']=_Blues_data
datad['BrBG']=_BrBG_data
@@ -5944,19 +5874,7 @@
datad['gist_stern']=_gist_stern_data
datad['gist_yarg']=_gist_yarg_data
-# reverse all the colormaps.
-# reversed colormaps have '_r' appended to the name.
-def revcmap(data):
- data_r = {}
- for key, val in data.iteritems():
- valnew = [(1.-a, b, c) for a, b, c in reversed(val)]
- data_r[key] = valnew
- return data_r
-cmapnames = datad.keys()
-for cmapname in cmapnames:
- cmapname_r = cmapname+'_r'
- cmapdat_r = revcmap(datad[cmapname])
- datad[cmapname_r] = cmapdat_r
- locals()[cmapname_r] = colors.LinearSegmentedColormap(cmapname_r, cmapdat_r, LUTSIZE)
+
+
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2009-07-30 21:50:10 UTC (rev 7310)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2009-07-31 02:48:18 UTC (rev 7311)
@@ -3911,12 +3911,12 @@
*bbox_to_anchor* keyword argument. bbox_to_anchor can be an instance
of BboxBase(or its derivatives) or a tuple of 2 or 4 floats.
For example,
-
+
loc = 'upper right', bbox_to_anchor = (0.5, 0.5)
will place the legend so that the upper right corner of the legend at
the center of the axes.
-
+
The legend location can be specified in other coordinate, by using the
*bbox_transform* keyword.
@@ -3946,7 +3946,7 @@
*fancybox*: [ None | False | True ]
if True, draw a frame with a round fancybox. If None, use rc
-
+
*shadow*: [ None | False | True ]
If *True*, draw a shadow behind legend. If *None*, use rc settings.
@@ -5172,9 +5172,9 @@
arguments will be used only if *c* is an array of floats.
*cmap*: [ None | Colormap ]
- A :class:`matplotlib.colors.Colormap` instance. If *None*,
- defaults to rc ``image.cmap``. *cmap* is only used if *c*
- is an array of floats.
+ A :class:`matplotlib.colors.Colormap` instance or registered
+ name. If *None*, defaults to rc ``image.cmap``. *cmap* is
+ only used if *c* is an array of floats.
*norm*: [ None | Normalize ]
A :class:`matplotlib.colors.Normalize` instance is used to
@@ -5370,7 +5370,6 @@
if colors is None:
if norm is not None: assert(isinstance(norm, mcolors.Normalize))
- if cmap is not None: assert(isinstance(cmap, mcolors.Colormap))
collection.set_array(np.asarray(c))
collection.set_cmap(cmap)
collection.set_norm(norm)
@@ -5712,7 +5711,6 @@
accum = bins.searchsorted(accum)
if norm is not None: assert(isinstance(norm, mcolors.Normalize))
- if cmap is not None: assert(isinstance(cmap, mcolors.Colormap))
collection.set_array(accum)
collection.set_cmap(cmap)
collection.set_norm(norm)
@@ -6245,7 +6243,6 @@
if not self._hold: self.cla()
if norm is not None: assert(isinstance(norm, mcolors.Normalize))
- if cmap is not None: assert(isinstance(cmap, mcolors.Colormap))
if aspect is None: aspect = rcParams['image.aspect']
self.set_aspect(aspect)
im = mimage.AxesImage(self, cmap, norm, interpolation, origin, extent,
@@ -6490,7 +6487,6 @@
collection.set_alpha(alpha)
collection.set_array(C)
if norm is not None: assert(isinstance(norm, mcolors.Normalize))
- if cmap is not None: assert(isinstance(cmap, mcolors.Colormap))
collection.set_cmap(cmap)
collection.set_norm(norm)
if vmin is not None or vmax is not None:
@@ -6612,7 +6608,6 @@
collection.set_alpha(alpha)
collection.set_array(C)
if norm is not None: assert(isinstance(norm, mcolors.Normalize))
- if cmap is not None: assert(isinstance(cmap, mcolors.Colormap))
collection.set_cmap(cmap)
collection.set_norm(norm)
if vmin is not None or vmax is not None:
@@ -6719,7 +6714,6 @@
vmin = kwargs.pop('vmin', None)
vmax = kwargs.pop('vmax', None)
if norm is not None: assert(isinstance(norm, mcolors.Normalize))
- if cmap is not None: assert(isinstance(cmap, mcolors.Colormap))
C = args[-1]
nr, nc = C.shape
Modified: trunk/matplotlib/lib/matplotlib/cm.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/cm.py 2009-07-30 21:50:10 UTC (rev 7310)
+++ trunk/matplotlib/lib/matplotlib/cm.py 2009-07-31 02:48:18 UTC (rev 7311)
@@ -1,25 +1,68 @@
"""
This module contains the instantiations of color mapping classes
"""
+import os
+try:
+ import cPickle as pickle
+except ImportError:
+ import pickle
+
import numpy as np
from numpy import ma
import matplotlib as mpl
import matplotlib.colors as colors
import matplotlib.cbook as cbook
-from matplotlib._cm import *
-# Dictionary for user-registered colormaps:
+LUTSIZE = mpl.rcParams['image.lut']
+
+_cmcache = os.path.join(mpl.get_configdir(), 'colormaps.cache')
+
+loaded = False
+try:
+ c = open(_cmcache)
+ datad = pickle.load(c)
+ c.close()
+ mpl.verbose.report("Using colormaps from %s" % _cmcache)
+ loaded = True
+except:
+ mpl.verbose.report("Could not load colormaps from %s" % _cmcache)
+
+if not loaded:
+ from matplotlib._cm import datad
+
+ try:
+ c = open(_cmcache, 'w')
+ pickle.dump(datad, c, 2)
+ c.close()
+ mpl.verbose.report("New colormap cache in %s" % _cmcache)
+ except:
+ mpl.verbose.report("Failed to generate colormap cache")
+
cmap_d = dict()
-# Using this second dictionary allows us to handle any
-# Colormap instance; the built-in datad is only for
-# LinearSegmentedColormaps. The advantage of keeping
-# datad is that it delays the generation of the Colormap
-# instance until it is actually needed. Generating the
-# instance is fast enough, and typically done few enough
-# times, that there is no need to cache the result.
+# reverse all the colormaps.
+# reversed colormaps have '_r' appended to the name.
+def revcmap(data):
+ data_r = {}
+ for key, val in data.iteritems():
+ valnew = [(1.0-a, b, c) for a, b, c in reversed(val)]
+ data_r[key] = valnew
+ return data_r
+
+_cmapnames = datad.keys() # need this list because datad is changed in loop
+for cmapname in _cmapnames:
+ cmapname_r = cmapname+'_r'
+ cmapdat_r = revcmap(datad[cmapname])
+ datad[cmapname_r] = cmapdat_r
+ cmap_d[cmapname] = colors.LinearSegmentedColormap(
+ cmapname, datad[cmapname], LUTSIZE)
+ cmap_d[cmapname_r] = colors.LinearSegmentedColormap(
+ cmapname_r, cmapdat_r, LUTSIZE)
+
+locals().update(cmap_d)
+
def register_cmap(name=None, cmap=None, data=None, lut=None):
"""
Add a colormap to the set recognized by :func:`get_cmap`.
@@ -67,6 +110,11 @@
If *name* is a :class:`colors.Colormap` instance, it will be
returned.
+
+ If *lut* is not None it must be an integer giving the number of
+ entries desired in the lookup table, and *name* must be a
+ standard mpl colormap name with a corresponding data dictionary
+ in *datad*.
"""
if name is None:
name = mpl.rcParams['image.cmap']
@@ -75,15 +123,13 @@
return name
if name in cmap_d:
- return cmap_d[name]
+ if lut is None:
+ return cmap_d[name]
+ elif name in datad:
+ return colors.LinearSegmentedColormap(name, datad[name], lut)
+ else:
+ raise ValueError("Colormap %s is not recognized" % name)
- if name not in datad:
- raise ValueError("%s is not a known colormap name" % name)
-
- if lut is None:
- lut = mpl.rcParams['image.lut']
- return colors.LinearSegmentedColormap(name, datad[name], lut)
-
class ScalarMappable:
"""
This is a mixin class to support scalar -> RGBA mapping. Handles
@@ -105,7 +151,7 @@
self._A = None
self.norm = norm
- self.cmap = cmap
+ self.cmap = get_cmap(cmap)
self.colorbar = None
self.update_dict = {'array':False}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <evi...@us...> - 2009-07-30 21:50:20
|
Revision: 7310
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7310&view=rev
Author: evilguru
Date: 2009-07-30 21:50:10 +0000 (Thu, 30 Jul 2009)
Log Message:
-----------
Revert r7307 to the mathtex branch after a dicussion on the mailing list.
Modified Paths:
--------------
branches/mathtex/setup.py
branches/mathtex/setupext.py
Modified: branches/mathtex/setup.py
===================================================================
--- branches/mathtex/setup.py 2009-07-30 19:32:15 UTC (rev 7309)
+++ branches/mathtex/setup.py 2009-07-30 21:50:10 UTC (rev 7310)
@@ -42,8 +42,7 @@
check_for_qt, check_for_qt4, check_for_cairo, \
check_provide_pytz, check_provide_dateutil,\
check_for_dvipng, check_for_ghostscript, check_for_latex, \
- check_for_pdftops, check_for_datetime, options, build_png, \
- check_provide_mathtex, build_mathtex
+ check_for_pdftops, check_for_datetime, options, build_png
#import distutils.sysconfig
# jdh
@@ -129,9 +128,6 @@
if has_libpng and options['build_agg'] or options['build_image']:
build_png(ext_modules, packages)
-if has_libpng and options['provide_mathtex'] and check_provide_mathtex():
- build_mathtex(ext_modules, packages, package_data)
-
if options['build_windowing'] and sys.platform=='win32':
build_windowing(ext_modules, packages)
Modified: branches/mathtex/setupext.py
===================================================================
--- branches/mathtex/setupext.py 2009-07-30 19:32:15 UTC (rev 7309)
+++ branches/mathtex/setupext.py 2009-07-30 21:50:10 UTC (rev 7310)
@@ -98,7 +98,6 @@
'verbose': False,
'provide_pytz': 'auto',
'provide_dateutil': 'auto',
- 'provide_mathtex' : 'auto',
'build_agg': True,
'build_gtk': 'auto',
'build_gtkagg': 'auto',
@@ -127,10 +126,6 @@
"dateutil")
except: options['provide_dateutil'] = 'auto'
- try: options['provide_mathtex'] = config.getboolean("provide_packages",
- "mathtex")
- except: options['provide_mathtex'] = 'auto'
-
try: options['build_gtk'] = config.getboolean("gui_support", "gtk")
except: options['build_gtk'] = 'auto'
@@ -391,14 +386,6 @@
print_status("datetime", "present, version unknown")
return True
-def check_provide_mathtex():
- try:
- import mathtex
- except ImportError:
- print_status("mathtex", "matplotlib will provide")
- return True
- return False
-
def check_provide_pytz(hasdatetime=True):
if hasdatetime and (options['provide_pytz'] is True):
print_status("pytz", "matplotlib will provide")
@@ -558,7 +545,7 @@
else:
add_base_flags(module)
module.libraries.append('z')
-
+
# put this last for library link order
module.libraries.extend(std_libs)
@@ -1105,11 +1092,6 @@
ext_modules.append(module)
BUILT_FT2FONT = True
-def build_mathtex(ext_modules, packages, package_data):
- packages.append('mathtex/mathtex')
- packages.append('mathtex/mathtex.backends')
- package_data['mathtex'] = ['lib/mathtex/data/fonts/*.ttf']
-
def build_ttconv(ext_modules, packages):
global BUILT_TTCONV
if BUILT_TTCONV: return # only build it if you you haven't already
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2009-07-30 19:32:25
|
Revision: 7309
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7309&view=rev
Author: efiring
Date: 2009-07-30 19:32:15 +0000 (Thu, 30 Jul 2009)
Log Message:
-----------
User-generated colormaps are handled more easily.
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/doc/api/api_changes.rst
trunk/matplotlib/examples/pylab_examples/custom_cmap.py
trunk/matplotlib/lib/matplotlib/cm.py
trunk/matplotlib/lib/matplotlib/image.py
trunk/matplotlib/lib/matplotlib/pyplot.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2009-07-30 17:08:23 UTC (rev 7308)
+++ trunk/matplotlib/CHANGELOG 2009-07-30 19:32:15 UTC (rev 7309)
@@ -1,3 +1,7 @@
+2009-07-30 Add set_cmap and register_cmap, and improve get_cmap,
+ to provide convenient handling of user-generated
+ colormaps. - EF
+
2009-07-28 Quiver speed improved, thanks to tip by Ray Speth. -EF
2009-07-27 Simplify argument handling code for plot method. -EF
Modified: trunk/matplotlib/doc/api/api_changes.rst
===================================================================
--- trunk/matplotlib/doc/api/api_changes.rst 2009-07-30 17:08:23 UTC (rev 7308)
+++ trunk/matplotlib/doc/api/api_changes.rst 2009-07-30 19:32:15 UTC (rev 7309)
@@ -21,6 +21,11 @@
Changes beyond 0.98.x
=====================
+* User-generated colormaps can now be added to the set recognized
+ by :func:`matplotlib.cm.get_cmap`. Colormaps can be made the
+ default and applied to the current image using
+ :func:`matplotlib.pyplot.set_cmap`.
+
* changed use_mrecords default to False in mlab.csv2rec since this is
partially broken
Modified: trunk/matplotlib/examples/pylab_examples/custom_cmap.py
===================================================================
--- trunk/matplotlib/examples/pylab_examples/custom_cmap.py 2009-07-30 17:08:23 UTC (rev 7308)
+++ trunk/matplotlib/examples/pylab_examples/custom_cmap.py 2009-07-30 19:32:15 UTC (rev 7309)
@@ -103,11 +103,25 @@
(1.0, 0.0, 0.0))
}
+# Now we will use this example to illustrate 3 ways of
+# handling custom colormaps.
+# First, the most direct and explicit:
blue_red1 = LinearSegmentedColormap('BlueRed1', cdict1)
+
+# Second, create the map explicitly and register it.
+# Like the first method, this method works with any kind
+# of Colormap, not just
+# a LinearSegmentedColormap:
+
blue_red2 = LinearSegmentedColormap('BlueRed2', cdict2)
-blue_red3 = LinearSegmentedColormap('BlueRed3', cdict3)
+plt.register_cmap(cmap=blue_red2)
+# Third, for LinearSegmentedColormap only,
+# leave everything to register_cmap:
+
+plt.register_cmap(name='BlueRed3', data=cdict3) # optional lut kwarg
+
x = np.arange(0, np.pi, 0.1)
y = np.arange(0, 2*np.pi, 0.1)
X, Y = np.meshgrid(x,y)
@@ -121,13 +135,33 @@
plt.colorbar()
plt.subplot(1,3,2)
-plt.imshow(Z, interpolation='nearest', cmap=blue_red2)
+cmap = plt.get_cmap('BlueRed2')
+plt.imshow(Z, interpolation='nearest', cmap=cmap)
plt.colorbar()
+# Now we will set the third cmap as the default. One would
+# not normally do this in the middle of a script like this;
+# it is done here just to illustrate the method.
+
+plt.rcParams['image.cmap'] = 'BlueRed3'
+
+# Also see below for an alternative, particularly for
+# interactive use.
+
plt.subplot(1,3,3)
-plt.imshow(Z, interpolation='nearest', cmap=blue_red3)
+plt.imshow(Z, interpolation='nearest')
plt.colorbar()
+# Or as yet another variation, we could replace the rcParams
+# specification *before* the imshow with the following *after*
+# imshow:
+#
+# plt.set_cmap('BlueRed3')
+#
+# This sets the new default *and* sets the colormap of the last
+# image-like item plotted via pyplot, if any.
+
+
plt.suptitle('Custom Blue-Red colormaps')
plt.show()
Modified: trunk/matplotlib/lib/matplotlib/cm.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/cm.py 2009-07-30 17:08:23 UTC (rev 7308)
+++ trunk/matplotlib/lib/matplotlib/cm.py 2009-07-30 19:32:15 UTC (rev 7309)
@@ -9,16 +9,79 @@
import matplotlib.cbook as cbook
from matplotlib._cm import *
+# Dictionary for user-registered colormaps:
+cmap_d = dict()
+# Using this second dictionary allows us to handle any
+# Colormap instance; the built-in datad is only for
+# LinearSegmentedColormaps. The advantage of keeping
+# datad is that it delays the generation of the Colormap
+# instance until it is actually needed. Generating the
+# instance is fast enough, and typically done few enough
+# times, that there is no need to cache the result.
+def register_cmap(name=None, cmap=None, data=None, lut=None):
+ """
+ Add a colormap to the set recognized by :func:`get_cmap`.
+
+ It can be used in two ways::
+
+ register_cmap(name='swirly', cmap=swirly_cmap)
+
+ register_cmap(name='choppy', data=choppydata, lut=128)
+
+ In the first case, *cmap* must be a :class:`colors.Colormap`
+ instance. The *name* is optional; if absent, the name will
+ be the :attr:`name` attribute of the *cmap*.
+
+ In the second case, the three arguments are passed to
+ the :class:`colors.LinearSegmentedColormap` initializer,
+ and the resulting colormap is registered.
+
+ """
+ if name is None:
+ try:
+ name = cmap.name
+ except AttributeError:
+ raise ValueError("Arguments must include a name or a Colormap")
+
+ if not cbook.is_string_like(name):
+ raise ValueError("Colormap name must be a string")
+
+ if isinstance(cmap, colors.Colormap):
+ cmap_d[name] = cmap
+ return
+
+ # For the remainder, let exceptions propagate.
+ if lut is None:
+ lut = mpl.rcParams['image.lut']
+ cmap = colors.LinearSegmentedColormap(name, data, lut)
+ cmap_d[name] = cmap
+
def get_cmap(name=None, lut=None):
"""
- Get a colormap instance, defaulting to rc values if *name* is None
+ Get a colormap instance, defaulting to rc values if *name* is None.
+
+ Colormaps added with :func:`register_cmap` take precedence over
+ builtin colormaps.
+
+ If *name* is a :class:`colors.Colormap` instance, it will be
+ returned.
"""
- if name is None: name = mpl.rcParams['image.cmap']
- if lut is None: lut = mpl.rcParams['image.lut']
+ if name is None:
+ name = mpl.rcParams['image.cmap']
- assert(name in datad.keys())
+ if isinstance(name, colors.Colormap):
+ return name
+
+ if name in cmap_d:
+ return cmap_d[name]
+
+ if name not in datad:
+ raise ValueError("%s is not a known colormap name" % name)
+
+ if lut is None:
+ lut = mpl.rcParams['image.lut']
return colors.LinearSegmentedColormap(name, datad[name], lut)
class ScalarMappable:
@@ -116,9 +179,9 @@
"""
set the colormap for luminance data
- ACCEPTS: a colormap
+ ACCEPTS: a colormap or registered colormap name
"""
- if cmap is None: cmap = get_cmap()
+ cmap = get_cmap(cmap)
self.cmap = cmap
self.changed()
Modified: trunk/matplotlib/lib/matplotlib/image.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/image.py 2009-07-30 17:08:23 UTC (rev 7308)
+++ trunk/matplotlib/lib/matplotlib/image.py 2009-07-30 19:32:15 UTC (rev 7309)
@@ -512,7 +512,7 @@
def set_cmap(self, cmap):
if self._A is not None:
raise RuntimeError('Cannot change colors after loading data')
- cm.ScalarMappable.set_cmap(self, norm)
+ cm.ScalarMappable.set_cmap(self, cmap)
class PcolorImage(martist.Artist, cm.ScalarMappable):
'''
Modified: trunk/matplotlib/lib/matplotlib/pyplot.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/pyplot.py 2009-07-30 17:08:23 UTC (rev 7308)
+++ trunk/matplotlib/lib/matplotlib/pyplot.py 2009-07-30 19:32:15 UTC (rev 7309)
@@ -17,7 +17,7 @@
from matplotlib.scale import get_scale_docs, get_scale_names
from matplotlib import cm
-from matplotlib.cm import get_cmap
+from matplotlib.cm import get_cmap, register_cmap
import numpy as np
@@ -1396,8 +1396,26 @@
im.set_clim(vmin, vmax)
draw_if_interactive()
+def set_cmap(cmap):
+ '''
+ set the default colormap to *cmap* and apply to current image if any.
+ See help(colormaps) for more information.
+ *cmap* must be a :class:`colors.Colormap` instance, or
+ the name of a registered colormap.
+ See :func:`register_cmap` and :func:`get_cmap`.
+ '''
+ cmap = cm.get_cmap(cmap)
+
+ rc('image', cmap=cmap.name)
+ im = gci()
+
+ if im is not None:
+ im.set_cmap(cmap)
+ draw_if_interactive()
+
+
def imread(*args, **kwargs):
return _imread(*args, **kwargs)
if _imread.__doc__ is not None:
@@ -6327,12 +6345,12 @@
*bbox_to_anchor* keyword argument. bbox_to_anchor can be an instance
of BboxBase(or its derivatives) or a tuple of 2 or 4 floats.
For example, ::
-
+
loc = 'upper right', bbox_to_anchor = (0.5, 0.5)
will place the legend so that the upper right corner of the legend at
the center of the axes.
-
+
The legend location can be specified in other coordinate, by using the
*bbox_transform* keyword.
@@ -6365,7 +6383,7 @@
*fancybox*: [ None | False | True ]
if True, draw a frame with a round fancybox. If None, use rc
-
+
*shadow*: [ None | False | True ]
If *True*, draw a shadow behind legend. If *None*, use rc settings.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <lee...@us...> - 2009-07-30 17:08:37
|
Revision: 7308
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7308&view=rev
Author: leejjoon
Date: 2009-07-30 17:08:23 +0000 (Thu, 30 Jul 2009)
Log Message:
-----------
legend doc. update
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/axes.py
trunk/matplotlib/lib/matplotlib/figure.py
trunk/matplotlib/lib/matplotlib/legend.py
trunk/matplotlib/lib/matplotlib/offsetbox.py
trunk/matplotlib/lib/matplotlib/pyplot.py
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2009-07-29 21:28:50 UTC (rev 7307)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2009-07-30 17:08:23 UTC (rev 7308)
@@ -3906,31 +3906,66 @@
'center' 10
=============== =============
- If none of these are locations are suitable, loc can be a 2-tuple
- giving x,y in axes coords, ie::
- loc = 0, 1 # left top
- loc = 0.5, 0.5 # center
+ Users can specify any arbitrary location for the legend using the
+ *bbox_to_anchor* keyword argument. bbox_to_anchor can be an instance
+ of BboxBase(or its derivatives) or a tuple of 2 or 4 floats.
+ For example,
+
+ loc = 'upper right', bbox_to_anchor = (0.5, 0.5)
+ will place the legend so that the upper right corner of the legend at
+ the center of the axes.
+
+ The legend location can be specified in other coordinate, by using the
+ *bbox_transform* keyword.
+
+ The loc itslef can be a 2-tuple giving x,y of the lower-left corner of
+ the legend in axes coords (*bbox_to_anchor* is ignored).
+
+
Keyword arguments:
- *isaxes*: [ True | False ]
- Indicates that this is an axes legend
+ *prop*: [ None | FontProperties | dict ]
+ A :class:`matplotlib.font_manager.FontProperties`
+ instance. If *prop* is a dictionary, a new instance will be
+ created with *prop*. If *None*, use rc settings.
*numpoints*: integer
- The number of points in the legend line, default is 4
+ The number of points in the legend for line
- *prop*: [ None | FontProperties ]
- A :class:`matplotlib.font_manager.FontProperties`
- instance, or *None* to use rc settings.
+ *scatterpoints*: integer
+ The number of points in the legend for scatter plot
+ *scatteroffsets*: list of floats
+ a list of yoffsets for scatter symbols in legend
+
*markerscale*: [ None | scalar ]
The relative size of legend markers vs. original. If *None*, use rc
settings.
+ *fancybox*: [ None | False | True ]
+ if True, draw a frame with a round fancybox. If None, use rc
+
*shadow*: [ None | False | True ]
If *True*, draw a shadow behind legend. If *None*, use rc settings.
+ *ncol* : integer
+ number of columns. default is 1
+
+ *mode* : [ "expand" | None ]
+ if mode is "expand", the legend will be horizontally expanded
+ to fill the axes area (or *bbox_to_anchor*)
+
+ *bbox_to_anchor* : an instance of BboxBase or a tuple of 2 or 4 floats
+ the bbox that the legend will be anchored.
+
+ *bbox_transform* : [ an instance of Transform | None ]
+ the transform for the bbox. transAxes if None.
+
+ *title* : string
+ the legend title
+
Padding and spacing between various elements use following keywords
parameters. The dimensions of these values are given as a fraction
of the fontsize. Values from rcParams will be used if None.
@@ -3946,9 +3981,13 @@
columnspacing the spacing between columns
================ ==================================================================
+
**Example:**
.. plot:: mpl_examples/api/legend_demo.py
+
+ Also see :ref:`plotting-guide-legend`.
+
"""
if len(args)==0:
Modified: trunk/matplotlib/lib/matplotlib/figure.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/figure.py 2009-07-29 21:28:50 UTC (rev 7307)
+++ trunk/matplotlib/lib/matplotlib/figure.py 2009-07-30 17:08:23 UTC (rev 7308)
@@ -829,29 +829,60 @@
(0,0) is the left, bottom of the figure and 1,1 is the right,
top.
- The legend instance is returned. The following kwargs are supported
+ Keyword arguments:
- *loc*
- the location of the legend
- *numpoints*
- the number of points in the legend line
- *prop*
- a :class:`matplotlib.font_manager.FontProperties` instance
- *pad*
- the fractional whitespace inside the legend border
- *markerscale*
- the relative size of legend markers vs. original
- *shadow*
- if True, draw a shadow behind legend
- *labelsep*
- the vertical space between the legend entries
- *handlelen*
- the length of the legend lines
- *handletextsep*
- the space between the legend line and legend text
- *axespad*
- the border between the axes and legend edge
+ *prop*: [ None | FontProperties | dict ]
+ A :class:`matplotlib.font_manager.FontProperties`
+ instance. If *prop* is a dictionary, a new instance will be
+ created with *prop*. If *None*, use rc settings.
+ *numpoints*: integer
+ The number of points in the legend line, default is 4
+
+ *scatterpoints*: integer
+ The number of points in the legend line, default is 4
+
+ *scatteroffsets*: list of floats
+ a list of yoffsets for scatter symbols in legend
+
+ *markerscale*: [ None | scalar ]
+ The relative size of legend markers vs. original. If *None*, use rc
+ settings.
+
+ *fancybox*: [ None | False | True ]
+ if True, draw a frame with a round fancybox. If None, use rc
+
+ *shadow*: [ None | False | True ]
+ If *True*, draw a shadow behind legend. If *None*, use rc settings.
+
+ *ncol* : integer
+ number of columns. default is 1
+
+ *mode* : [ "expand" | None ]
+ if mode is "expand", the legend will be horizontally expanded
+ to fill the axes area (or *bbox_to_anchor*)
+
+ *title* : string
+ the legend title
+
+ Padding and spacing between various elements use following keywords
+ parameters. The dimensions of these values are given as a fraction
+ of the fontsize. Values from rcParams will be used if None.
+
+ ================ ==================================================================
+ Keyword Description
+ ================ ==================================================================
+ borderpad the fractional whitespace inside the legend border
+ labelspacing the vertical space between the legend entries
+ handlelength the length of the legend handles
+ handletextpad the pad between the legend handle and text
+ borderaxespad the pad between the axes and legend border
+ columnspacing the spacing between columns
+ ================ ==================================================================
+
+
+ **Example:**
+
.. plot:: mpl_examples/pylab_examples/figlegend_demo.py
"""
handles = flatten(handles)
Modified: trunk/matplotlib/lib/matplotlib/legend.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/legend.py 2009-07-29 21:28:50 UTC (rev 7307)
+++ trunk/matplotlib/lib/matplotlib/legend.py 2009-07-30 17:08:23 UTC (rev 7308)
@@ -126,13 +126,15 @@
================ ==================================================================
Keyword Description
================ ==================================================================
- loc a location code or a tuple of coordinates
- numpoints the number of points in the legend line
+ loc a location code
prop the font property
markerscale the relative size of legend markers vs. original
+ numpoints the number of points in the legend for line
+ scatterpoints the number of points in the legend for scatter plot
+ scatteryoffsets a list of yoffsets for scatter symbols in legend
fancybox if True, draw a frame with a round fancybox. If None, use rc
shadow if True, draw a shadow behind legend
- scatteryoffsets a list of yoffsets for scatter symbols in legend
+ ncol number of columns
borderpad the fractional whitespace inside the legend border
labelspacing the vertical space between the legend entries
handlelength the length of the legend handles
@@ -147,9 +149,14 @@
The dimensions of pad and spacing are given as a fraction of the
_fontsize. Values from rcParams will be used if None.
-bbox_to_anchor can be an instance of BboxBase(or its derivatives) or a
-tuple of 2 or 4 floats. See :meth:`set_bbox_to_anchor` for more
-detail.
+Users can specify any arbitrary location for the legend using the
+*bbox_to_anchor* keyword argument. bbox_to_anchor can be an instance
+of BboxBase(or its derivatives) or a tuple of 2 or 4 floats.
+See :meth:`set_bbox_to_anchor` for more detail.
+
+The legend location can be specified by setting *loc* with a tuple of
+2 floats, which is interpreted as the lower-left corner of the legend
+in the normalized axes coordinate.
"""
from matplotlib.axes import Axes # local import only to avoid circularity
from matplotlib.figure import Figure # local import only to avoid circularity
@@ -158,8 +165,13 @@
if prop is None:
self.prop=FontProperties(size=rcParams["legend.fontsize"])
+ elif isinstance(prop, dict):
+ self.prop=FontProperties(**prop)
+ if "size" not in prop:
+ self.prop.set_size(rcParams["legend.fontsize"])
else:
self.prop=prop
+
self._fontsize = self.prop.get_size_in_points()
propnames=['numpoints', 'markerscale', 'shadow', "columnspacing",
Modified: trunk/matplotlib/lib/matplotlib/offsetbox.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/offsetbox.py 2009-07-29 21:28:50 UTC (rev 7307)
+++ trunk/matplotlib/lib/matplotlib/offsetbox.py 2009-07-30 17:08:23 UTC (rev 7308)
@@ -833,6 +833,10 @@
if prop is None:
self.prop=FontProperties(size=rcParams["legend.fontsize"])
+ elif isinstance(prop, dict):
+ self.prop=FontProperties(**prop)
+ if "size" not in prop:
+ self.prop.set_size(rcParams["legend.fontsize"])
else:
self.prop = prop
Modified: trunk/matplotlib/lib/matplotlib/pyplot.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/pyplot.py 2009-07-29 21:28:50 UTC (rev 7307)
+++ trunk/matplotlib/lib/matplotlib/pyplot.py 2009-07-30 17:08:23 UTC (rev 7308)
@@ -438,7 +438,7 @@
.. seealso::
:func:`~matplotlib.pyplot.legend`
- For information about the location codes
+
"""
l = gcf().legend(handles, labels, loc, **kwargs)
draw_if_interactive()
@@ -6322,31 +6322,69 @@
'center' 10
=============== =============
-If none of these are locations are suitable, loc can be a 2-tuple
-giving x,y in axes coords, ie::
- loc = 0, 1 # left top
- loc = 0.5, 0.5 # center
+Users can specify any arbitrary location for the legend using the
+*bbox_to_anchor* keyword argument. bbox_to_anchor can be an instance
+of BboxBase(or its derivatives) or a tuple of 2 or 4 floats.
+For example, ::
+
+ loc = 'upper right', bbox_to_anchor = (0.5, 0.5)
+will place the legend so that the upper right corner of the legend at
+the center of the axes.
+
+The legend location can be specified in other coordinate, by using the
+*bbox_transform* keyword.
+
+The loc itslef can be a 2-tuple giving x,y of the lower-left corner of
+the legend in axes coords (*bbox_to_anchor* is ignored).
+
+
Keyword arguments:
*isaxes*: [ True | False ]
Indicates that this is an axes legend
+ *prop*: [ None | FontProperties | dict ]
+ A :class:`matplotlib.font_manager.FontProperties`
+ instance. If *prop* is a dictionary, a new instance will be
+ created with *prop*. If *None*, use rc settings.
+
*numpoints*: integer
- The number of points in the legend line, default is 4
+ The number of points in the legend for line
- *prop*: [ None | FontProperties ]
- A :class:`matplotlib.font_manager.FontProperties`
- instance, or *None* to use rc settings.
+ *scatterpoints*: integer
+ The number of points in the legend for scatter plot
+ *scatteroffsets*: list of floats
+ a list of yoffsets for scatter symbols in legend
+
*markerscale*: [ None | scalar ]
The relative size of legend markers vs. original. If *None*, use rc
settings.
+ *fancybox*: [ None | False | True ]
+ if True, draw a frame with a round fancybox. If None, use rc
+
*shadow*: [ None | False | True ]
If *True*, draw a shadow behind legend. If *None*, use rc settings.
+ *ncol* : integer
+ number of columns. default is 1
+
+ *mode* : [ "expand" | None ]
+ if mode is "expand", the legend will be horizontally expanded
+ to fill the axes area (or *bbox_to_anchor*)
+
+ *bbox_to_anchor* : an instance of BboxBase or a tuple of 2 or 4 floats
+ the bbox that the legend will be anchored.
+
+ *bbox_transform* : [ an instance of Transform | None ]
+ the transform for the bbox. transAxes if None.
+
+ *title* : string
+ the legend title
+
Padding and spacing between various elements use following keywords
parameters. The dimensions of these values are given as a fraction
of the fontsize. Values from rcParams will be used if None.
@@ -6362,9 +6400,14 @@
columnspacing the spacing between columns
================ ==================================================================
+
**Example:**
-.. plot:: mpl_examples/api/legend_demo.py"""
+.. plot:: mpl_examples/api/legend_demo.py
+
+Also see :ref:`plotting-guide-legend`.
+
+"""
ret = gca().legend(*args, **kwargs)
draw_if_interactive()
return ret
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <evi...@us...> - 2009-07-29 21:29:05
|
Revision: 7307
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7307&view=rev
Author: evilguru
Date: 2009-07-29 21:28:50 +0000 (Wed, 29 Jul 2009)
Log Message:
-----------
Add first attempt at getting matplotlib to install mathtex.
Modified Paths:
--------------
branches/mathtex/setup.py
branches/mathtex/setupext.py
Modified: branches/mathtex/setup.py
===================================================================
--- branches/mathtex/setup.py 2009-07-29 17:14:05 UTC (rev 7306)
+++ branches/mathtex/setup.py 2009-07-29 21:28:50 UTC (rev 7307)
@@ -42,7 +42,8 @@
check_for_qt, check_for_qt4, check_for_cairo, \
check_provide_pytz, check_provide_dateutil,\
check_for_dvipng, check_for_ghostscript, check_for_latex, \
- check_for_pdftops, check_for_datetime, options, build_png
+ check_for_pdftops, check_for_datetime, options, build_png, \
+ check_provide_mathtex, build_mathtex
#import distutils.sysconfig
# jdh
@@ -128,6 +129,9 @@
if has_libpng and options['build_agg'] or options['build_image']:
build_png(ext_modules, packages)
+if has_libpng and options['provide_mathtex'] and check_provide_mathtex():
+ build_mathtex(ext_modules, packages, package_data)
+
if options['build_windowing'] and sys.platform=='win32':
build_windowing(ext_modules, packages)
Modified: branches/mathtex/setupext.py
===================================================================
--- branches/mathtex/setupext.py 2009-07-29 17:14:05 UTC (rev 7306)
+++ branches/mathtex/setupext.py 2009-07-29 21:28:50 UTC (rev 7307)
@@ -98,6 +98,7 @@
'verbose': False,
'provide_pytz': 'auto',
'provide_dateutil': 'auto',
+ 'provide_mathtex' : 'auto',
'build_agg': True,
'build_gtk': 'auto',
'build_gtkagg': 'auto',
@@ -126,6 +127,10 @@
"dateutil")
except: options['provide_dateutil'] = 'auto'
+ try: options['provide_mathtex'] = config.getboolean("provide_packages",
+ "mathtex")
+ except: options['provide_mathtex'] = 'auto'
+
try: options['build_gtk'] = config.getboolean("gui_support", "gtk")
except: options['build_gtk'] = 'auto'
@@ -386,6 +391,14 @@
print_status("datetime", "present, version unknown")
return True
+def check_provide_mathtex():
+ try:
+ import mathtex
+ except ImportError:
+ print_status("mathtex", "matplotlib will provide")
+ return True
+ return False
+
def check_provide_pytz(hasdatetime=True):
if hasdatetime and (options['provide_pytz'] is True):
print_status("pytz", "matplotlib will provide")
@@ -545,7 +558,7 @@
else:
add_base_flags(module)
module.libraries.append('z')
-
+
# put this last for library link order
module.libraries.extend(std_libs)
@@ -1092,6 +1105,11 @@
ext_modules.append(module)
BUILT_FT2FONT = True
+def build_mathtex(ext_modules, packages, package_data):
+ packages.append('mathtex/mathtex')
+ packages.append('mathtex/mathtex.backends')
+ package_data['mathtex'] = ['lib/mathtex/data/fonts/*.ttf']
+
def build_ttconv(ext_modules, packages):
global BUILT_TTCONV
if BUILT_TTCONV: return # only build it if you you haven't already
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <evi...@us...> - 2009-07-29 17:14:20
|
Revision: 7306
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7306&view=rev
Author: evilguru
Date: 2009-07-29 17:14:05 +0000 (Wed, 29 Jul 2009)
Log Message:
-----------
Update the mathtex branch so that it is up-to-date with trunk.
Modified Paths:
--------------
branches/mathtex/CHANGELOG
branches/mathtex/boilerplate.py
branches/mathtex/examples/pylab_examples/axes_zoom_effect.py
branches/mathtex/examples/pylab_examples/findobj_demo.py
branches/mathtex/examples/pylab_examples/griddata_demo.py
branches/mathtex/examples/pylab_examples/hatch_demo.py
branches/mathtex/lib/matplotlib/axes.py
branches/mathtex/lib/matplotlib/backends/backend_pdf.py
branches/mathtex/lib/matplotlib/backends/backend_svg.py
branches/mathtex/lib/matplotlib/collections.py
branches/mathtex/lib/matplotlib/delaunay/VoronoiDiagramGenerator.cpp
branches/mathtex/lib/matplotlib/delaunay/__init__.py
branches/mathtex/lib/matplotlib/delaunay/_delaunay.cpp
branches/mathtex/lib/matplotlib/delaunay/triangulate.py
branches/mathtex/lib/matplotlib/mlab.py
branches/mathtex/lib/matplotlib/pyplot.py
branches/mathtex/lib/matplotlib/quiver.py
branches/mathtex/lib/mpl_toolkits/axes_grid/axislines.py
branches/mathtex/lib/mpl_toolkits/mplot3d/art3d.py
branches/mathtex/lib/mpl_toolkits/mplot3d/axes3d.py
branches/mathtex/src/_backend_agg.cpp
Added Paths:
-----------
branches/mathtex/examples/api/radar_chart.py
branches/mathtex/examples/mplot3d/hist3d_demo.py
branches/mathtex/examples/pylab_examples/legend_translucent.py
Removed Paths:
-------------
branches/mathtex/src/agg.cxx
branches/mathtex/src/swig_runtime.h
Property Changed:
----------------
branches/mathtex/
branches/mathtex/doc/pyplots/README
branches/mathtex/doc/sphinxext/gen_gallery.py
branches/mathtex/doc/sphinxext/gen_rst.py
branches/mathtex/examples/misc/multiprocess.py
branches/mathtex/examples/mplot3d/contour3d_demo.py
branches/mathtex/examples/mplot3d/contourf3d_demo.py
branches/mathtex/examples/mplot3d/polys3d_demo.py
branches/mathtex/examples/mplot3d/scatter3d_demo.py
branches/mathtex/examples/mplot3d/surface3d_demo.py
branches/mathtex/examples/mplot3d/wire3d_demo.py
branches/mathtex/lib/matplotlib/sphinxext/mathmpl.py
branches/mathtex/lib/matplotlib/sphinxext/only_directives.py
branches/mathtex/lib/matplotlib/sphinxext/plot_directive.py
Property changes on: branches/mathtex
___________________________________________________________________
Modified: svnmerge-integrated
- /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-7253 /trunk/matplotlib:1-7262
+ /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-7253 /trunk/matplotlib:1-7305
Modified: svn:mergeinfo
- /branches/v0_91_maint:5753-5771
/branches/v0_98_5_maint:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080,7176,7209-7211,7227,7245
+ /branches/v0_91_maint:5753-5771
/branches/v0_98_5_maint:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080,7176,7209-7211,7227,7245
/trunk/matplotlib:7265-7303
Modified: branches/mathtex/CHANGELOG
===================================================================
--- branches/mathtex/CHANGELOG 2009-07-29 16:58:13 UTC (rev 7305)
+++ branches/mathtex/CHANGELOG 2009-07-29 17:14:05 UTC (rev 7306)
@@ -1,3 +1,26 @@
+2009-07-28 Quiver speed improved, thanks to tip by Ray Speth. -EF
+
+2009-07-27 Simplify argument handling code for plot method. -EF
+
+2009-07-25 Allow "plot(1, 2, 'r*')" to work. - EF
+
+2009-07-22 Added an 'interp' keyword to griddata so the faster linear
+ interpolation method can be chosen. Default is 'nn', so
+ default behavior (using natural neighbor method) is unchanged (JSW)
+
+2009-07-22 Improved boilerplate.py so that it generates the correct
+ signatures for pyplot functions. - JKS
+
+2009-07-19 Fixed the docstring of Axes.step to reflect the correct
+ meaning of the kwargs "pre" and "post" - See SF bug
+ https://sourceforge.net/tracker/index.php?func=detail&aid=2823304&group_id=80706&atid=560720
+ - JDH
+
+2009-07-18 Fix support for hatches without color fills to pdf and svg
+ backends. Add an example of that to hatch_demo.py. - JKS
+
+2009-07-17 Removed fossils from swig version of agg backend. - EF
+
2009-07-14 initial submission of the annotation guide. -JJL
2009-07-14 axes_grid : minor improvements in anchored_artists and
@@ -3,5 +26,5 @@
inset_locator. -JJL
-2009-07-14 Fix a few bugs in ConnectionStyle algorithms. Add
+2009-07-14 Fix a few bugs in ConnectionStyle algorithms. Add
ConnectionPatch class. -JJL
Modified: branches/mathtex/boilerplate.py
===================================================================
--- branches/mathtex/boilerplate.py 2009-07-29 16:58:13 UTC (rev 7305)
+++ branches/mathtex/boilerplate.py 2009-07-29 17:14:05 UTC (rev 7306)
@@ -1,47 +1,50 @@
-# wrap the plot commands defined in axes. The code generated by this
+# Wrap the plot commands defined in axes. The code generated by this
# file is pasted into pylab.py. We did try to do this the smart way,
# with callable functions and new.function, but could never get the
# docstrings right for python2.2. See
# http://groups.google.com/group/comp.lang.python/browse_frm/thread/dcd63ec13096a0f6/1b14640f3a4ad3dc?#1b14640f3a4ad3dc
+# For some later history, see
+# http://thread.gmane.org/gmane.comp.python.matplotlib.devel/7068
+import inspect
+import random
+import re
+import sys
+import types
-# note we check for __doc__ is not None since py2exe optimize removes
-# the docstrings
+# import the local copy of matplotlib, not the installed one
+sys.path.insert(0, './lib')
+from matplotlib.axes import Axes
+from matplotlib.cbook import dedent
_fmtplot = """\
# This function was autogenerated by boilerplate.py. Do not edit as
# changes will be lost
-def %(func)s(*args, **kwargs):
+def %(func)s(%(argspec)s):
+ %(docstring)s
+ %(ax)s = gca()
# allow callers to override the hold state by passing hold=True|False
- b = ishold()
- h = kwargs.pop('hold', None)
- if h is not None:
- hold(h)
+ %(washold)s = %(ax)s.ishold()
+ %(sethold)s
+ if hold is not None:
+ %(ax)s.hold(hold)
try:
- ret = gca().%(func)s(*args, **kwargs)
+ %(ret)s = %(ax)s.%(func)s(%(call)s)
draw_if_interactive()
- except:
- hold(b)
- raise
+ finally:
+ %(ax)s.hold(%(washold)s)
%(mappable)s
- hold(b)
- return ret
-if Axes.%(func)s.__doc__ is not None:
- %(func)s.__doc__ = dedent(Axes.%(func)s.__doc__) + \"\"\"
-
-Additional kwargs: hold = [True|False] overrides default hold state\"\"\"
+ return %(ret)s
"""
_fmtmisc = """\
# This function was autogenerated by boilerplate.py. Do not edit as
# changes will be lost
-def %(func)s(*args, **kwargs):
-
- ret = gca().%(func)s(*args, **kwargs)
+def %(func)s(%(argspec)s):
+ %(docstring)s
+ %(ret)s = gca().%(func)s(%(call)s)
draw_if_interactive()
- return ret
-if Axes.%(func)s.__doc__ is not None:
- %(func)s.__doc__ = dedent(Axes.%(func)s.__doc__)
+ return %(ret)s
"""
# these methods are all simple wrappers of Axes methods by the same
@@ -101,33 +104,113 @@
)
cmappable = {
- 'contour' : 'if ret._A is not None: gci._current = ret',
- 'contourf': 'if ret._A is not None: gci._current = ret',
- 'hexbin' : 'gci._current = ret[0]',
- 'scatter' : 'gci._current = ret',
- 'pcolor' : 'gci._current = ret',
- 'pcolormesh' : 'gci._current = ret',
- 'imshow' : 'gci._current = ret',
- 'spy' : 'gci._current = ret',
- 'quiver' : 'gci._current = ret',
- 'specgram' : 'gci._current = ret[-1]',
+ 'contour' : 'if %(ret)s._A is not None: gci._current = %(ret)s',
+ 'contourf': 'if %(ret)s._A is not None: gci._current = %(ret)s',
+ 'hexbin' : 'gci._current = %(ret)s',
+ 'scatter' : 'gci._current = %(ret)s',
+ 'pcolor' : 'gci._current = %(ret)s',
+ 'pcolormesh' : 'gci._current = %(ret)s',
+ 'imshow' : 'gci._current = %(ret)s',
+ 'spy' : 'gci._current = %(ret)s',
+ 'quiver' : 'gci._current = %(ret)s',
+ 'specgram' : 'gci._current = %(ret)s[-1]',
}
+def format_value(value):
+ """
+ Format function default values as needed for inspect.formatargspec.
+ The interesting part is a hard-coded list of functions used
+ as defaults in pyplot methods.
+ """
+ if isinstance(value, types.FunctionType):
+ if value.func_name in ('detrend_none', 'window_hanning'):
+ return '=mlab.' + value.func_name
+ if value.func_name == 'mean':
+ return '=np.' + value.func_name
+ raise ValueError, ('default value %s unknown to boilerplate.formatvalue'
+ % value)
+ return '='+repr(value)
-for func in _plotcommands:
- if func in cmappable:
- mappable = cmappable[func]
- else:
- mappable = ''
- print _fmtplot%locals()
+def remove_final_whitespace(string):
+ """
+ Return a copy of *string* with final whitespace removed from each line.
+ """
+ return '\n'.join(x.rstrip() for x in string.split('\n'))
+def make_docstring(cmd, mention_hold):
+ func = getattr(Axes, cmd)
+ docstring = inspect.getdoc(func)
+ if docstring is None:
+ return ""
+ escaped = re.sub(r'\\', r'\\\\', docstring)
+ if mention_hold:
+ escaped += '''
-for func in _misccommands:
- print _fmtmisc%locals()
+Additional kwargs: hold = [True|False] overrides default hold state
+'''
+ return '"""'+escaped+'"""'
+for fmt,cmdlist in (_fmtplot,_plotcommands),(_fmtmisc,_misccommands):
+ for func in cmdlist:
+ # For some commands, an additional line is needed to set the
+ # color map
+ if func in cmappable:
+ mappable = cmappable[func] % locals()
+ else:
+ mappable = ''
+ # Format docstring
+ docstring = make_docstring(func, fmt is _fmtplot)
+ # Get argspec of wrapped function
+ args, varargs, varkw, defaults = inspect.getargspec(getattr(Axes, func))
+ args.pop(0) # remove 'self' argument
+ if defaults is None:
+ defaults = ()
+
+ # How to call the wrapped function
+ call = map(str, args)
+ if varargs is not None:
+ call.append('*'+varargs)
+ if varkw is not None:
+ call.append('**'+varkw)
+ call = ', '.join(call)
+
+ # Add a hold keyword argument if needed (fmt is _fmtplot) and
+ # possible (if *args is used, we can't just add a hold
+ # argument in front of it since it would gobble one of the
+ # arguments the user means to pass via *args)
+ if varargs:
+ sethold = "hold = %(varkw)s.pop('hold', None)" % locals()
+ elif fmt is _fmtplot:
+ args.append('hold')
+ defaults = defaults + (None,)
+ sethold = ''
+
+ # Now we can build the argspec for defining the wrapper
+ argspec = inspect.formatargspec(args, varargs, varkw, defaults,
+ formatvalue=format_value)
+ argspec = argspec[1:-1] # remove parens
+
+ # A gensym-like facility in case some function takes an
+ # argument named washold, ax, or ret
+ washold,ret,ax = 'washold', 'ret', 'ax'
+ bad = set(args) | set((varargs, varkw))
+ while washold in bad or ret in bad or ax in bad:
+ washold = 'washold' + str(random.randrange(10**12))
+ ret = 'ret' + str(random.randrange(10**12))
+ ax = 'ax' + str(random.randrange(10**12))
+
+ # Since we can't avoid using some function names,
+ # bail out if they are used as argument names
+ for reserved in ('gca', 'gci', 'draw_if_interactive'):
+ if reserved in bad:
+ raise ValueError, \
+ 'Axes method %s has kwarg named %s' % (func, reserved)
+
+ print remove_final_whitespace(fmt%locals())
+
# define the colormap functions
_fmtcmap = """\
# This function was autogenerated by boilerplate.py. Do not edit as
Property changes on: branches/mathtex/doc/pyplots/README
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_98_5_maint/doc/pyplots/README:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080,7176,7209-7211,7227,7245
+ /branches/v0_98_5_maint/doc/pyplots/README:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080,7176,7209-7211,7227,7245
/trunk/matplotlib/doc/pyplots/README:7265-7303
Property changes on: branches/mathtex/doc/sphinxext/gen_gallery.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/doc/_templates/gen_gallery.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_gallery.py:6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080,7176,7209-7211,7227,7245
+ /branches/v0_91_maint/doc/_templates/gen_gallery.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_gallery.py:6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080,7176,7209-7211,7227,7245
/trunk/matplotlib/doc/sphinxext/gen_gallery.py:7265-7303
Property changes on: branches/mathtex/doc/sphinxext/gen_rst.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/doc/examples/gen_rst.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_rst.py:6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080,7176,7209-7211,7227,7245
+ /branches/v0_91_maint/doc/examples/gen_rst.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_rst.py:6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080,7176,7209-7211,7227,7245
/trunk/matplotlib/doc/sphinxext/gen_rst.py:7265-7303
Copied: branches/mathtex/examples/api/radar_chart.py (from rev 7303, trunk/matplotlib/examples/api/radar_chart.py)
===================================================================
--- branches/mathtex/examples/api/radar_chart.py (rev 0)
+++ branches/mathtex/examples/api/radar_chart.py 2009-07-29 17:14:05 UTC (rev 7306)
@@ -0,0 +1,144 @@
+import numpy as np
+
+import matplotlib.pyplot as plt
+from matplotlib.projections.polar import PolarAxes
+from matplotlib.projections import register_projection
+
+def radar_factory(num_vars, frame='circle'):
+ """Create a radar chart with `num_vars` axes."""
+ # calculate evenly-spaced axis angles
+ theta = 2*np.pi * np.linspace(0, 1-1./num_vars, num_vars)
+ # rotate theta such that the first axis is at the top
+ theta += np.pi/2
+
+ def draw_poly_frame(self, x0, y0, r):
+ # TODO: use transforms to convert (x, y) to (r, theta)
+ verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta]
+ return plt.Polygon(verts, closed=True, edgecolor='k')
+
+ def draw_circle_frame(self, x0, y0, r):
+ return plt.Circle((x0, y0), r)
+
+ frame_dict = {'polygon': draw_poly_frame, 'circle': draw_circle_frame}
+ if frame not in frame_dict:
+ raise ValueError, 'unknown value for `frame`: %s' % frame
+
+ class RadarAxes(PolarAxes):
+ """Class for creating a radar chart (a.k.a. a spider or star chart)
+
+ http://en.wikipedia.org/wiki/Radar_chart
+ """
+ name = 'radar'
+ # use 1 line segment to connect specified points
+ RESOLUTION = 1
+ # define draw_frame method
+ draw_frame = frame_dict[frame]
+
+ def fill(self, *args, **kwargs):
+ """Override fill so that line is closed by default"""
+ closed = kwargs.pop('closed', True)
+ return super(RadarAxes, self).fill(closed=closed, *args, **kwargs)
+
+ def plot(self, *args, **kwargs):
+ """Override plot so that line is closed by default"""
+ lines = super(RadarAxes, self).plot(*args, **kwargs)
+ for line in lines:
+ self._close_line(line)
+
+ def _close_line(self, line):
+ x, y = line.get_data()
+ # FIXME: markers at x[0], y[0] get doubled-up
+ if x[0] != x[-1]:
+ x = np.concatenate((x, [x[0]]))
+ y = np.concatenate((y, [y[0]]))
+ line.set_data(x, y)
+
+ def set_varlabels(self, labels):
+ self.set_thetagrids(theta * 180/np.pi, labels)
+
+ def _gen_axes_patch(self):
+ x0, y0 = (0.5, 0.5)
+ r = 0.5
+ return self.draw_frame(x0, y0, r)
+
+ register_projection(RadarAxes)
+ return theta
+
+
+if __name__ == '__main__':
+ #The following data is from the Denver Aerosol Sources and Health study.
+ #See doi:10.1016/j.atmosenv.2008.12.017
+ #
+ #The data are pollution source profile estimates for five modeled pollution
+ #sources (e.g., cars, wood-burning, etc) that emit 7-9 chemical species.
+ #The radar charts are experimented with here to see if we can nicely
+ #visualize how the modeled source profiles change across four scenarios:
+ # 1) No gas-phase species present, just seven particulate counts on
+ # Sulfate
+ # Nitrate
+ # Elemental Carbon (EC)
+ # Organic Carbon fraction 1 (OC)
+ # Organic Carbon fraction 2 (OC2)
+ # Organic Carbon fraction 3 (OC3)
+ # Pyrolized Organic Carbon (OP)
+ # 2)Inclusion of gas-phase specie carbon monoxide (CO)
+ # 3)Inclusion of gas-phase specie ozone (O3).
+ # 4)Inclusion of both gas-phase speciesis present...
+ N = 9
+ theta = radar_factory(N)
+ spoke_labels = ['Sulfate', 'Nitrate', 'EC', 'OC1', 'OC2', 'OC3', 'OP', 'CO',
+ 'O3']
+ f1_base = [0.88, 0.01, 0.03, 0.03, 0.00, 0.06, 0.01, 0.00, 0.00]
+ f1_CO = [0.88, 0.02, 0.02, 0.02, 0.00, 0.05, 0.00, 0.05, 0.00]
+ f1_O3 = [0.89, 0.01, 0.07, 0.00, 0.00, 0.05, 0.00, 0.00, 0.03]
+ f1_both = [0.87, 0.01, 0.08, 0.00, 0.00, 0.04, 0.00, 0.00, 0.01]
+
+ f2_base = [0.07, 0.95, 0.04, 0.05, 0.00, 0.02, 0.01, 0.00, 0.00]
+ f2_CO = [0.08, 0.94, 0.04, 0.02, 0.00, 0.01, 0.12, 0.04, 0.00]
+ f2_O3 = [0.07, 0.95, 0.05, 0.04, 0.00, 0.02, 0.12, 0.00, 0.00]
+ f2_both = [0.09, 0.95, 0.02, 0.03, 0.00, 0.01, 0.13, 0.06, 0.00]
+
+ f3_base = [0.01, 0.02, 0.85, 0.19, 0.05, 0.10, 0.00, 0.00, 0.00]
+ f3_CO = [0.01, 0.01, 0.79, 0.10, 0.00, 0.05, 0.00, 0.31, 0.00]
+ f3_O3 = [0.01, 0.02, 0.86, 0.27, 0.16, 0.19, 0.00, 0.00, 0.00]
+ f3_both = [0.01, 0.02, 0.71, 0.24, 0.13, 0.16, 0.00, 0.50, 0.00]
+
+ f4_base = [0.02, 0.01, 0.07, 0.01, 0.21, 0.12, 0.98, 0.00, 0.00]
+ f4_CO = [0.00, 0.02, 0.03, 0.38, 0.31, 0.31, 0.00, 0.59, 0.00]
+ f4_O3 = [0.01, 0.03, 0.00, 0.32, 0.29, 0.27, 0.00, 0.00, 0.95]
+ f4_both = [0.01, 0.03, 0.00, 0.28, 0.24, 0.23, 0.00, 0.44, 0.88]
+
+ f5_base = [0.01, 0.01, 0.02, 0.71, 0.74, 0.70, 0.00, 0.00, 0.00]
+ f5_CO = [0.02, 0.02, 0.11, 0.47, 0.69, 0.58, 0.88, 0.00, 0.00]
+ f5_O3 = [0.02, 0.00, 0.03, 0.37, 0.56, 0.47, 0.87, 0.00, 0.00]
+ f5_both = [0.02, 0.00, 0.18, 0.45, 0.64, 0.55, 0.86, 0.00, 0.16]
+
+ fig = plt.figure(figsize=(9,9))
+ # adjust spacing around the subplots
+ fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)
+ title_list = ['Basecase', 'With CO', 'With O3', 'CO & O3']
+ data = {'Basecase': [f1_base, f2_base, f3_base, f4_base, f5_base],
+ 'With CO': [f1_CO, f2_CO, f3_CO, f4_CO, f5_CO],
+ 'With O3': [f1_O3, f2_O3, f3_O3, f4_O3, f5_O3],
+ 'CO & O3': [f1_both, f2_both, f3_both, f4_both, f5_both]}
+ colors = ['b', 'r', 'g', 'm', 'y']
+ # chemicals range from 0 to 1
+ radial_grid = [0.2, 0.4, 0.6, 0.8]
+ # If you don't care about the order, you can loop over data_dict.items()
+ for n, title in enumerate(title_list):
+ ax = fig.add_subplot(2, 2, n+1, projection='radar')
+ plt.rgrids(radial_grid)
+ ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1),
+ horizontalalignment='center', verticalalignment='center')
+ for d, color in zip(data[title], colors):
+ ax.plot(theta, d, color=color)
+ ax.fill(theta, d, facecolor=color, alpha=0.25)
+ ax.set_varlabels(spoke_labels)
+ # add legend relative to top-left plot
+ plt.subplot(2,2,1)
+ labels = ('Factor 1', 'Factor 2', 'Factor 3', 'Factor 4', 'Factor 5')
+ legend = plt.legend(labels, loc=(0.9, .95), labelspacing=0.1)
+ plt.setp(legend.get_texts(), fontsize='small')
+ plt.figtext(0.5, 0.965, '5-Factor Solution Profiles Across Four Scenarios',
+ ha='center', color='black', weight='bold', size='large')
+ plt.show()
Property changes on: branches/mathtex/examples/misc/multiprocess.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/examples/misc/log.py:5753-5771
/branches/v0_98_5_maint/examples/misc/log.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080
+ /branches/v0_91_maint/examples/misc/log.py:5753-5771
/branches/v0_98_5_maint/examples/misc/log.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080
/trunk/matplotlib/examples/misc/multiprocess.py:7265-7303
Property changes on: branches/mathtex/examples/mplot3d/contour3d_demo.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/examples/mplot3d/contour.py:5753-5771
/branches/v0_98_5_maint/examples/mplot3d/contour.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080
+ /branches/v0_91_maint/examples/mplot3d/contour.py:5753-5771
/branches/v0_98_5_maint/examples/mplot3d/contour.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080
/trunk/matplotlib/examples/mplot3d/contour3d_demo.py:7265-7303
Property changes on: branches/mathtex/examples/mplot3d/contourf3d_demo.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/examples/mplot3d/contourf.py:5753-5771
/branches/v0_98_5_maint/examples/mplot3d/contourf.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080
+ /branches/v0_91_maint/examples/mplot3d/contourf.py:5753-5771
/branches/v0_98_5_maint/examples/mplot3d/contourf.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080
/trunk/matplotlib/examples/mplot3d/contourf3d_demo.py:7265-7303
Copied: branches/mathtex/examples/mplot3d/hist3d_demo.py (from rev 7303, trunk/matplotlib/examples/mplot3d/hist3d_demo.py)
===================================================================
--- branches/mathtex/examples/mplot3d/hist3d_demo.py (rev 0)
+++ branches/mathtex/examples/mplot3d/hist3d_demo.py 2009-07-29 17:14:05 UTC (rev 7306)
@@ -0,0 +1,27 @@
+from mpl_toolkits.mplot3d import Axes3D
+from matplotlib.collections import PolyCollection
+from matplotlib.colors import colorConverter
+import pylab
+import random
+import numpy as np
+
+fig = pylab.figure()
+ax = Axes3D(fig)
+x = np.random.rand(100) * 4
+y = np.random.rand(100) * 4
+hist, xedges, yedges = np.histogram2d(x, y, bins=4)
+
+elements = (len(xedges) - 1) * (len(yedges) - 1)
+xpos, ypos = np.meshgrid(
+ [xedges[i] + 0.25 for i in range(len(xedges) - 1)],
+ [yedges[i] + 0.25 for i in range(len(yedges) - 1)])
+xpos = xpos.flatten()
+ypos = ypos.flatten()
+zpos = [0] * elements
+dx = [0.5] * elements
+dy = [0.5] * elements
+dz = hist.flatten()
+ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b')
+
+pylab.show()
+
Property changes on: branches/mathtex/examples/mplot3d/polys3d_demo.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/examples/mplot3d/polys.py:5753-5771
/branches/v0_98_5_maint/examples/mplot3d/polys.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080
+ /branches/v0_91_maint/examples/mplot3d/polys.py:5753-5771
/branches/v0_98_5_maint/examples/mplot3d/polys.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080
/trunk/matplotlib/examples/mplot3d/polys3d_demo.py:7265-7303
Property changes on: branches/mathtex/examples/mplot3d/scatter3d_demo.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/examples/mplot3d/scatter.py:5753-5771
/branches/v0_98_5_maint/examples/mplot3d/scatter.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080
+ /branches/v0_91_maint/examples/mplot3d/scatter.py:5753-5771
/branches/v0_98_5_maint/examples/mplot3d/scatter.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080
/trunk/matplotlib/examples/mplot3d/scatter3d_demo.py:7265-7303
Property changes on: branches/mathtex/examples/mplot3d/surface3d_demo.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/examples/mplot3d/surface.py:5753-5771
/branches/v0_98_5_maint/examples/mplot3d/surface.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080
+ /branches/v0_91_maint/examples/mplot3d/surface.py:5753-5771
/branches/v0_98_5_maint/examples/mplot3d/surface.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080
/trunk/matplotlib/examples/mplot3d/surface3d_demo.py:7265-7303
Property changes on: branches/mathtex/examples/mplot3d/wire3d_demo.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/examples/mplot3d/wire.py:5753-5771
/branches/v0_98_5_maint/examples/mplot3d/wire.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080
+ /branches/v0_91_maint/examples/mplot3d/wire.py:5753-5771
/branches/v0_98_5_maint/examples/mplot3d/wire.py:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934,6941,6946,6948,6950,6952,6960,6972,6984-6985,6990,6995,6997-7001,7014,7016,7018,7024-7025,7033,7035,7042,7072,7080
/trunk/matplotlib/examples/mplot3d/wire3d_demo.py:7265-7303
Modified: branches/mathtex/examples/pylab_examples/axes_zoom_effect.py
===================================================================
--- branches/mathtex/examples/pylab_examples/axes_zoom_effect.py 2009-07-29 16:58:13 UTC (rev 7305)
+++ branches/mathtex/examples/pylab_examples/axes_zoom_effect.py 2009-07-29 17:14:05 UTC (rev 7306)
@@ -51,7 +51,7 @@
prop_patches=kwargs.copy()
prop_patches["ec"]="none"
- prop_patches["alpha"]="0.2"
+ prop_patches["alpha"]=0.2
c1, c2, bbox_patch1, bbox_patch2, p = \
connect_bbox(mybbox1, mybbox2,
@@ -84,7 +84,7 @@
prop_patches=kwargs.copy()
prop_patches["ec"]="none"
- prop_patches["alpha"]="0.2"
+ prop_patches["alpha"]=0.2
c1, c2, bbox_patch1, bbox_patch2, p = \
connect_bbox(mybbox1, mybbox2,
Modified: branches/mathtex/examples/pylab_examples/findobj_demo.py
===================================================================
--- branches/mathtex/examples/pylab_examples/findobj_demo.py 2009-07-29 16:58:13 UTC (rev 7305)
+++ branches/mathtex/examples/pylab_examples/findobj_demo.py 2009-07-29 17:14:05 UTC (rev 7306)
@@ -23,7 +23,7 @@
# match on arbitrary function
def myfunc(x):
- return hasattr(x, 'set_color')
+ return hasattr(x, 'set_color') and not hasattr(x, 'set_facecolor')
for o in fig.findobj(myfunc):
o.set_color('blue')
Modified: branches/mathtex/examples/pylab_examples/griddata_demo.py
===================================================================
--- branches/mathtex/examples/pylab_examples/griddata_demo.py 2009-07-29 16:58:13 UTC (rev 7305)
+++ branches/mathtex/examples/pylab_examples/griddata_demo.py 2009-07-29 17:14:05 UTC (rev 7306)
@@ -4,7 +4,7 @@
import numpy as np
# make up data.
#npts = int(raw_input('enter # of random points to plot:'))
-seed(-1)
+seed(0)
npts = 200
x = uniform(-2,2,npts)
y = uniform(-2,2,npts)
Modified: branches/mathtex/examples/pylab_examples/hatch_demo.py
===================================================================
--- branches/mathtex/examples/pylab_examples/hatch_demo.py 2009-07-29 16:58:13 UTC (rev 7305)
+++ branches/mathtex/examples/pylab_examples/hatch_demo.py 2009-07-29 17:14:05 UTC (rev 7306)
@@ -3,18 +3,29 @@
PDF, SVG and Agg backends only.
"""
import matplotlib.pyplot as plt
+from matplotlib.patches import Ellipse, Polygon
fig = plt.figure()
-ax1 = fig.add_subplot(121)
+ax1 = fig.add_subplot(131)
ax1.bar(range(1,5), range(1,5), color='red', edgecolor='black', hatch="/")
ax1.bar(range(1,5), [6] * 4, bottom=range(1,5), color='blue', edgecolor='black', hatch='//')
+ax1.set_xticks([1.5,2.5,3.5,4.5])
-ax2 = fig.add_subplot(122)
+ax2 = fig.add_subplot(132)
bars = ax2.bar(range(1,5), range(1,5), color='yellow', ecolor='black') + \
ax2.bar(range(1, 5), [6] * 4, bottom=range(1,5), color='green', ecolor='black')
+ax2.set_xticks([1.5,2.5,3.5,4.5])
patterns = ('-', '+', 'x', '\\', '*', 'o', 'O', '.')
for bar, pattern in zip(bars, patterns):
bar.set_hatch(pattern)
+ax3 = fig.add_subplot(133)
+ax3.fill([1,3,3,1],[1,1,2,2], fill=False, hatch='\\')
+ax3.add_patch(Ellipse((4,1.5), 4, 0.5, fill=False, hatch='*'))
+ax3.add_patch(Polygon([[0,0],[4,1.1],[6,2.5],[2,1.4]], closed=True,
+ fill=False, hatch='/'))
+ax3.set_xlim((0,6))
+ax3.set_ylim((0,2.5))
+
plt.show()
Copied: branches/mathtex/examples/pylab_examples/legend_translucent.py (from rev 7303, trunk/matplotlib/examples/pylab_examples/legend_translucent.py)
===================================================================
--- branches/mathtex/examples/pylab_examples/legend_translucent.py (rev 0)
+++ branches/mathtex/examples/pylab_examples/legend_translucent.py 2009-07-29 17:14:05 UTC (rev 7306)
@@ -0,0 +1,18 @@
+#!/usr/bin/python
+#
+# Show how to add a translucent legend
+
+# import pyplot module
+import matplotlib.pyplot as plt
+
+# draw 2 crossing lines
+plt.plot([0,1], label='going up')
+plt.plot([1,0], label='going down')
+
+# add the legend in the middle of the plot
+leg = plt.legend(fancybox=True, loc='center')
+# set the alpha value of the legend: it will be translucent
+leg.get_frame().set_alpha(0.5)
+
+# show the plot
+plt.show()
Modified: branches/mathtex/lib/matplotlib/axes.py
===================================================================
--- branches/mathtex/lib/matplotlib/axes.py 2009-07-29 16:58:13 UTC (rev 7305)
+++ branches/mathtex/lib/matplotlib/axes.py 2009-07-29 17:14:05 UTC (rev 7306)
@@ -199,21 +199,6 @@
func = getattr(fill_poly,funcName)
func(val)
- def _xy_from_y(self, y):
- if self.axes.yaxis is not None:
- b = self.axes.yaxis.update_units(y)
- if b: return np.arange(len(y)), y, False
-
- if not ma.isMaskedArray(y):
- y = np.asarray(y)
- if len(y.shape) == 1:
- y = y[:,np.newaxis]
- nr, nc = y.shape
- x = np.arange(nr)
- if len(x.shape) == 1:
- x = x[:,np.newaxis]
- return x,y, True
-
def _xy_from_xy(self, x, y):
if self.axes.xaxis is not None and self.axes.yaxis is not None:
bx = self.axes.xaxis.update_units(x)
@@ -223,197 +208,107 @@
if by:
y = self.axes.convert_yunits(y)
- x = ma.asarray(x)
- y = ma.asarray(y)
- if len(x.shape) == 1:
+ x = np.atleast_1d(x) #like asanyarray, but converts scalar to array
+ y = np.atleast_1d(y)
+ if x.shape[0] != y.shape[0]:
+ raise ValueError("x and y must have same first dimension")
+ if x.ndim > 2 or y.ndim > 2:
+ raise ValueError("x and y can be no greater than 2-D")
+
+ if x.ndim == 1:
x = x[:,np.newaxis]
- if len(y.shape) == 1:
+ if y.ndim == 1:
y = y[:,np.newaxis]
- nrx, ncx = x.shape
- nry, ncy = y.shape
- assert nrx == nry, 'Dimensions of x and y are incompatible'
- if ncx == ncy:
- return x, y, True
- if ncx == 1:
- x = np.repeat(x, ncy, axis=1)
- if ncy == 1:
- y = np.repeat(y, ncx, axis=1)
- assert x.shape == y.shape, 'Dimensions of x and y are incompatible'
- return x, y, True
+ return x, y
+ def _makeline(self, x, y, kw, kwargs):
+ kw = kw.copy() # Don't modify the original kw.
+ if not 'color' in kw:
+ kw['color'] = self._get_next_cycle_color()
+ # (can't use setdefault because it always evaluates
+ # its second argument)
+ seg = mlines.Line2D(x, y,
+ axes=self.axes,
+ **kw
+ )
+ self.set_lineprops(seg, **kwargs)
+ return seg
- def _plot_1_arg(self, y, **kwargs):
- assert self.command == 'plot', 'fill needs at least 2 arguments'
- ret = []
+ def _makefill(self, x, y, kw, kwargs):
+ try:
+ facecolor = kw['color']
+ except KeyError:
+ facecolor = self._get_next_cycle_color()
+ seg = mpatches.Polygon(np.hstack(
+ (x[:,np.newaxis],y[:,np.newaxis])),
+ facecolor = facecolor,
+ fill=True,
+ closed=kw['closed']
+ )
+ self.set_patchprops(seg, **kwargs)
+ return seg
- x, y, multicol = self._xy_from_y(y)
- if multicol:
- for j in xrange(y.shape[1]):
- color = self._get_next_cycle_color()
- seg = mlines.Line2D(x, y[:,j],
- color = color,
- axes=self.axes,
- )
- self.set_lineprops(seg, **kwargs)
- ret.append(seg)
+ def _plot_args(self, tup, kwargs):
+ ret = []
+ if len(tup) > 1 and is_string_like(tup[-1]):
+ linestyle, marker, color = _process_plot_format(tup[-1])
+ tup = tup[:-1]
+ elif len(tup) == 3:
+ raise ValueError, 'third arg must be a format string'
else:
- color = self._get_next_cycle_color()
- seg = mlines.Line2D(x, y,
- color = color,
- axes=self.axes,
- )
- self.set_lineprops(seg, **kwargs)
- ret.append(seg)
+ linestyle, marker, color = None, None, None
+ kw = {}
+ for k, v in zip(('linestyle', 'marker', 'color'),
+ (linestyle, marker, color)):
+ if v is not None:
+ kw[k] = v
- return ret
+ y = np.atleast_1d(tup[-1])
- def _plot_2_args(self, tup2, **kwargs):
- ret = []
- if is_string_like(tup2[1]):
-
- assert self.command == 'plot', ('fill needs at least 2 non-string '
- 'arguments')
- y, fmt = tup2
- x, y, multicol = self._xy_from_y(y)
-
- linestyle, marker, color = _process_plot_format(fmt)
-
- def makeline(x, y):
- _color = color
- if _color is None:
- _color = self._get_next_cycle_color()
- seg = mlines.Line2D(x, y,
- color=_color,
- linestyle=linestyle, marker=marker,
- axes=self.axes,
- )
- self.set_lineprops(seg, **kwargs)
- ret.append(seg)
-
- if multicol:
- for j in xrange(y.shape[1]):
- makeline(x[:,j], y[:,j])
- else:
- makeline(x, y)
-
- return ret
+ if len(tup) == 2:
+ x = np.atleast_1d(tup[0])
else:
+ x = np.arange(y.shape[0], dtype=float)
- x, y = tup2
- x, y, multicol = self._xy_from_xy(x, y)
+ x, y = self._xy_from_xy(x, y)
- def makeline(x, y):
- color = self._get_next_cycle_color()
- seg = mlines.Line2D(x, y,
- color=color,
- axes=self.axes,
- )
- self.set_lineprops(seg, **kwargs)
- ret.append(seg)
-
- def makefill(x, y):
- facecolor = self._get_next_cycle_color()
- seg = mpatches.Polygon(np.hstack(
- (x[:,np.newaxis],y[:,np.newaxis])),
- facecolor = facecolor,
- fill=True,
- closed=closed
- )
- self.set_patchprops(seg, **kwargs)
- ret.append(seg)
-
- if self.command == 'plot':
- func = makeline
- else:
- closed = kwargs.get('closed', True)
- func = makefill
- if multicol:
- for j in xrange(y.shape[1]):
- func(x[:,j], y[:,j])
- else:
- func(x, y)
-
-
- return ret
-
- def _plot_3_args(self, tup3, **kwargs):
- ret = []
-
- x, y, fmt = tup3
- x, y, multicol = self._xy_from_xy(x, y)
-
- linestyle, marker, color = _process_plot_format(fmt)
-
- def makeline(x, y):
- _color = color
- if _color is None:
- _color = self._get_next_cycle_color()
- seg = mlines.Line2D(x, y,
- color=_color,
- linestyle=linestyle, marker=marker,
- axes=self.axes,
- )
- self.set_lineprops(seg, **kwargs)
- ret.append(seg)
-
- def makefill(x, y):
- facecolor = color
- seg = mpatches.Polygon(np.hstack(
- (x[:,np.newaxis],y[:,np.newaxis])),
- facecolor = facecolor,
- fill=True,
- closed=closed
- )
- self.set_patchprops(seg, **kwargs)
- ret.append(seg)
-
if self.command == 'plot':
- func = makeline
+ func = self._makeline
else:
- closed = kwargs.get('closed', True)
- func = makefill
+ kw['closed'] = kwargs.get('closed', True)
+ func = self._makefill
- if multicol:
- for j in xrange(y.shape[1]):
- func(x[:,j], y[:,j])
- else:
- func(x, y)
+ ncx, ncy = x.shape[1], y.shape[1]
+ for j in xrange(max(ncx, ncy)):
+ seg = func(x[:,j%ncx], y[:,j%ncy], kw, kwargs)
+ ret.append(seg)
return ret
+
def _grab_next_args(self, *args, **kwargs):
remaining = args
while 1:
- if len(remaining)==0: return
- if len(remaining)==1:
- for seg in self._plot_1_arg(remaining[0], **kwargs):
+ if len(remaining)==0:
+ return
+ if len(remaining) <= 3:
+ for seg in self._plot_args(remaining, kwargs):
yield seg
- remaining = []
- continue
- if len(remaining)==2:
- for seg in self._plot_2_args(remaining, **kwargs):
- yield seg
- remaining = []
- continue
- if len(remaining)==3:
- if not is_string_like(remaining[2]):
- raise ValueError, 'third arg must be a format string'
- for seg in self._plot_3_args(remaining, **kwargs):
- yield seg
- remaining=[]
- continue
+ return
+
if is_string_like(remaining[2]):
- for seg in self._plot_3_args(remaining[:3], **kwargs):
- yield seg
- remaining=remaining[3:]
+ isplit = 3
else:
- for seg in self._plot_2_args(remaining[:2], **kwargs):
- yield seg
- remaining=remaining[2:]
+ isplit = 2
+ for seg in self._plot_args(remaining[:isplit], kwargs):
+ yield seg
+ remaining=remaining[isplit:]
+
+
class Axes(martist.Artist):
"""
The :class:`Axes` contains most of the figure elements:
@@ -4109,9 +4004,9 @@
Keyword arguments:
*where*: [ 'pre' | 'post' | 'mid' ]
- If 'pre', the interval from x[i] to x[i+1] has level y[i]
+ If 'pre', the interval from x[i] to x[i+1] has level y[i+1]
- If 'post', that interval has level y[i+1]
+ If 'post', that interval has level y[i]
If 'mid', the jumps in *y* occur half-way between the
*x*-values.
Modified: branches/mathtex/lib/matplotlib/backends/backend_pdf.py
===================================================================
--- branches/mathtex/lib/matplotlib/backends/backend_pdf.py 2009-07-29 16:58:13 UTC (rev 7305)
+++ branches/mathtex/lib/matplotlib/backends/backend_pdf.py 2009-07-29 17:14:05 UTC (rev 7306)
@@ -1743,14 +1743,27 @@
return `d`
def _strokep(self):
+ """
+ Predicate: does the path need to be stroked (its outline drawn)?
+ This tests for the various conditions that disable stroking
+ the path, in which case it would presumably be filled.
+ """
return (self._linewidth > 0 and self._alpha > 0 and
(len(self._rgb) <= 3 or self._rgb[3] != 0.0))
def _fillp(self):
- return ((self._fillcolor is not None or self._hatch) and
- (len(self._fillcolor) <= 3 or self._fillcolor[3] != 0.0))
+ """
+ Predicate: does the path need to be filled?
+ """
+ return self._hatch or \
+ (self._fillcolor is not None and
+ (len(self._fillcolor) <= 3 or self._fillcolor[3] != 0.0))
def close_and_paint(self):
+ """
+ Return the appropriate pdf operator to close the path and
+ cause it to be stroked, filled, or both.
+ """
if self._strokep():
if self._fillp():
return Op.close_fill_stroke
@@ -1763,6 +1776,10 @@
return Op.endpath
def paint(self):
+ """
+ Return the appropriate pdf operator to cause the path to be
+ stroked, filled, or both.
+ """
if self._strokep():
if self._fillp():
return Op.fill_stroke
Modified: branches/mathtex/lib/matplotlib/backends/backend_svg.py
===================================================================
--- branches/mathtex/lib/matplotlib/backends/backend_svg.py 2009-07-29 16:58:13 UTC (rev 7305)
+++ branches/mathtex/lib/matplotlib/backends/backend_svg.py 2009-07-29 17:14:05 UTC (rev 7306)
@@ -106,9 +106,13 @@
path_data = self._convert_path(
gc.get_hatch_path(),
Affine2D().scale(HATCH_SIZE).scale(1.0, -1.0).translate(0, HATCH_SIZE))
+ if rgbFace is None:
+ fill = 'none'
+ else:
+ fill = rgb2hex(rgbFace)
self._svgwriter.write(
'<rect x="0" y="0" width="%d" height="%d" fill="%s"/>' %
- (HATCH_SIZE+1, HATCH_SIZE+1, rgb2hex(rgbFace)))
+ (HATCH_SIZE+1, HATCH_SIZE+1, fill))
path = '<path d="%s" fill="%s" stroke="%s" stroke-width="1.0"/>' % (
path_data, rgb2hex(gc.get_rgb()[:3]), rgb2hex(gc.get_rgb()[:3]))
self._svgwriter.write(path)
Modified: branches/mathtex/lib/matplotlib/collections.py
===================================================================
--- branches/mathtex/lib/matplotlib/collections.py 2009-07-29 16:58:13 UTC (rev 7305)
+++ branches/mathtex/lib/matplotlib/collections.py 2009-07-29 17:14:05 UTC (rev 7306)
@@ -670,6 +670,9 @@
def set_verts(self, verts, closed=True):
'''This allows one to delay initialization of the vertices.'''
+ if np.ma.isMaskedArray(verts):
+ verts = verts.astype(np.float_).filled(np.nan)
+ # This is much faster than having Path do it one at a time.
if closed:
self._paths = []
for xy in verts:
Modified: branches/mathtex/lib/matplotlib/delaunay/VoronoiDiagramGenerator.cpp
===================================================================
--- branches/mathtex/lib/matplotlib/delaunay/VoronoiDiagramGenerator.cpp 2009-07-29 16:58:13 UTC (rev 7305)
+++ branches/mathtex/lib/matplotlib/delaunay/VoronoiDiagramGenerator.cpp 2009-07-29 17:14:05 UTC (rev 7306)
@@ -12,9 +12,9 @@
* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
*/
-/*
- * This code was originally written by Stephan Fortune in C code. Shane O'Sullivan,
- * have since modified it, encapsulating it in a C++ class and, fixing memory leaks and
+/*
+ * This code was originally written by Stephan Fortune in C code. Shane O'Sullivan,
+ * have since modified it, encapsulating it in a C++ class and, fixing memory leaks and
* adding accessors to the Voronoi Edges.
* Permission to use, copy, modify, and distribute this software for any
* purpose without fee is hereby granted, provided that this entire notice
@@ -26,7 +26,7 @@
* REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
*/
-
+
/*
* Subsequently, Robert Kern modified it to yield Python objects.
* Copyright 2005 Robert Kern <rob...@gm...>
@@ -78,9 +78,9 @@
nsites=numPoints;
plot = 0;
- triangulate = 0;
+ triangulate = 0;
debug = 1;
- sorted = 0;
+ sorted = 0;
freeinit(&sfl, sizeof (Site));
sites = (struct Site *) myalloc(nsites*sizeof( *sites));
@@ -112,9 +112,9 @@
//printf("\n%f %f\n",xValues[i],yValues[i]);
}
-
+
qsort(sites, nsites, sizeof (*sites), scomp);
-
+
siteidx = 0;
geominit();
double temp = 0;
@@ -134,9 +134,9 @@
borderMinY = minY;
borderMaxX = maxX;
borderMaxY = maxY;
+
+ siteidx = 0;
- siteidx = 0;
-
voronoi(triangulate);
return true;
@@ -191,25 +191,25 @@
struct Halfedge * VoronoiDiagramGenerator::ELgethash(int b)
{
struct Halfedge *he;
-
- if(b<0 || b>=ELhashsize)
+
+ if(b<0 || b>=ELhashsize)
return((struct Halfedge *) NULL);
- he = ELhash[b];
- if (he == (struct Halfedge *) NULL || he->ELedge != (struct Edge *) DELETED )
+ he = ELhash[b];
+ if (he == (struct Halfedge *) NULL || he->ELedge != (struct Edge *) DELETED )
return (he);
-
+
/* Hash table points to deleted half edge. Patch as necessary. */
ELhash[b] = (struct Halfedge *) NULL;
- if ((he -> ELrefcnt -= 1) == 0)
+ if ((he -> ELrefcnt -= 1) == 0)
makefree((Freenode*)he, &hfl);
return ((struct Halfedge *) NULL);
-}
+}
struct Halfedge * VoronoiDiagramGenerator::ELleftbnd(struct Point *p)
{
int i, bucket;
struct Halfedge *he;
-
+
/* Use hash table to get close to desired halfedge */
bucket = (int)((p->x - xmin)/deltax * ELhashsize); //use the hash function to find the place in the hash map that this HalfEdge should be
@@ -218,12 +218,12 @@
he = ELgethash(bucket);
if(he == (struct Halfedge *) NULL) //if the HE isn't found, search backwards and forwards in the hash map for the first non-null entry
- {
+ {
for(i=1; 1 ; i += 1)
- {
- if ((he=ELgethash(bucket-i)) != (struct Halfedge *) NULL)
+ {
+ if ((he=ELgethash(bucket-i)) != (struct Halfedge *) NULL)
break;
- if ((he=ELgethash(bucket+i)) != (struct Halfedge *) NULL)
+ if ((he=ELgethash(bucket+i)) != (struct Halfedge *) NULL)
break;
};
totalsearch += i;
@@ -232,22 +232,22 @@
/* Now search linear list of halfedges for the correct one */
if (he==ELleftend || (he != ELrightend && right_of(he,p)))
{
- do
+ do
{
he = he -> ELright;
} while (he!=ELrightend && right_of(he,p)); //keep going right on the list until either the end is reached, or you find the 1st edge which the point
he = he -> ELleft; //isn't to the right of
}
else //if the point is to the left of the HalfEdge, then search left for the HE just to the left of the point
- do
+ do
{
he = he -> ELleft;
} while (he!=ELleftend && !right_of(he,p));
-
+
/* Update hash table and reference counts */
if(bucket > 0 && bucket <ELhashsize-1)
- {
- if(ELhash[bucket] != (struct Halfedge *) NULL)
+ {
+ if(ELhash[bucket] != (struct Halfedge *) NULL)
{
ELhash[bucket] -> ELrefcnt -= 1;
}
@@ -281,9 +281,9 @@
struct Site * VoronoiDiagramGenerator::leftreg(struct Halfedge *he)
{
- if(he -> ELedge == (struct Edge *)NULL)
+ if(he -> ELedge == (struct Edge *)NULL)
return(bottomsite);
- return( he -> ELpm == le ?
+ return( he -> ELpm == le ?
he -> ELedge -> reg[le] : he -> ELedge -> reg[re]);
}
@@ -297,7 +297,7 @@
}
void VoronoiDiagramGenerator::geominit()
-{
+{
double sn;
freeinit(&efl, sizeof(Edge));
@@ -313,17 +313,17 @@
struct Edge * VoronoiDiagramGenerator::bisect(struct Site *s1, struct Site *s2)
{
double dx,dy,adx,ady;
- struct Edge *newedge;
+ struct Edge *newedge;
newedge = (struct Edge *) getfree(&efl);
-
+
newedge -> reg[0] = s1; //store the sites that this edge is bisecting
newedge -> reg[1] = s2;
- ref(s1);
+ ref(s1);
ref(s2);
newedge -> ep[0] = (struct Site *) NULL; //to begin with, there are no endpoints on the bisector - it goes to infinity
newedge -> ep[1] = (struct Site *) NULL;
-
+
dx = s2->coord.x - s1->coord.x; //get the difference in x dist between the sites
dy = s2->coord.y - s1->coord.y;
adx = dx>0 ? dx : -dx; //make sure that the difference in positive
@@ -331,18 +331,18 @@
newedge -> c = (double)(s1->coord.x * dx + s1->coord.y * dy + (dx*dx + dy*dy)*0.5);//get the slope of the line
if (adx>ady)
- {
+ {
newedge -> a = 1.0; newedge -> b = dy/dx; newedge -> c /= dx;//set formula of line, with x fixed to 1
}
else
- {
+ {
newedge -> b = 1.0; newedge -> a = dx/dy; newedge -> c /= dy;//set formula of line, with y fixed to 1
};
-
+
newedge -> edgenbr = nedges;
//printf("\nbisect(%d) ((%f,%f) and (%f,%f)",nedges,s1->coord.x,s1->coord.y,s2->coord.x,s2->coord.y);
-
+
nedges += 1;
return(newedge);
}
@@ -355,40 +355,40 @@
double d, xint, yint;
int right_of_site;
struct Site *v;
-
+
e1 = el1 -> ELedge;
e2 = el2 -> ELedge;
- if(e1 == (struct Edge*)NULL || e2 == (struct Edge*)NULL)
+ if(e1 == (struct Edge*)NULL || e2 == (struct Edge*)NULL)
return ((struct Site *) NULL);
//if the two edges bisect the same parent, return null
- if (e1->reg[1] == e2->reg[1])
+ if (e1->reg[1] == e2->reg[1])
return ((struct Site *) NULL);
-
+
d = e1->a * e2->b - e1->b * e2->a;
- if (-1.0e-10<d && d<1.0e-10)
+ if (-1.0e-10<d && d<1.0e-10)
return ((struct Site *) NULL);
-
+
xint = (e1->c*e2->b - e2->c*e1->b)/d;
yint = (e2->c*e1->a - e1->c*e2->a)/d;
-
+
if( (e1->reg[1]->coord.y < e2->reg[1]->coord.y) ||
(e1->reg[1]->coord.y == e2->reg[1]->coord.y &&
e1->reg[1]->coord.x < e2->reg[1]->coord.x) )
- {
- el = el1;
+ {
+ el = el1;
e = e1;
}
else
- {
- el = el2;
+ {
+ el = el2;
e = e2;
};
-
+
right_of_site = xint >= e -> reg[1] -> coord.x;
- if ((right_of_site && el -> ELpm == le) || (!right_of_site && el -> ELpm == re))
+ if ((right_of_site && el -> ELpm == le) || (!right_of_site && el -> ELpm == re))
return ((struct Site *) NULL);
-
+
//create a new site at the point of intersection - this is a new vector event waiting to happen
v = (struct Site *) getfree(&sfl);
v -> refcnt = 0;
@@ -404,22 +404,22 @@
struct Site *topsite;
int right_of_site, above, fast;
double dxp, dyp, dxs, t1, t2, t3, yl;
-
+
e = el -> ELedge;
topsite = e -> reg[1];
right_of_site = p -> x > topsite -> coord.x;
if(right_of_site && el -> ELpm == le) return(1);
if(!right_of_site && el -> ELpm == re) return (0);
-
+
if (e->a == 1.0)
{ dyp = p->y - topsite->coord.y;
dxp = p->x - topsite->coord.x;
fast = 0;
if ((!right_of_site & (e->b<0.0)) | (right_of_site & (e->b>=0.0)) )
- { above = dyp>= e->b*dxp;
+ { above = dyp>= e->b*dxp;
fast = above;
}
- else
+ else
{ above = p->x + p->y*e->b > e-> c;
if(e->b<0.0) above = !above;
if (!above) fast = 1;
@@ -446,7 +446,7 @@
{
e -> ep[lr] = s;
ref(s);
- if(e -> ep[re-lr]== (struct Site *) NULL)
+ if(e -> ep[re-lr]== (struct Site *) NULL)
return;
clip_line(e);
@@ -477,7 +477,7 @@
void VoronoiDiagramGenerator::deref(struct Site *v)
{
v -> refcnt -= 1;
- if (v -> refcnt == 0 )
+ if (v -> refcnt == 0 )
makefree((Freenode*)v, &sfl);
...
[truncated message content] |
|
From: <evi...@us...> - 2009-07-29 16:58:21
|
Revision: 7305
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7305&view=rev
Author: evilguru
Date: 2009-07-29 16:58:13 +0000 (Wed, 29 Jul 2009)
Log Message:
-----------
Try to add merge tracking to the mathtex branch.
Property Changed:
----------------
branches/mathtex/
Property changes on: branches/mathtex
___________________________________________________________________
Modified: svnmerge-integrated
- /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-7253
+ /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-7253 /trunk/matplotlib:1-7262
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <evi...@us...> - 2009-07-29 09:57:47
|
Revision: 7304
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7304&view=rev
Author: evilguru
Date: 2009-07-29 09:57:39 +0000 (Wed, 29 Jul 2009)
Log Message:
-----------
Add support for mathtext.default to the OS X backend. This still requires testing from a Mac user.
Modified Paths:
--------------
branches/mathtex/lib/matplotlib/backends/backend_macosx.py
Modified: branches/mathtex/lib/matplotlib/backends/backend_macosx.py
===================================================================
--- branches/mathtex/lib/matplotlib/backends/backend_macosx.py 2009-07-28 22:43:15 UTC (rev 7303)
+++ branches/mathtex/lib/matplotlib/backends/backend_macosx.py 2009-07-29 09:57:39 UTC (rev 7304)
@@ -97,7 +97,8 @@
if not HAVE_MATHTEX:
return
- m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(), self.dpi)
+ m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(),
+ self.dpi, rcParams['mathtext.default'])
b = MathtexBackendImage()
m.render_to_backend(b)
@@ -125,7 +126,7 @@
if ismath:
if HAVE_MATHTEX:
m = Mathtex(s, rcParams['mathtext.fontset'],
- prop.get_size_in_points(), self.dpi)
+ prop.get_size_in_points(), self.dpi, rcParams['mathtext.default'])
return m.width, m.height, m.depth
else:
warnings.warn('matplotlib was compiled without mathtex support. ' +
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2009-07-28 22:43:25
|
Revision: 7303
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7303&view=rev
Author: efiring
Date: 2009-07-28 22:43:15 +0000 (Tue, 28 Jul 2009)
Log Message:
-----------
Speed up quiver for large numbers of arrows; key tip given by Ray Speth.
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/collections.py
trunk/matplotlib/lib/matplotlib/quiver.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2009-07-28 20:56:07 UTC (rev 7302)
+++ trunk/matplotlib/CHANGELOG 2009-07-28 22:43:15 UTC (rev 7303)
@@ -1,3 +1,5 @@
+2009-07-28 Quiver speed improved, thanks to tip by Ray Speth. -EF
+
2009-07-27 Simplify argument handling code for plot method. -EF
2009-07-25 Allow "plot(1, 2, 'r*')" to work. - EF
Modified: trunk/matplotlib/lib/matplotlib/collections.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/collections.py 2009-07-28 20:56:07 UTC (rev 7302)
+++ trunk/matplotlib/lib/matplotlib/collections.py 2009-07-28 22:43:15 UTC (rev 7303)
@@ -670,6 +670,9 @@
def set_verts(self, verts, closed=True):
'''This allows one to delay initialization of the vertices.'''
+ if np.ma.isMaskedArray(verts):
+ verts = verts.astype(np.float_).filled(np.nan)
+ # This is much faster than having Path do it one at a time.
if closed:
self._paths = []
for xy in verts:
Modified: trunk/matplotlib/lib/matplotlib/quiver.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/quiver.py 2009-07-28 20:56:07 UTC (rev 7302)
+++ trunk/matplotlib/lib/matplotlib/quiver.py 2009-07-28 22:43:15 UTC (rev 7303)
@@ -253,8 +253,12 @@
self._set_transform()
_pivot = self.Q.pivot
self.Q.pivot = self.pivot[self.labelpos]
+ # Hack: save and restore the Umask
+ _mask = self.Q.Umask
+ self.Q.Umask = ma.nomask
self.verts = self.Q._make_verts(np.array([self.U]),
np.zeros((1,)))
+ self.Q.Umask = _mask
self.Q.pivot = _pivot
kw = self.Q.polykw
kw.update(self.kw)
@@ -388,9 +392,9 @@
X, Y, U, V, C = [None]*5
args = list(args)
if len(args) == 3 or len(args) == 5:
- C = ma.masked_invalid(args.pop(-1), copy=False)
- V = ma.masked_invalid(args.pop(-1), copy=False)
- U = ma.masked_invalid(args.pop(-1), copy=False)
+ C = np.asanyarray(args.pop(-1))
+ V = np.asanyarray(args.pop(-1))
+ U = np.asanyarray(args.pop(-1))
if U.ndim == 1:
nr, nc = 1, U.shape[0]
else:
@@ -430,10 +434,21 @@
collections.PolyCollection.draw(self, renderer)
def set_UVC(self, U, V, C=None):
- self.U = U.ravel()
- self.V = V.ravel()
+ U = ma.masked_invalid(U, copy=False).ravel()
+ V = ma.masked_invalid(V, copy=False).ravel()
+ mask = ma.mask_or(U.mask, V.mask, copy=False, shrink=True)
if C is not None:
- self.set_array(C.ravel())
+ C = ma.masked_invalid(C, copy=False).ravel()
+ mask = ma.mask_or(mask, C.mask, copy=False, shrink=True)
+ if mask is ma.nomask:
+ C = C.filled()
+ else:
+ C = ma.array(C, mask=mask, copy=False)
+ self.U = U.filled(1)
+ self.V = V.filled(1)
+ self.Umask = mask
+ if C is not None:
+ self.set_array(C)
self._new_UV = True
def _set_transform(self):
@@ -463,32 +478,33 @@
def _angles(self, U, V, eps=0.001):
xy = self.ax.transData.transform(self.XY)
- uv = ma.hstack((U[:,np.newaxis], V[:,np.newaxis])).filled(0)
+ uv = np.hstack((U[:,np.newaxis], V[:,np.newaxis]))
xyp = self.ax.transData.transform(self.XY + eps * uv)
dxy = xyp - xy
- ang = ma.arctan2(dxy[:,1], dxy[:,0])
+ ang = np.arctan2(dxy[:,1], dxy[:,0])
return ang
def _make_verts(self, U, V):
- uv = ma.asarray(U+V*1j)
- a = ma.absolute(uv)
+ uv = (U+V*1j)
+ a = np.absolute(uv)
if self.scale is None:
sn = max(10, math.sqrt(self.N))
- scale = 1.8 * a.mean() * sn / self.span # crude auto-scaling
+ scale = 1.8 * a[~self.Umask].mean() * sn / self.span # crude auto-scaling
self.scale = scale
length = a/(self.scale*self.width)
X, Y = self._h_arrows(length)
if self.angles == 'xy':
- theta = self._angles(U, V).filled(0)
+ theta = self._angles(U, V)
elif self.angles == 'uv':
- theta = np.angle(uv.filled(0))
+ theta = np.angle(uv)
else:
theta = ma.masked_invalid(self.angles, copy=False).filled(0)
theta *= (np.pi/180.0)
theta.shape = (theta.shape[0], 1) # for broadcasting
xy = (X+Y*1j) * np.exp(1j*theta)*self.width
xy = xy[:,:,np.newaxis]
- XY = ma.concatenate((xy.real, xy.imag), axis=2)
+ XY = np.concatenate((xy.real, xy.imag), axis=2)
+
return XY
@@ -502,8 +518,8 @@
length = length.reshape(N, 1)
# This number is chosen based on when pixel values overflow in Agg
# causing rendering errors
- length = np.minimum(length, 2 ** 16)
-
+ #length = np.minimum(length, 2 ** 16)
+ np.clip(length, 0, 2**16, out=length)
# x, y: normal horizontal arrow
x = np.array([0, -self.headaxislength,
-self.headlength, 0], np.float64)
@@ -514,21 +530,20 @@
x0 = np.array([0, minsh-self.headaxislength,
minsh-self.headlength, minsh], np.float64)
y0 = 0.5 * np.array([1, 1, self.headwidth, 0], np.float64)
- ii = [0,1,2,3,2,1,0]
+ ii = [0,1,2,3,2,1,0,0]
X = x.take(ii, 1)
Y = y.take(ii, 1)
- Y[:, 3:] *= -1
+ Y[:, 3:-1] *= -1
X0 = x0.take(ii)
Y0 = y0.take(ii)
- Y0[3:] *= -1
+ Y0[3:-1] *= -1
shrink = length/minsh
X0 = shrink * X0[np.newaxis,:]
Y0 = shrink * Y0[np.newaxis,:]
- short = np.repeat(length < minsh, 7, axis=1)
- #print 'short', length < minsh
+ short = np.repeat(length < minsh, 8, axis=1)
# Now select X0, Y0 if short, otherwise X, Y
- X = ma.where(short, X0, X)
- Y = ma.where(short, Y0, Y)
+ np.putmask(X, short, X0)
+ np.putmask(Y, short, Y0)
if self.pivot[:3] == 'mid':
X -= 0.5 * X[:,3, np.newaxis]
elif self.pivot[:3] == 'tip':
@@ -538,14 +553,18 @@
tooshort = length < self.minlength
if tooshort.any():
# Use a heptagonal dot:
- th = np.arange(0,7,1, np.float64) * (np.pi/3.0)
+ th = np.arange(0,8,1, np.float64) * (np.pi/3.0)
x1 = np.cos(th) * self.minlength * 0.5
y1 = np.sin(th) * self.minlength * 0.5
X1 = np.repeat(x1[np.newaxis, :], N, axis=0)
Y1 = np.repeat(y1[np.newaxis, :], N, axis=0)
- tooshort = ma.repeat(tooshort, 7, 1)
- X = ma.where(tooshort, X1, X)
- Y = ma.where(tooshort, Y1, Y)
+ tooshort = np.repeat(tooshort, 8, 1)
+ np.putmask(X, tooshort, X1)
+ np.putmask(Y, tooshort, Y1)
+ if self.Umask is not ma.nomask:
+ mask = np.repeat(self.Umask[:,np.newaxis], 8, 1)
+ X = ma.array(X, mask=mask, copy=False)
+ Y = ma.array(Y, mask=mask, copy=False)
return X, Y
quiver_doc = _quiver_doc
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <evi...@us...> - 2009-07-28 20:56:20
|
Revision: 7302
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7302&view=rev
Author: evilguru
Date: 2009-07-28 20:56:07 +0000 (Tue, 28 Jul 2009)
Log Message:
-----------
Update the INSTALL file so that it includes information about mathtex.
Modified Paths:
--------------
branches/mathtex/INSTALL
Modified: branches/mathtex/INSTALL
===================================================================
--- branches/mathtex/INSTALL 2009-07-28 19:55:30 UTC (rev 7301)
+++ branches/mathtex/INSTALL 2009-07-28 20:56:07 UTC (rev 7302)
@@ -17,6 +17,11 @@
with agg support and use one of the GUI agg backends: GTKAgg, WXAgg,
TkAgg or FLTKAgg.
+ In addition matplotlib can also optionally make use of mathtex, a
+ pure python TeX rendering library. In previous versions of
+ matplotlib this was built in, however it will split off in mid-2009.
+ To ease installation mathtex is included in matplotlib in lib/mathtex.
+
COMPILING
You will need to have recent versions of freetype, libpng and zlib
@@ -45,13 +50,16 @@
/some/path/include/somheader.h, put /some/path in the basedir list
for your platform.
-
Once you have everything above set to your liking, just do the usual
thing
python setup.py build
python setup.py install
+ If mathtex is not already available on the system it can be installed
+ by following the instructions in lib/mathtex/INSTALL. The
+ dependencies are a subset of those required by matplotlib.
+
WINDOWS
If you don't already have python installed, you may want to consider
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2009-07-28 19:55:42
|
Revision: 7301
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7301&view=rev
Author: jdh2358
Date: 2009-07-28 19:55:30 +0000 (Tue, 28 Jul 2009)
Log Message:
-----------
added Tony's radar chart demo
Added Paths:
-----------
trunk/matplotlib/examples/api/radar_chart.py
Added: trunk/matplotlib/examples/api/radar_chart.py
===================================================================
--- trunk/matplotlib/examples/api/radar_chart.py (rev 0)
+++ trunk/matplotlib/examples/api/radar_chart.py 2009-07-28 19:55:30 UTC (rev 7301)
@@ -0,0 +1,144 @@
+import numpy as np
+
+import matplotlib.pyplot as plt
+from matplotlib.projections.polar import PolarAxes
+from matplotlib.projections import register_projection
+
+def radar_factory(num_vars, frame='circle'):
+ """Create a radar chart with `num_vars` axes."""
+ # calculate evenly-spaced axis angles
+ theta = 2*np.pi * np.linspace(0, 1-1./num_vars, num_vars)
+ # rotate theta such that the first axis is at the top
+ theta += np.pi/2
+
+ def draw_poly_frame(self, x0, y0, r):
+ # TODO: use transforms to convert (x, y) to (r, theta)
+ verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta]
+ return plt.Polygon(verts, closed=True, edgecolor='k')
+
+ def draw_circle_frame(self, x0, y0, r):
+ return plt.Circle((x0, y0), r)
+
+ frame_dict = {'polygon': draw_poly_frame, 'circle': draw_circle_frame}
+ if frame not in frame_dict:
+ raise ValueError, 'unknown value for `frame`: %s' % frame
+
+ class RadarAxes(PolarAxes):
+ """Class for creating a radar chart (a.k.a. a spider or star chart)
+
+ http://en.wikipedia.org/wiki/Radar_chart
+ """
+ name = 'radar'
+ # use 1 line segment to connect specified points
+ RESOLUTION = 1
+ # define draw_frame method
+ draw_frame = frame_dict[frame]
+
+ def fill(self, *args, **kwargs):
+ """Override fill so that line is closed by default"""
+ closed = kwargs.pop('closed', True)
+ return super(RadarAxes, self).fill(closed=closed, *args, **kwargs)
+
+ def plot(self, *args, **kwargs):
+ """Override plot so that line is closed by default"""
+ lines = super(RadarAxes, self).plot(*args, **kwargs)
+ for line in lines:
+ self._close_line(line)
+
+ def _close_line(self, line):
+ x, y = line.get_data()
+ # FIXME: markers at x[0], y[0] get doubled-up
+ if x[0] != x[-1]:
+ x = np.concatenate((x, [x[0]]))
+ y = np.concatenate((y, [y[0]]))
+ line.set_data(x, y)
+
+ def set_varlabels(self, labels):
+ self.set_thetagrids(theta * 180/np.pi, labels)
+
+ def _gen_axes_patch(self):
+ x0, y0 = (0.5, 0.5)
+ r = 0.5
+ return self.draw_frame(x0, y0, r)
+
+ register_projection(RadarAxes)
+ return theta
+
+
+if __name__ == '__main__':
+ #The following data is from the Denver Aerosol Sources and Health study.
+ #See doi:10.1016/j.atmosenv.2008.12.017
+ #
+ #The data are pollution source profile estimates for five modeled pollution
+ #sources (e.g., cars, wood-burning, etc) that emit 7-9 chemical species.
+ #The radar charts are experimented with here to see if we can nicely
+ #visualize how the modeled source profiles change across four scenarios:
+ # 1) No gas-phase species present, just seven particulate counts on
+ # Sulfate
+ # Nitrate
+ # Elemental Carbon (EC)
+ # Organic Carbon fraction 1 (OC)
+ # Organic Carbon fraction 2 (OC2)
+ # Organic Carbon fraction 3 (OC3)
+ # Pyrolized Organic Carbon (OP)
+ # 2)Inclusion of gas-phase specie carbon monoxide (CO)
+ # 3)Inclusion of gas-phase specie ozone (O3).
+ # 4)Inclusion of both gas-phase speciesis present...
+ N = 9
+ theta = radar_factory(N)
+ spoke_labels = ['Sulfate', 'Nitrate', 'EC', 'OC1', 'OC2', 'OC3', 'OP', 'CO',
+ 'O3']
+ f1_base = [0.88, 0.01, 0.03, 0.03, 0.00, 0.06, 0.01, 0.00, 0.00]
+ f1_CO = [0.88, 0.02, 0.02, 0.02, 0.00, 0.05, 0.00, 0.05, 0.00]
+ f1_O3 = [0.89, 0.01, 0.07, 0.00, 0.00, 0.05, 0.00, 0.00, 0.03]
+ f1_both = [0.87, 0.01, 0.08, 0.00, 0.00, 0.04, 0.00, 0.00, 0.01]
+
+ f2_base = [0.07, 0.95, 0.04, 0.05, 0.00, 0.02, 0.01, 0.00, 0.00]
+ f2_CO = [0.08, 0.94, 0.04, 0.02, 0.00, 0.01, 0.12, 0.04, 0.00]
+ f2_O3 = [0.07, 0.95, 0.05, 0.04, 0.00, 0.02, 0.12, 0.00, 0.00]
+ f2_both = [0.09, 0.95, 0.02, 0.03, 0.00, 0.01, 0.13, 0.06, 0.00]
+
+ f3_base = [0.01, 0.02, 0.85, 0.19, 0.05, 0.10, 0.00, 0.00, 0.00]
+ f3_CO = [0.01, 0.01, 0.79, 0.10, 0.00, 0.05, 0.00, 0.31, 0.00]
+ f3_O3 = [0.01, 0.02, 0.86, 0.27, 0.16, 0.19, 0.00, 0.00, 0.00]
+ f3_both = [0.01, 0.02, 0.71, 0.24, 0.13, 0.16, 0.00, 0.50, 0.00]
+
+ f4_base = [0.02, 0.01, 0.07, 0.01, 0.21, 0.12, 0.98, 0.00, 0.00]
+ f4_CO = [0.00, 0.02, 0.03, 0.38, 0.31, 0.31, 0.00, 0.59, 0.00]
+ f4_O3 = [0.01, 0.03, 0.00, 0.32, 0.29, 0.27, 0.00, 0.00, 0.95]
+ f4_both = [0.01, 0.03, 0.00, 0.28, 0.24, 0.23, 0.00, 0.44, 0.88]
+
+ f5_base = [0.01, 0.01, 0.02, 0.71, 0.74, 0.70, 0.00, 0.00, 0.00]
+ f5_CO = [0.02, 0.02, 0.11, 0.47, 0.69, 0.58, 0.88, 0.00, 0.00]
+ f5_O3 = [0.02, 0.00, 0.03, 0.37, 0.56, 0.47, 0.87, 0.00, 0.00]
+ f5_both = [0.02, 0.00, 0.18, 0.45, 0.64, 0.55, 0.86, 0.00, 0.16]
+
+ fig = plt.figure(figsize=(9,9))
+ # adjust spacing around the subplots
+ fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)
+ title_list = ['Basecase', 'With CO', 'With O3', 'CO & O3']
+ data = {'Basecase': [f1_base, f2_base, f3_base, f4_base, f5_base],
+ 'With CO': [f1_CO, f2_CO, f3_CO, f4_CO, f5_CO],
+ 'With O3': [f1_O3, f2_O3, f3_O3, f4_O3, f5_O3],
+ 'CO & O3': [f1_both, f2_both, f3_both, f4_both, f5_both]}
+ colors = ['b', 'r', 'g', 'm', 'y']
+ # chemicals range from 0 to 1
+ radial_grid = [0.2, 0.4, 0.6, 0.8]
+ # If you don't care about the order, you can loop over data_dict.items()
+ for n, title in enumerate(title_list):
+ ax = fig.add_subplot(2, 2, n+1, projection='radar')
+ plt.rgrids(radial_grid)
+ ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1),
+ horizontalalignment='center', verticalalignment='center')
+ for d, color in zip(data[title], colors):
+ ax.plot(theta, d, color=color)
+ ax.fill(theta, d, facecolor=color, alpha=0.25)
+ ax.set_varlabels(spoke_labels)
+ # add legend relative to top-left plot
+ plt.subplot(2,2,1)
+ labels = ('Factor 1', 'Factor 2', 'Factor 3', 'Factor 4', 'Factor 5')
+ legend = plt.legend(labels, loc=(0.9, .95), labelspacing=0.1)
+ plt.setp(legend.get_texts(), fontsize='small')
+ plt.figtext(0.5, 0.965, '5-Factor Solution Profiles Across Four Scenarios',
+ ha='center', color='black', weight='bold', size='large')
+ plt.show()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <lee...@us...> - 2009-07-27 21:41:20
|
Revision: 7300
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7300&view=rev
Author: leejjoon
Date: 2009-07-27 21:41:12 +0000 (Mon, 27 Jul 2009)
Log Message:
-----------
axes_zoom_effect.py modified to use floats (instead of strings) for alpha values
Modified Paths:
--------------
trunk/matplotlib/examples/pylab_examples/axes_zoom_effect.py
Modified: trunk/matplotlib/examples/pylab_examples/axes_zoom_effect.py
===================================================================
--- trunk/matplotlib/examples/pylab_examples/axes_zoom_effect.py 2009-07-27 19:49:20 UTC (rev 7299)
+++ trunk/matplotlib/examples/pylab_examples/axes_zoom_effect.py 2009-07-27 21:41:12 UTC (rev 7300)
@@ -51,7 +51,7 @@
prop_patches=kwargs.copy()
prop_patches["ec"]="none"
- prop_patches["alpha"]="0.2"
+ prop_patches["alpha"]=0.2
c1, c2, bbox_patch1, bbox_patch2, p = \
connect_bbox(mybbox1, mybbox2,
@@ -84,7 +84,7 @@
prop_patches=kwargs.copy()
prop_patches["ec"]="none"
- prop_patches["alpha"]="0.2"
+ prop_patches["alpha"]=0.2
c1, c2, bbox_patch1, bbox_patch2, p = \
connect_bbox(mybbox1, mybbox2,
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <evi...@us...> - 2009-07-27 19:49:30
|
Revision: 7299
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7299&view=rev
Author: evilguru
Date: 2009-07-27 19:49:20 +0000 (Mon, 27 Jul 2009)
Log Message:
-----------
Fix an error importing afm.py.
Modified Paths:
--------------
branches/mathtex/lib/matplotlib/afm.py
Modified: branches/mathtex/lib/matplotlib/afm.py
===================================================================
--- branches/mathtex/lib/matplotlib/afm.py 2009-07-27 19:35:47 UTC (rev 7298)
+++ branches/mathtex/lib/matplotlib/afm.py 2009-07-27 19:49:20 UTC (rev 7299)
@@ -35,7 +35,7 @@
"""
import sys, os, re
-from _mathtext_data import uni2type1
+from _font_data import uni2type1
#Convert string the a python type
_to_int = int
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2009-07-27 19:35:55
|
Revision: 7298
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7298&view=rev
Author: efiring
Date: 2009-07-27 19:35:47 +0000 (Mon, 27 Jul 2009)
Log Message:
-----------
Simplify plot argument handling code.
The only side effect of the change should be that previously,
plotting multiple columns required that x and y have the same
number of columns, or that one of them have only one column.
Now the plotting simply cycles through the columns of both,
wrapping back to the first column as needed.
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/axes.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2009-07-27 19:23:55 UTC (rev 7297)
+++ trunk/matplotlib/CHANGELOG 2009-07-27 19:35:47 UTC (rev 7298)
@@ -1,3 +1,5 @@
+2009-07-27 Simplify argument handling code for plot method. -EF
+
2009-07-25 Allow "plot(1, 2, 'r*')" to work. - EF
2009-07-22 Added an 'interp' keyword to griddata so the faster linear
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2009-07-27 19:23:55 UTC (rev 7297)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2009-07-27 19:35:47 UTC (rev 7298)
@@ -199,21 +199,6 @@
func = getattr(fill_poly,funcName)
func(val)
- def _xy_from_y(self, y):
- if self.axes.yaxis is not None:
- b = self.axes.yaxis.update_units(y)
- if b: return np.arange(len(y)), y, False
-
- if not ma.isMaskedArray(y):
- y = np.asarray(y)
- if len(y.shape) == 1:
- y = y[:,np.newaxis]
- nr, nc = y.shape
- x = np.arange(nr)
- if len(x.shape) == 1:
- x = x[:,np.newaxis]
- return x,y, True
-
def _xy_from_xy(self, x, y):
if self.axes.xaxis is not None and self.axes.yaxis is not None:
bx = self.axes.xaxis.update_units(x)
@@ -223,197 +208,107 @@
if by:
y = self.axes.convert_yunits(y)
- x = ma.asarray(np.atleast_1d(x))
- y = ma.asarray(np.atleast_1d(y))
+ x = np.atleast_1d(x) #like asanyarray, but converts scalar to array
+ y = np.atleast_1d(y)
+ if x.shape[0] != y.shape[0]:
+ raise ValueError("x and y must have same first dimension")
+ if x.ndim > 2 or y.ndim > 2:
+ raise ValueError("x and y can be no greater than 2-D")
+
if x.ndim == 1:
x = x[:,np.newaxis]
if y.ndim == 1:
y = y[:,np.newaxis]
- nrx, ncx = x.shape
- nry, ncy = y.shape
- assert nrx == nry, 'Dimensions of x and y are incompatible'
- if ncx == ncy:
- return x, y, True
- if ncx == 1:
- x = np.repeat(x, ncy, axis=1)
- if ncy == 1:
- y = np.repeat(y, ncx, axis=1)
- assert x.shape == y.shape, 'Dimensions of x and y are incompatible'
- return x, y, True
+ return x, y
+ def _makeline(self, x, y, kw, kwargs):
+ kw = kw.copy() # Don't modify the original kw.
+ if not 'color' in kw:
+ kw['color'] = self._get_next_cycle_color()
+ # (can't use setdefault because it always evaluates
+ # its second argument)
+ seg = mlines.Line2D(x, y,
+ axes=self.axes,
+ **kw
+ )
+ self.set_lineprops(seg, **kwargs)
+ return seg
- def _plot_1_arg(self, y, **kwargs):
- assert self.command == 'plot', 'fill needs at least 2 arguments'
- ret = []
+ def _makefill(self, x, y, kw, kwargs):
+ try:
+ facecolor = kw['color']
+ except KeyError:
+ facecolor = self._get_next_cycle_color()
+ seg = mpatches.Polygon(np.hstack(
+ (x[:,np.newaxis],y[:,np.newaxis])),
+ facecolor = facecolor,
+ fill=True,
+ closed=kw['closed']
+ )
+ self.set_patchprops(seg, **kwargs)
+ return seg
- x, y, multicol = self._xy_from_y(y)
- if multicol:
- for j in xrange(y.shape[1]):
- color = self._get_next_cycle_color()
- seg = mlines.Line2D(x, y[:,j],
- color = color,
- axes=self.axes,
- )
- self.set_lineprops(seg, **kwargs)
- ret.append(seg)
+ def _plot_args(self, tup, kwargs):
+ ret = []
+ if len(tup) > 1 and is_string_like(tup[-1]):
+ linestyle, marker, color = _process_plot_format(tup[-1])
+ tup = tup[:-1]
+ elif len(tup) == 3:
+ raise ValueError, 'third arg must be a format string'
else:
- color = self._get_next_cycle_color()
- seg = mlines.Line2D(x, y,
- color = color,
- axes=self.axes,
- )
- self.set_lineprops(seg, **kwargs)
- ret.append(seg)
+ linestyle, marker, color = None, None, None
+ kw = {}
+ for k, v in zip(('linestyle', 'marker', 'color'),
+ (linestyle, marker, color)):
+ if v is not None:
+ kw[k] = v
- return ret
+ y = np.atleast_1d(tup[-1])
- def _plot_2_args(self, tup2, **kwargs):
- ret = []
- if is_string_like(tup2[1]):
-
- assert self.command == 'plot', ('fill needs at least 2 non-string '
- 'arguments')
- y, fmt = tup2
- x, y, multicol = self._xy_from_y(y)
-
- linestyle, marker, color = _process_plot_format(fmt)
-
- def makeline(x, y):
- _color = color
- if _color is None:
- _color = self._get_next_cycle_color()
- seg = mlines.Line2D(x, y,
- color=_color,
- linestyle=linestyle, marker=marker,
- axes=self.axes,
- )
- self.set_lineprops(seg, **kwargs)
- ret.append(seg)
-
- if multicol:
- for j in xrange(y.shape[1]):
- makeline(x[:,j], y[:,j])
- else:
- makeline(x, y)
-
- return ret
+ if len(tup) == 2:
+ x = np.atleast_1d(tup[0])
else:
+ x = np.arange(y.shape[0], dtype=float)
- x, y = tup2
- x, y, multicol = self._xy_from_xy(x, y)
+ x, y = self._xy_from_xy(x, y)
- def makeline(x, y):
- color = self._get_next_cycle_color()
- seg = mlines.Line2D(x, y,
- color=color,
- axes=self.axes,
- )
- self.set_lineprops(seg, **kwargs)
- ret.append(seg)
-
- def makefill(x, y):
- facecolor = self._get_next_cycle_color()
- seg = mpatches.Polygon(np.hstack(
- (x[:,np.newaxis],y[:,np.newaxis])),
- facecolor = facecolor,
- fill=True,
- closed=closed
- )
- self.set_patchprops(seg, **kwargs)
- ret.append(seg)
-
- if self.command == 'plot':
- func = makeline
- else:
- closed = kwargs.get('closed', True)
- func = makefill
- if multicol:
- for j in xrange(y.shape[1]):
- func(x[:,j], y[:,j])
- else:
- func(x, y)
-
-
- return ret
-
- def _plot_3_args(self, tup3, **kwargs):
- ret = []
-
- x, y, fmt = tup3
- x, y, multicol = self._xy_from_xy(x, y)
-
- linestyle, marker, color = _process_plot_format(fmt)
-
- def makeline(x, y):
- _color = color
- if _color is None:
- _color = self._get_next_cycle_color()
- seg = mlines.Line2D(x, y,
- color=_color,
- linestyle=linestyle, marker=marker,
- axes=self.axes,
- )
- self.set_lineprops(seg, **kwargs)
- ret.append(seg)
-
- def makefill(x, y):
- facecolor = color
- seg = mpatches.Polygon(np.hstack(
- (x[:,np.newaxis],y[:,np.newaxis])),
- facecolor = facecolor,
- fill=True,
- closed=closed
- )
- self.set_patchprops(seg, **kwargs)
- ret.append(seg)
-
if self.command == 'plot':
- func = makeline
+ func = self._makeline
else:
- closed = kwargs.get('closed', True)
- func = makefill
+ kw['closed'] = kwargs.get('closed', True)
+ func = self._makefill
- if multicol:
- for j in xrange(y.shape[1]):
- func(x[:,j], y[:,j])
- else:
- func(x, y)
+ ncx, ncy = x.shape[1], y.shape[1]
+ for j in xrange(max(ncx, ncy)):
+ seg = func(x[:,j%ncx], y[:,j%ncy], kw, kwargs)
+ ret.append(seg)
return ret
+
def _grab_next_args(self, *args, **kwargs):
remaining = args
while 1:
- if len(remaining)==0: return
- if len(remaining)==1:
- for seg in self._plot_1_arg(remaining[0], **kwargs):
+ if len(remaining)==0:
+ return
+ if len(remaining) <= 3:
+ for seg in self._plot_args(remaining, kwargs):
yield seg
- remaining = []
- continue
- if len(remaining)==2:
- for seg in self._plot_2_args(remaining, **kwargs):
- yield seg
- remaining = []
- continue
- if len(remaining)==3:
- if not is_string_like(remaining[2]):
- raise ValueError, 'third arg must be a format string'
- for seg in self._plot_3_args(remaining, **kwargs):
- yield seg
- remaining=[]
- continue
+ return
+
if is_string_like(remaining[2]):
- for seg in self._plot_3_args(remaining[:3], **kwargs):
- yield seg
- remaining=remaining[3:]
+ isplit = 3
else:
- for seg in self._plot_2_args(remaining[:2], **kwargs):
- yield seg
- remaining=remaining[2:]
+ isplit = 2
+ for seg in self._plot_args(remaining[:isplit], kwargs):
+ yield seg
+ remaining=remaining[isplit:]
+
+
class Axes(martist.Artist):
"""
The :class:`Axes` contains most of the figure elements:
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2009-07-27 19:24:03
|
Revision: 7297
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7297&view=rev
Author: efiring
Date: 2009-07-27 19:23:55 +0000 (Mon, 27 Jul 2009)
Log Message:
-----------
In findobj_demo, exclude patches from objects to be colored blue.
Modified Paths:
--------------
trunk/matplotlib/examples/pylab_examples/findobj_demo.py
Modified: trunk/matplotlib/examples/pylab_examples/findobj_demo.py
===================================================================
--- trunk/matplotlib/examples/pylab_examples/findobj_demo.py 2009-07-27 12:30:35 UTC (rev 7296)
+++ trunk/matplotlib/examples/pylab_examples/findobj_demo.py 2009-07-27 19:23:55 UTC (rev 7297)
@@ -23,7 +23,7 @@
# match on arbitrary function
def myfunc(x):
- return hasattr(x, 'set_color')
+ return hasattr(x, 'set_color') and not hasattr(x, 'set_facecolor')
for o in fig.findobj(myfunc):
o.set_color('blue')
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <evi...@us...> - 2009-07-27 12:30:45
|
Revision: 7296
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7296&view=rev
Author: evilguru
Date: 2009-07-27 12:30:35 +0000 (Mon, 27 Jul 2009)
Log Message:
-----------
Add support for rcParams['mathtext.default'], currently broken due to a suspected bug in mathtex.
Modified Paths:
--------------
branches/mathtex/lib/matplotlib/backends/backend_agg.py
branches/mathtex/lib/matplotlib/backends/backend_cairo.py
branches/mathtex/lib/matplotlib/backends/backend_gdk.py
branches/mathtex/lib/matplotlib/backends/backend_pdf.py
branches/mathtex/lib/matplotlib/backends/backend_ps.py
branches/mathtex/lib/matplotlib/backends/backend_svg.py
Modified: branches/mathtex/lib/matplotlib/backends/backend_agg.py
===================================================================
--- branches/mathtex/lib/matplotlib/backends/backend_agg.py 2009-07-26 17:53:54 UTC (rev 7295)
+++ branches/mathtex/lib/matplotlib/backends/backend_agg.py 2009-07-27 12:30:35 UTC (rev 7296)
@@ -110,7 +110,8 @@
if __debug__: verbose.report('RendererAgg.draw_mathtext',
'debug-annoying')
if HAVE_MATHTEX:
- m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(), self.dpi)
+ m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(),
+ self.dpi, rcParams['mathtext.default'])
b = MathtexBackendImage()
m.render_to_backend(b)
@@ -164,7 +165,8 @@
'Math will not be rendered.')
return 0.0, 0.0, 0.0
else:
- m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(), self.dpi)
+ m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(),
+ self.dpi, rcParams['mathtext.default'])
return m.width, m.height, m.depth
font = self._get_agg_font(prop)
font.set_text(s, 0.0, flags=LOAD_FORCE_AUTOHINT) # the width and height of unrotated string
Modified: branches/mathtex/lib/matplotlib/backends/backend_cairo.py
===================================================================
--- branches/mathtex/lib/matplotlib/backends/backend_cairo.py 2009-07-26 17:53:54 UTC (rev 7295)
+++ branches/mathtex/lib/matplotlib/backends/backend_cairo.py 2009-07-27 12:30:35 UTC (rev 7296)
@@ -210,7 +210,8 @@
ctx = gc.ctx
- m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(), self.dpi)
+ m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(),
+ self.dpi, rcParams['mathtext.default'])
b = MathtexBackendCairo()
m.render_to_backend(b)
@@ -240,7 +241,8 @@
if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name())
if ismath:
if HAVE_MATHTEX:
- m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(), self.dpi)
+ m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(),
+ self.dpi, rcParams['mathtext.default'])
return m.width, m.height, m.depth
else:
warnings.warn('matplotlib was compiled without mathtex support. ' +
Modified: branches/mathtex/lib/matplotlib/backends/backend_gdk.py
===================================================================
--- branches/mathtex/lib/matplotlib/backends/backend_gdk.py 2009-07-26 17:53:54 UTC (rev 7295)
+++ branches/mathtex/lib/matplotlib/backends/backend_gdk.py 2009-07-27 12:30:35 UTC (rev 7296)
@@ -167,7 +167,7 @@
return
m = Mathtex(s, matplotlib.rcParams['mathtext.fontset'],
- prop.get_size_in_points(), self.dpi)
+ prop.get_size_in_points(), self.dpi, rcParams['mathtext.default'])
b = MathtexBackendImage()
m.render_to_backend(b)
@@ -318,7 +318,7 @@
return 0.0, 0.0, 0.0
else:
m = Mathtex(s, matplotlib.rcParams['mathtext.fontset'],
- prop.get_size_in_points(), self.dpi)
+ prop.get_size_in_points(), self.dpi, rcParams['mathtext.default'])
return m.width, m.height, m.depth
layout, inkRect, logicalRect = self._get_pango_layout(s, prop)
Modified: branches/mathtex/lib/matplotlib/backends/backend_pdf.py
===================================================================
--- branches/mathtex/lib/matplotlib/backends/backend_pdf.py 2009-07-26 17:53:54 UTC (rev 7295)
+++ branches/mathtex/lib/matplotlib/backends/backend_pdf.py 2009-07-27 12:30:35 UTC (rev 7296)
@@ -1351,7 +1351,8 @@
if not HAVE_MATHTEX:
return
- m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(), 72.0)
+ m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(),
+ 72.0, rcParams['mathtext.default'])
# Generate the dict of used characters
used_characters = {}
@@ -1668,7 +1669,7 @@
w, h, d = 0.0, 0.0, 0.0
else:
m = Mathtex(s, rcParams['mathtext.fontset'],
- prop.get_size_in_points(), 72.0)
+ prop.get_size_in_points(), 72.0, rcParams['mathtext.default'])
w, h, d = m.width, m.height, m.depth
elif rcParams['pdf.use14corefonts']:
Modified: branches/mathtex/lib/matplotlib/backends/backend_ps.py
===================================================================
--- branches/mathtex/lib/matplotlib/backends/backend_ps.py 2009-07-26 17:53:54 UTC (rev 7295)
+++ branches/mathtex/lib/matplotlib/backends/backend_ps.py 2009-07-27 12:30:35 UTC (rev 7296)
@@ -282,7 +282,8 @@
if ismath:
if HAVE_MATHTEX:
- m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(), 72.0)
+ m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(),
+ 72.0, rcParams['mathtext.default'])
return m.width, m.height, m.depth
else:
warnings.warn('matplotlib was compiled without mathtex support. ' +
@@ -750,7 +751,8 @@
if not HAVE_MATHTEX:
return
- m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(), 72.0)
+ m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(),
+ 72.0, rcParams['mathtext.default'])
# Generate the dict of used characters
used_characters = {}
Modified: branches/mathtex/lib/matplotlib/backends/backend_svg.py
===================================================================
--- branches/mathtex/lib/matplotlib/backends/backend_svg.py 2009-07-26 17:53:54 UTC (rev 7295)
+++ branches/mathtex/lib/matplotlib/backends/backend_svg.py 2009-07-27 12:30:35 UTC (rev 7296)
@@ -494,7 +494,8 @@
if not HAVE_MATHTEX:
return
- m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(), 72.0)
+ m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(),
+ 72.0, rcParams['mathtext.default'])
# Extract the glyphs and rects to render
svg_glyphs = [(info.font, info.fontsize, unichr(info.num),
@@ -600,8 +601,8 @@
def get_text_width_height_descent(self, s, prop, ismath):
if ismath:
if HAVE_MATHTEX:
- m = Mathtex(s, rcParams['mathtext.fontset'],
- prop.get_size_in_points(), 72.0)
+ m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(),
+ 72.0, rcParams['mathtext.default'])
return m.width, m.height, m.depth
else:
warnings.warn('matplotlib was compiled without mathtex support. ' +
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <evi...@us...> - 2009-07-26 17:54:02
|
Revision: 7295
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7295&view=rev
Author: evilguru
Date: 2009-07-26 17:53:54 +0000 (Sun, 26 Jul 2009)
Log Message:
-----------
Make mathtex an optional dependency. Warn when trying to render math when it is not available.
Modified Paths:
--------------
branches/mathtex/lib/matplotlib/backends/backend_agg.py
branches/mathtex/lib/matplotlib/backends/backend_cairo.py
branches/mathtex/lib/matplotlib/backends/backend_gdk.py
branches/mathtex/lib/matplotlib/backends/backend_macosx.py
branches/mathtex/lib/matplotlib/backends/backend_pdf.py
branches/mathtex/lib/matplotlib/backends/backend_ps.py
branches/mathtex/lib/matplotlib/backends/backend_svg.py
Modified: branches/mathtex/lib/matplotlib/backends/backend_agg.py
===================================================================
--- branches/mathtex/lib/matplotlib/backends/backend_agg.py 2009-07-26 00:06:34 UTC (rev 7294)
+++ branches/mathtex/lib/matplotlib/backends/backend_agg.py 2009-07-26 17:53:54 UTC (rev 7295)
@@ -21,6 +21,7 @@
* integrate screen dpi w/ ppi and text
"""
from __future__ import division
+import warnings
import numpy as npy
@@ -37,8 +38,12 @@
from _backend_agg import RendererAgg as _RendererAgg
from matplotlib import _png
-from mathtex.mathtex_main import Mathtex
-from mathtex.backends.backend_image import MathtexBackendImage
+try:
+ from mathtex.mathtex_main import Mathtex
+ from mathtex.backends.backend_image import MathtexBackendImage
+ HAVE_MATHTEX = True
+except ImportError:
+ HAVE_MATHTEX = False
backend_version = 'v2.2'
@@ -104,12 +109,13 @@
"""
if __debug__: verbose.report('RendererAgg.draw_mathtext',
'debug-annoying')
- m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(), self.dpi)
- b = MathtexBackendImage()
+ if HAVE_MATHTEX:
+ m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(), self.dpi)
+ b = MathtexBackendImage()
- m.render_to_backend(b)
+ m.render_to_backend(b)
- self._renderer.draw_text_image(b.image, int(x), int(y) + 1, angle, gc)
+ self._renderer.draw_text_image(b.image, int(x), int(y) + 1, angle, gc)
def draw_text(self, gc, x, y, s, prop, angle, ismath):
"""
@@ -153,8 +159,13 @@
return w, h, d
if ismath:
- m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(), self.dpi)
- return m.width, m.height, m.depth
+ if not HAVE_MATHTEX:
+ warnings.warn('matplotlib was compiled without mathtex support. ' +
+ 'Math will not be rendered.')
+ return 0.0, 0.0, 0.0
+ else:
+ m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(), self.dpi)
+ return m.width, m.height, m.depth
font = self._get_agg_font(prop)
font.set_text(s, 0.0, flags=LOAD_FORCE_AUTOHINT) # the width and height of unrotated string
w, h = font.get_width_height()
@@ -250,7 +261,7 @@
>>> x1, y1, x2, y2 = region.get_extents()
>>> renderer.restore_region(region, bbox=(x1+dx, y1, x2, y2),
xy=(x1-dx, y1))
-
+
"""
if bbox is not None or xy is not None:
if bbox is None:
Modified: branches/mathtex/lib/matplotlib/backends/backend_cairo.py
===================================================================
--- branches/mathtex/lib/matplotlib/backends/backend_cairo.py 2009-07-26 00:06:34 UTC (rev 7294)
+++ branches/mathtex/lib/matplotlib/backends/backend_cairo.py 2009-07-26 17:53:54 UTC (rev 7295)
@@ -47,8 +47,12 @@
from matplotlib.font_manager import ttfFontProperty
from matplotlib import rcParams
-from mathtex.mathtex_main import Mathtex
-from mathtex.backends.backend_cairo import MathtexBackendCairo
+try:
+ from mathtex.mathtex_main import Mathtex
+ from mathtex.backends.backend_cairo import MathtexBackendCairo
+ HAVE_MATHTEX = True
+except ImportError:
+ HAVE_MATHTEX = False
_debug = False
#_debug = True
@@ -202,6 +206,7 @@
def _draw_mathtext(self, gc, x, y, s, prop, angle):
if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name())
+ if not HAVE_MATHTEX: return
ctx = gc.ctx
@@ -234,8 +239,13 @@
def get_text_width_height_descent(self, s, prop, ismath):
if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name())
if ismath:
- m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(), self.dpi)
- return m.width, m.height, m.depth
+ if HAVE_MATHTEX:
+ m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(), self.dpi)
+ return m.width, m.height, m.depth
+ else:
+ warnings.warn('matplotlib was compiled without mathtex support. ' +
+ 'Math will not be rendered.')
+ return 0.0, 0.0, 0.0
ctx = self.text_ctx
ctx.save()
Modified: branches/mathtex/lib/matplotlib/backends/backend_gdk.py
===================================================================
--- branches/mathtex/lib/matplotlib/backends/backend_gdk.py 2009-07-26 00:06:34 UTC (rev 7294)
+++ branches/mathtex/lib/matplotlib/backends/backend_gdk.py 2009-07-26 17:53:54 UTC (rev 7295)
@@ -27,8 +27,12 @@
from matplotlib.transforms import Affine2D
from matplotlib.backends._backend_gdk import pixbuf_get_pixels_array
-from mathtex.mathtex_main import Mathtex
-from mathtex.backends.backend_image import MathtexBackendImage
+try:
+ from mathtex.mathtex_main import Mathtex
+ from mathtex.backends.backend_image import MathtexBackendImage
+ HAVE_MATHTEX = True
+except ImportError:
+ HAVE_MATHTEX = False
backend_version = "%d.%d.%d" % gtk.pygtk_version
_debug = False
@@ -159,6 +163,9 @@
def _draw_mathtext(self, gc, x, y, s, prop, angle):
+ if not HAVE_MATHTEX:
+ return
+
m = Mathtex(s, matplotlib.rcParams['mathtext.fontset'],
prop.get_size_in_points(), self.dpi)
b = MathtexBackendImage()
@@ -305,9 +312,14 @@
def get_text_width_height_descent(self, s, prop, ismath):
if ismath:
- m = Mathtex(s, matplotlib.rcParams['mathtext.fontset'],
- prop.get_size_in_points(), self.dpi)
- return m.width, m.height, m.depth
+ if not HAVE_MATHTEX:
+ warnings.warn('matplotlib was compiled without mathtex support. ' +
+ 'Math will not be rendered.')
+ return 0.0, 0.0, 0.0
+ else:
+ m = Mathtex(s, matplotlib.rcParams['mathtext.fontset'],
+ prop.get_size_in_points(), self.dpi)
+ return m.width, m.height, m.depth
layout, inkRect, logicalRect = self._get_pango_layout(s, prop)
l, b, w, h = inkRect
Modified: branches/mathtex/lib/matplotlib/backends/backend_macosx.py
===================================================================
--- branches/mathtex/lib/matplotlib/backends/backend_macosx.py 2009-07-26 00:06:34 UTC (rev 7294)
+++ branches/mathtex/lib/matplotlib/backends/backend_macosx.py 2009-07-26 17:53:54 UTC (rev 7295)
@@ -11,8 +11,12 @@
from matplotlib.path import Path
from matplotlib.colors import colorConverter
-from mathtex.mathtex_main import Mathtex
-from mathtex.backends.backend_image import MathtexBackendImage
+try:
+ from mathtex.mathtex_main import Mathtex
+ from mathtex.backends.backend_image import MathtexBackendImage
+ HAVE_MATHTEX = True
+except ImportError:
+ HAVE_MATHTEX = False
from matplotlib.widgets import SubplotTool
@@ -90,6 +94,9 @@
gc.draw_mathtext(x, y, angle, Z)
def _draw_mathtext(self, gc, x, y, s, prop, angle):
+ if not HAVE_MATHTEX:
+ return
+
m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(), self.dpi)
b = MathtexBackendImage()
m.render_to_backend(b)
@@ -116,9 +123,14 @@
renderer=self)
return w, h, d
if ismath:
- m = Mathtex(s, rcParams['mathtext.fontset'],
- prop.get_size_in_points(), self.dpi)
- return m.width, m.height, m.depth
+ if HAVE_MATHTEX:
+ m = Mathtex(s, rcParams['mathtext.fontset'],
+ prop.get_size_in_points(), self.dpi)
+ return m.width, m.height, m.depth
+ else:
+ warnings.warn('matplotlib was compiled without mathtex support. ' +
+ 'Math will not be rendered.')
+ return 0.0, 0.0, 0.0
family = prop.get_family()
weight = prop.get_weight()
style = prop.get_style()
Modified: branches/mathtex/lib/matplotlib/backends/backend_pdf.py
===================================================================
--- branches/mathtex/lib/matplotlib/backends/backend_pdf.py 2009-07-26 00:06:34 UTC (rev 7294)
+++ branches/mathtex/lib/matplotlib/backends/backend_pdf.py 2009-07-26 17:53:54 UTC (rev 7295)
@@ -1,7 +1,7 @@
# -*- coding: iso-8859-1 -*-
"""
A PDF matplotlib backend (not yet complete)
-Author: Jouni K Sepp\xE4nen <jk...@ik...>
+Author: Jouni K Sepp�nen <jk...@ik...>
"""
from __future__ import division
@@ -42,7 +42,11 @@
from matplotlib.path import Path
from matplotlib import ttconv
-from mathtex.mathtex_main import Mathtex
+try:
+ from mathtex.mathtex_main import Mathtex
+ HAVE_MATHTEX = True
+except ImportError:
+ HAVE_MATHTEX = False
# Overview
#
@@ -1344,6 +1348,9 @@
def draw_mathtext(self, gc, x, y, s, prop, angle):
# TODO: fix positioning and encoding
+ if not HAVE_MATHTEX:
+ return
+
m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(), 72.0)
# Generate the dict of used characters
@@ -1654,9 +1661,15 @@
return w, h, d
if ismath:
- m = Mathtex(s, rcParams['mathtext.fontset'],
- prop.get_size_in_points(), 72.0)
- w, h, d = m.width, m.height, m.depth
+ # Ensure mathtex is available
+ if not HAVE_MATHTEX:
+ warnings.warn('matplotlib was compiled without mathtex support. ' +
+ 'Math will not be rendered.')
+ w, h, d = 0.0, 0.0, 0.0
+ else:
+ m = Mathtex(s, rcParams['mathtext.fontset'],
+ prop.get_size_in_points(), 72.0)
+ w, h, d = m.width, m.height, m.depth
elif rcParams['pdf.use14corefonts']:
font = self._get_font_afm(prop)
Modified: branches/mathtex/lib/matplotlib/backends/backend_ps.py
===================================================================
--- branches/mathtex/lib/matplotlib/backends/backend_ps.py 2009-07-26 00:06:34 UTC (rev 7294)
+++ branches/mathtex/lib/matplotlib/backends/backend_ps.py 2009-07-26 17:53:54 UTC (rev 7295)
@@ -3,7 +3,7 @@
"""
from __future__ import division
-import glob, math, os, shutil, sys, time
+import glob, math, os, shutil, sys, time, warnings
def _fn_name(): return sys._getframe(1).f_code.co_name
try:
@@ -34,7 +34,11 @@
from matplotlib.backends.backend_mixed import MixedModeRenderer
-from mathtex.mathtex_main import Mathtex
+try:
+ from mathtex.mathtex_main import Mathtex
+ HAVE_MATHTEX = True
+except ImportError:
+ HAVE_MATHTEX = False
import numpy as npy
import binascii
@@ -277,8 +281,13 @@
return w, h, d
if ismath:
- m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(), 72.0)
- return m.width, m.height, m.depth
+ if HAVE_MATHTEX:
+ m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(), 72.0)
+ return m.width, m.height, m.depth
+ else:
+ warnings.warn('matplotlib was compiled without mathtex support. ' +
+ 'Math will not be rendered.')
+ return 0.0, 0.0, 0.0
if rcParams['ps.useafm']:
if ismath: s = s[1:-1]
@@ -738,6 +747,8 @@
"""
if debugPS:
self._pswriter.write("% mathtext\n")
+ if not HAVE_MATHTEX:
+ return
m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(), 72.0)
Modified: branches/mathtex/lib/matplotlib/backends/backend_svg.py
===================================================================
--- branches/mathtex/lib/matplotlib/backends/backend_svg.py 2009-07-26 00:06:34 UTC (rev 7294)
+++ branches/mathtex/lib/matplotlib/backends/backend_svg.py 2009-07-26 17:53:54 UTC (rev 7295)
@@ -1,6 +1,6 @@
from __future__ import division
-import os, codecs, base64, tempfile, urllib, gzip, cStringIO
+import os, codecs, base64, tempfile, urllib, gzip, cStringIO, warnings
try:
from hashlib import md5
@@ -20,7 +20,11 @@
from matplotlib.transforms import Affine2D
from matplotlib import _png
-from mathtex.mathtex_main import Mathtex
+try:
+ from mathtex.mathtex_main import Mathtex
+ HAVE_MATHTEX = True
+except ImportError:
+ HAVE_MATHTEX = False
from xml.sax.saxutils import escape as escape_xml_text
@@ -487,6 +491,9 @@
"""
Draw math text using mathtex
"""
+ if not HAVE_MATHTEX:
+ return
+
m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(), 72.0)
# Extract the glyphs and rects to render
@@ -592,9 +599,14 @@
def get_text_width_height_descent(self, s, prop, ismath):
if ismath:
- m = Mathtex(s, rcParams['mathtext.fontset'],
- prop.get_size_in_points(), 72.0)
- return m.width, m.height, m.depth
+ if HAVE_MATHTEX:
+ m = Mathtex(s, rcParams['mathtext.fontset'],
+ prop.get_size_in_points(), 72.0)
+ return m.width, m.height, m.depth
+ else:
+ warnings.warn('matplotlib was compiled without mathtex support. ' +
+ 'Math will not be rendered.')
+ return 0.0, 0.0, 0.0
font = self._get_font(prop)
font.set_text(s, 0.0, flags=LOAD_NO_HINTING)
w, h = font.get_width_height()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2009-07-26 00:06:45
|
Revision: 7294
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7294&view=rev
Author: efiring
Date: 2009-07-26 00:06:34 +0000 (Sun, 26 Jul 2009)
Log Message:
-----------
Plot accepts scalar coordinates, e.g. plot(1, 2, 'r*')
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/axes.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2009-07-24 02:09:20 UTC (rev 7293)
+++ trunk/matplotlib/CHANGELOG 2009-07-26 00:06:34 UTC (rev 7294)
@@ -1,3 +1,5 @@
+2009-07-25 Allow "plot(1, 2, 'r*')" to work. - EF
+
2009-07-22 Added an 'interp' keyword to griddata so the faster linear
interpolation method can be chosen. Default is 'nn', so
default behavior (using natural neighbor method) is unchanged (JSW)
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2009-07-24 02:09:20 UTC (rev 7293)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2009-07-26 00:06:34 UTC (rev 7294)
@@ -223,11 +223,11 @@
if by:
y = self.axes.convert_yunits(y)
- x = ma.asarray(x)
- y = ma.asarray(y)
- if len(x.shape) == 1:
+ x = ma.asarray(np.atleast_1d(x))
+ y = ma.asarray(np.atleast_1d(y))
+ if x.ndim == 1:
x = x[:,np.newaxis]
- if len(y.shape) == 1:
+ if y.ndim == 1:
y = y[:,np.newaxis]
nrx, ncx = x.shape
nry, ncy = y.shape
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2009-07-24 02:09:29
|
Revision: 7293
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7293&view=rev
Author: jswhit
Date: 2009-07-24 02:09:20 +0000 (Fri, 24 Jul 2009)
Log Message:
-----------
merge from scikits.delaunay trunk
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/delaunay/VoronoiDiagramGenerator.cpp
trunk/matplotlib/lib/matplotlib/delaunay/__init__.py
trunk/matplotlib/lib/matplotlib/delaunay/_delaunay.cpp
trunk/matplotlib/lib/matplotlib/delaunay/triangulate.py
Modified: trunk/matplotlib/lib/matplotlib/delaunay/VoronoiDiagramGenerator.cpp
===================================================================
--- trunk/matplotlib/lib/matplotlib/delaunay/VoronoiDiagramGenerator.cpp 2009-07-23 22:23:04 UTC (rev 7292)
+++ trunk/matplotlib/lib/matplotlib/delaunay/VoronoiDiagramGenerator.cpp 2009-07-24 02:09:20 UTC (rev 7293)
@@ -12,9 +12,9 @@
* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
*/
-/*
- * This code was originally written by Stephan Fortune in C code. Shane O'Sullivan,
- * have since modified it, encapsulating it in a C++ class and, fixing memory leaks and
+/*
+ * This code was originally written by Stephan Fortune in C code. Shane O'Sullivan,
+ * have since modified it, encapsulating it in a C++ class and, fixing memory leaks and
* adding accessors to the Voronoi Edges.
* Permission to use, copy, modify, and distribute this software for any
* purpose without fee is hereby granted, provided that this entire notice
@@ -26,7 +26,7 @@
* REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
*/
-
+
/*
* Subsequently, Robert Kern modified it to yield Python objects.
* Copyright 2005 Robert Kern <rob...@gm...>
@@ -78,9 +78,9 @@
nsites=numPoints;
plot = 0;
- triangulate = 0;
+ triangulate = 0;
debug = 1;
- sorted = 0;
+ sorted = 0;
freeinit(&sfl, sizeof (Site));
sites = (struct Site *) myalloc(nsites*sizeof( *sites));
@@ -112,9 +112,9 @@
//printf("\n%f %f\n",xValues[i],yValues[i]);
}
-
+
qsort(sites, nsites, sizeof (*sites), scomp);
-
+
siteidx = 0;
geominit();
double temp = 0;
@@ -134,9 +134,9 @@
borderMinY = minY;
borderMaxX = maxX;
borderMaxY = maxY;
+
+ siteidx = 0;
- siteidx = 0;
-
voronoi(triangulate);
return true;
@@ -191,25 +191,25 @@
struct Halfedge * VoronoiDiagramGenerator::ELgethash(int b)
{
struct Halfedge *he;
-
- if(b<0 || b>=ELhashsize)
+
+ if(b<0 || b>=ELhashsize)
return((struct Halfedge *) NULL);
- he = ELhash[b];
- if (he == (struct Halfedge *) NULL || he->ELedge != (struct Edge *) DELETED )
+ he = ELhash[b];
+ if (he == (struct Halfedge *) NULL || he->ELedge != (struct Edge *) DELETED )
return (he);
-
+
/* Hash table points to deleted half edge. Patch as necessary. */
ELhash[b] = (struct Halfedge *) NULL;
- if ((he -> ELrefcnt -= 1) == 0)
+ if ((he -> ELrefcnt -= 1) == 0)
makefree((Freenode*)he, &hfl);
return ((struct Halfedge *) NULL);
-}
+}
struct Halfedge * VoronoiDiagramGenerator::ELleftbnd(struct Point *p)
{
int i, bucket;
struct Halfedge *he;
-
+
/* Use hash table to get close to desired halfedge */
bucket = (int)((p->x - xmin)/deltax * ELhashsize); //use the hash function to find the place in the hash map that this HalfEdge should be
@@ -218,12 +218,12 @@
he = ELgethash(bucket);
if(he == (struct Halfedge *) NULL) //if the HE isn't found, search backwards and forwards in the hash map for the first non-null entry
- {
+ {
for(i=1; 1 ; i += 1)
- {
- if ((he=ELgethash(bucket-i)) != (struct Halfedge *) NULL)
+ {
+ if ((he=ELgethash(bucket-i)) != (struct Halfedge *) NULL)
break;
- if ((he=ELgethash(bucket+i)) != (struct Halfedge *) NULL)
+ if ((he=ELgethash(bucket+i)) != (struct Halfedge *) NULL)
break;
};
totalsearch += i;
@@ -232,22 +232,22 @@
/* Now search linear list of halfedges for the correct one */
if (he==ELleftend || (he != ELrightend && right_of(he,p)))
{
- do
+ do
{
he = he -> ELright;
} while (he!=ELrightend && right_of(he,p)); //keep going right on the list until either the end is reached, or you find the 1st edge which the point
he = he -> ELleft; //isn't to the right of
}
else //if the point is to the left of the HalfEdge, then search left for the HE just to the left of the point
- do
+ do
{
he = he -> ELleft;
} while (he!=ELleftend && !right_of(he,p));
-
+
/* Update hash table and reference counts */
if(bucket > 0 && bucket <ELhashsize-1)
- {
- if(ELhash[bucket] != (struct Halfedge *) NULL)
+ {
+ if(ELhash[bucket] != (struct Halfedge *) NULL)
{
ELhash[bucket] -> ELrefcnt -= 1;
}
@@ -281,9 +281,9 @@
struct Site * VoronoiDiagramGenerator::leftreg(struct Halfedge *he)
{
- if(he -> ELedge == (struct Edge *)NULL)
+ if(he -> ELedge == (struct Edge *)NULL)
return(bottomsite);
- return( he -> ELpm == le ?
+ return( he -> ELpm == le ?
he -> ELedge -> reg[le] : he -> ELedge -> reg[re]);
}
@@ -297,7 +297,7 @@
}
void VoronoiDiagramGenerator::geominit()
-{
+{
double sn;
freeinit(&efl, sizeof(Edge));
@@ -313,17 +313,17 @@
struct Edge * VoronoiDiagramGenerator::bisect(struct Site *s1, struct Site *s2)
{
double dx,dy,adx,ady;
- struct Edge *newedge;
+ struct Edge *newedge;
newedge = (struct Edge *) getfree(&efl);
-
+
newedge -> reg[0] = s1; //store the sites that this edge is bisecting
newedge -> reg[1] = s2;
- ref(s1);
+ ref(s1);
ref(s2);
newedge -> ep[0] = (struct Site *) NULL; //to begin with, there are no endpoints on the bisector - it goes to infinity
newedge -> ep[1] = (struct Site *) NULL;
-
+
dx = s2->coord.x - s1->coord.x; //get the difference in x dist between the sites
dy = s2->coord.y - s1->coord.y;
adx = dx>0 ? dx : -dx; //make sure that the difference in positive
@@ -331,18 +331,18 @@
newedge -> c = (double)(s1->coord.x * dx + s1->coord.y * dy + (dx*dx + dy*dy)*0.5);//get the slope of the line
if (adx>ady)
- {
+ {
newedge -> a = 1.0; newedge -> b = dy/dx; newedge -> c /= dx;//set formula of line, with x fixed to 1
}
else
- {
+ {
newedge -> b = 1.0; newedge -> a = dx/dy; newedge -> c /= dy;//set formula of line, with y fixed to 1
};
-
+
newedge -> edgenbr = nedges;
//printf("\nbisect(%d) ((%f,%f) and (%f,%f)",nedges,s1->coord.x,s1->coord.y,s2->coord.x,s2->coord.y);
-
+
nedges += 1;
return(newedge);
}
@@ -355,40 +355,40 @@
double d, xint, yint;
int right_of_site;
struct Site *v;
-
+
e1 = el1 -> ELedge;
e2 = el2 -> ELedge;
- if(e1 == (struct Edge*)NULL || e2 == (struct Edge*)NULL)
+ if(e1 == (struct Edge*)NULL || e2 == (struct Edge*)NULL)
return ((struct Site *) NULL);
//if the two edges bisect the same parent, return null
- if (e1->reg[1] == e2->reg[1])
+ if (e1->reg[1] == e2->reg[1])
return ((struct Site *) NULL);
-
+
d = e1->a * e2->b - e1->b * e2->a;
- if (-1.0e-10<d && d<1.0e-10)
+ if (-1.0e-10<d && d<1.0e-10)
return ((struct Site *) NULL);
-
+
xint = (e1->c*e2->b - e2->c*e1->b)/d;
yint = (e2->c*e1->a - e1->c*e2->a)/d;
-
+
if( (e1->reg[1]->coord.y < e2->reg[1]->coord.y) ||
(e1->reg[1]->coord.y == e2->reg[1]->coord.y &&
e1->reg[1]->coord.x < e2->reg[1]->coord.x) )
- {
- el = el1;
+ {
+ el = el1;
e = e1;
}
else
- {
- el = el2;
+ {
+ el = el2;
e = e2;
};
-
+
right_of_site = xint >= e -> reg[1] -> coord.x;
- if ((right_of_site && el -> ELpm == le) || (!right_of_site && el -> ELpm == re))
+ if ((right_of_site && el -> ELpm == le) || (!right_of_site && el -> ELpm == re))
return ((struct Site *) NULL);
-
+
//create a new site at the point of intersection - this is a new vector event waiting to happen
v = (struct Site *) getfree(&sfl);
v -> refcnt = 0;
@@ -404,22 +404,22 @@
struct Site *topsite;
int right_of_site, above, fast;
double dxp, dyp, dxs, t1, t2, t3, yl;
-
+
e = el -> ELedge;
topsite = e -> reg[1];
right_of_site = p -> x > topsite -> coord.x;
if(right_of_site && el -> ELpm == le) return(1);
if(!right_of_site && el -> ELpm == re) return (0);
-
+
if (e->a == 1.0)
{ dyp = p->y - topsite->coord.y;
dxp = p->x - topsite->coord.x;
fast = 0;
if ((!right_of_site & (e->b<0.0)) | (right_of_site & (e->b>=0.0)) )
- { above = dyp>= e->b*dxp;
+ { above = dyp>= e->b*dxp;
fast = above;
}
- else
+ else
{ above = p->x + p->y*e->b > e-> c;
if(e->b<0.0) above = !above;
if (!above) fast = 1;
@@ -446,7 +446,7 @@
{
e -> ep[lr] = s;
ref(s);
- if(e -> ep[re-lr]== (struct Site *) NULL)
+ if(e -> ep[re-lr]== (struct Site *) NULL)
return;
clip_line(e);
@@ -477,7 +477,7 @@
void VoronoiDiagramGenerator::deref(struct Site *v)
{
v -> refcnt -= 1;
- if (v -> refcnt == 0 )
+ if (v -> refcnt == 0 )
makefree((Freenode*)v, &sfl);
}
@@ -490,7 +490,7 @@
void VoronoiDiagramGenerator::PQinsert(struct Halfedge *he,struct Site * v, double offset)
{
struct Halfedge *last, *next;
-
+
he -> vertex = v;
ref(v);
he -> ystar = (double)(v -> coord.y + offset);
@@ -498,23 +498,23 @@
while ((next = last -> PQnext) != (struct Halfedge *) NULL &&
(he -> ystar > next -> ystar ||
(he -> ystar == next -> ystar && v -> coord.x > next->vertex->coord.x)))
- {
+ {
last = next;
};
- he -> PQnext = last -> PQnext;
+ he -> PQnext = last -> PQnext;
last -> PQnext = he;
PQcount += 1;
}
-//remove the HalfEdge from the list of vertices
+//remove the HalfEdge from the list of vertices
void VoronoiDiagramGenerator::PQdelete(struct Halfedge *he)
{
struct Halfedge *last;
-
+
if(he -> vertex != (struct Site *) NULL)
- {
+ {
last = &PQhash[PQbucket(he)];
- while (last -> PQnext != he)
+ while (last -> PQnext != he)
last = last -> PQnext;
last -> PQnext = he -> PQnext;
@@ -527,7 +527,7 @@
int VoronoiDiagramGenerator::PQbucket(struct Halfedge *he)
{
int bucket;
-
+
bucket = (int)((he->ystar - ymin)/deltay * PQhashsize);
if (bucket<0) bucket = 0;
if (bucket>=PQhashsize) bucket = PQhashsize-1 ;
@@ -546,7 +546,7 @@
struct Point VoronoiDiagramGenerator::PQ_min()
{
struct Point answer;
-
+
while(PQhash[PQmin].PQnext == (struct Halfedge *)NULL) {PQmin += 1;};
answer.x = PQhash[PQmin].PQnext -> vertex -> coord.x;
answer.y = PQhash[PQmin].PQnext -> ystar;
@@ -556,7 +556,7 @@
struct Halfedge * VoronoiDiagramGenerator::PQextractmin()
{
struct Halfedge *curr;
-
+
curr = PQhash[PQmin].PQnext;
PQhash[PQmin].PQnext = curr -> PQnext;
PQcount -= 1;
@@ -566,8 +566,8 @@
bool VoronoiDiagramGenerator::PQinitialize()
{
- int i;
-
+ int i;
+
PQcount = 0;
PQmin = 0;
PQhashsize = 4 * sqrt_nsites;
@@ -590,23 +590,23 @@
char * VoronoiDiagramGenerator::getfree(struct Freelist *fl)
{
- int i;
+ int i;
struct Freenode *t;
if(fl->head == (struct Freenode *) NULL)
- {
+ {
t = (struct Freenode *) myalloc(sqrt_nsites * fl->nodesize);
if(t == 0)
return 0;
-
+
currentMemoryBlock->next = new FreeNodeArrayList;
currentMemoryBlock = currentMemoryBlock->next;
currentMemoryBlock->memory = t;
currentMemoryBlock->next = 0;
- for(i=0; i<sqrt_nsites; i+=1)
- makefree((struct Freenode *)((char *)t+i*fl->nodesize), fl);
+ for(i=0; i<sqrt_nsites; i+=1)
+ makefree((struct Freenode *)((char *)t+i*fl->nodesize), fl);
};
t = fl -> head;
fl -> head = (fl -> head) -> nextfree;
@@ -725,7 +725,7 @@
char * VoronoiDiagramGenerator::myalloc(unsigned n)
{
- char *t=0;
+ char *t=0;
t=(char*)malloc(n);
total_alloc += n;
return(t);
@@ -736,7 +736,7 @@
/* #include <plot.h> */
void VoronoiDiagramGenerator::openpl(){}
void VoronoiDiagramGenerator::line(double x1, double y1, double x2, double y2)
-{
+{
pushGraphEdge(x1,y1,x2,y2);
}
@@ -747,20 +747,20 @@
void VoronoiDiagramGenerator::out_bisector(struct Edge *e)
{
+
-
}
void VoronoiDiagramGenerator::out_ep(struct Edge *e)
{
-
-
+
+
}
void VoronoiDiagramGenerator::out_vertex(struct Site *v)
{
-
+
}
@@ -768,13 +768,13 @@
{
if(!triangulate & plot & !debug)
circle (s->coord.x, s->coord.y, cradius);
-
+
}
void VoronoiDiagramGenerator::out_triple(struct Site *s1, struct Site *s2,struct Site * s3)
{
-
+
}
@@ -782,7 +782,7 @@
void VoronoiDiagramGenerator::plotinit()
{
// double dx,dy,d;
-//
+//
// dy = ymax - ymin;
// dx = xmax - xmin;
// d = (double)(( dx > dy ? dx : dy) * 1.1);
@@ -808,7 +808,7 @@
// y1 = e->reg[0]->coord.y;
// y2 = e->reg[1]->coord.y;
//
-// //if the distance between the two points this line was created from is less than
+// //if the distance between the two points this line was created from is less than
// //the square root of 2, then ignore it
// if(sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))) < minDistanceBetweenSites)
// {
@@ -820,16 +820,16 @@
// pymax = borderMaxY;
//
// if(e -> a == 1.0 && e ->b >= 0.0)
-// {
+// {
// s1 = e -> ep[1];
// s2 = e -> ep[0];
// }
-// else
+// else
// {
// s1 = e -> ep[0];
// s2 = e -> ep[1];
// };
-//
+//
// if(e -> a == 1.0)
// {
// y1 = pymin;
@@ -837,7 +837,7 @@
// {
// y1 = s1->coord.y;
// }
-// if(y1>pymax)
+// if(y1>pymax)
// {
// // printf("\nClipped (1) y1 = %f to %f",y1,pymax);
// y1 = pymax;
@@ -845,17 +845,17 @@
// }
// x1 = e -> c - e -> b * y1;
// y2 = pymax;
-// if (s2!=(struct Site *)NULL && s2->coord.y < pymax)
+// if (s2!=(struct Site *)NULL && s2->coord.y < pymax)
// y2 = s2->coord.y;
//
-// if(y2<pymin)
+// if(y2<pymin)
// {
// //printf("\nClipped (2) y2 = %f to %f",y2,pymin);
// y2 = pymin;
// //return;
// }
// x2 = (e->c) - (e->b) * y2;
-// if (((x1> pxmax) & (x2>pxmax)) | ((x1<pxmin)&(x2<pxmin)))
+// if (((x1> pxmax) & (x2>pxmax)) | ((x1<pxmin)&(x2<pxmin)))
// {
// //printf("\nClipLine jumping out(3), x1 = %f, pxmin = %f, pxmax = %f",x1,pxmin,pxmax);
// return;
@@ -872,9 +872,9 @@
// else
// {
// x1 = pxmin;
-// if (s1!=(struct Site *)NULL && s1->coord.x > pxmin)
+// if (s1!=(struct Site *)NULL && s1->coord.x > pxmin)
// x1 = s1->coord.x;
-// if(x1>pxmax)
+// if(x1>pxmax)
// {
// //printf("\nClipped (3) x1 = %f to %f",x1,pxmin);
// //return;
@@ -882,16 +882,16 @@
// }
// y1 = e -> c - e -> a * x1;
// x2 = pxmax;
-// if (s2!=(struct Site *)NULL && s2->coord.x < pxmax)
+// if (s2!=(struct Site *)NULL && s2->coord.x < pxmax)
// x2 = s2->coord.x;
-// if(x2<pxmin)
+// if(x2<pxmin)
// {
// //printf("\nClipped (4) x2 = %f to %f",x2,pxmin);
// //return;
// x2 = pxmin;
// }
// y2 = e -> c - e -> a * x2;
-// if (((y1> pymax) & (y2>pymax)) | ((y1<pymin)&(y2<pymin)))
+// if (((y1> pymax) & (y2>pymax)) | ((y1<pymin)&(y2<pymin)))
// {
// //printf("\nClipLine jumping out(6), y1 = %f, pymin = %f, pymax = %f",y2,pymin,pymax);
// return;
@@ -905,7 +905,7 @@
// if(y2<pymin)
// { y2 = pymin; x2 = (e -> c - y2)/e -> a;};
// };
-//
+//
// //printf("\nPushing line (%f,%f,%f,%f)",x1,y1,x2,y2);
// line(x1,y1,x2,y2);
}
@@ -924,7 +924,7 @@
int pm;
struct Halfedge *lbnd, *rbnd, *llbnd, *rrbnd, *bisector;
struct Edge *e;
-
+
PQinitialize();
bottomsite = nextone();
out_site(bottomsite);
@@ -932,16 +932,16 @@
if(!retval)
return false;
-
+
newsite = nextone();
while(1)
{
- if(!PQempty())
+ if(!PQempty())
newintstar = PQ_min();
-
+
//if the lowest site has a smaller y value than the lowest vector intersection, process the site
- //otherwise process the vector intersection
+ //otherwise process the vector intersection
if (newsite != (struct Site *)NULL && (PQempty() || newsite -> coord.y < newintstar.y
|| (newsite->coord.y == newintstar.y && newsite->coord.x < newintstar.x)))
@@ -950,31 +950,31 @@
lbnd = ELleftbnd(&(newsite->coord)); //get the first HalfEdge to the LEFT of the new site
rbnd = ELright(lbnd); //get the first HalfEdge to the RIGHT of the new site
bot = rightreg(lbnd); //if this halfedge has no edge, , bot = bottom site (whatever that is)
- e = bisect(bot, newsite); //create a new edge that bisects
- bisector = HEcreate(e, le); //create a new HalfEdge, setting its ELpm field to 0
- ELinsert(lbnd, bisector); //insert this new bisector edge between the left and right vectors in a linked list
+ e = bisect(bot, newsite); //create a new edge that bisects
+ bisector = HEcreate(e, le); //create a new HalfEdge, setting its ELpm field to 0
+ ELinsert(lbnd, bisector); //insert this new bisector edge between the left and right vectors in a linked list
if ((p = intersect(lbnd, bisector)) != (struct Site *) NULL) //if the new bisector intersects with the left edge, remove the left edge's vertex, and put in the new one
- {
+ {
PQdelete(lbnd);
PQinsert(lbnd, p, dist(p,newsite));
};
- lbnd = bisector;
+ lbnd = bisector;
bisector = HEcreate(e, re); //create a new HalfEdge, setting its ELpm field to 1
ELinsert(lbnd, bisector); //insert the new HE to the right of the original bisector earlier in the IF stmt
if ((p = intersect(bisector, rbnd)) != (struct Site *) NULL) //if this new bisector intersects with the
- {
+ {
PQinsert(bisector, p, dist(p,newsite)); //push the HE into the ordered linked list of vertices
};
- newsite = nextone();
+ newsite = nextone();
}
- else if (!PQempty()) /* intersection is smallest - this is a vector event */
- {
- lbnd = PQextractmin(); //pop the HalfEdge with the lowest vector off the ordered list of vectors
+ else if (!PQempty()) /* intersection is smallest - this is a vector event */
+ {
+ lbnd = PQextractmin(); //pop the HalfEdge with the lowest vector off the ordered list of vectors
llbnd = ELleft(lbnd); //get the HalfEdge to the left of the above HE
rbnd = ELright(lbnd); //get the HalfEdge to the right of the above HE
- rrbnd = ELright(rbnd); //get the HalfEdge to the right of the HE to the right of the lowest HE
+ rrbnd = ELright(rbnd); //get the HalfEdge to the right of the HE to the right of the lowest HE
bot = leftreg(lbnd); //get the Site to the left of the left HE which it bisects
top = rightreg(rbnd); //get the Site to the right of the right HE which it bisects
@@ -984,16 +984,16 @@
makevertex(v); //set the vertex number - couldn't do this earlier since we didn't know when it would be processed
endpoint(lbnd->ELedge,lbnd->ELpm,v); //set the endpoint of the left HalfEdge to be this vector
endpoint(rbnd->ELedge,rbnd->ELpm,v); //set the endpoint of the right HalfEdge to be this vector
- ELdelete(lbnd); //mark the lowest HE for deletion - can't delete yet because there might be pointers to it in Hash Map
+ ELdelete(lbnd); //mark the lowest HE for deletion - can't delete yet because there might be pointers to it in Hash Map
PQdelete(rbnd); //remove all vertex events to do with the right HE
- ELdelete(rbnd); //mark the right HE for deletion - can't delete yet because there might be pointers to it in Hash Map
+ ELdelete(rbnd); //mark the right HE for deletion - can't delete yet because there might be pointers to it in Hash Map
pm = le; //set the pm variable to zero
-
+
if (bot->coord.y > top->coord.y) //if the site to the left of the event is higher than the Site
{ //to the right of it, then swap them and set the 'pm' variable to 1
- temp = bot;
- bot = top;
- top = temp;
+ temp = bot;
+ bot = top;
+ top = temp;
pm = re;
}
e = bisect(bot, top); //create an Edge (or line) that is between the two Sites. This creates
@@ -1005,27 +1005,27 @@
//Site, then this endpoint is put in position 0; otherwise in pos 1
deref(v); //delete the vector 'v'
- //if left HE and the new bisector don't intersect, then delete the left HE, and reinsert it
+ //if left HE and the new bisector don't intersect, then delete the left HE, and reinsert it
if((p = intersect(llbnd, bisector)) != (struct Site *) NULL)
- {
+ {
PQdelete(llbnd);
PQinsert(llbnd, p, dist(p,bot));
};
- //if right HE and the new bisector don't intersect, then reinsert it
+ //if right HE and the new bisector don't intersect, then reinsert it
if ((p = intersect(bisector, rrbnd)) != (struct Site *) NULL)
- {
+ {
PQinsert(bisector, p, dist(p,bot));
};
}
else break;
};
+
-
for(lbnd=ELright(ELleftend); lbnd != ELrightend; lbnd=ELright(lbnd))
- {
+ {
e = lbnd -> ELedge;
clip_line(e);
@@ -1035,7 +1035,7 @@
cleanup();
return true;
-
+
}
@@ -1054,16 +1054,16 @@
{
struct Site *s;
if(siteidx < nsites)
- {
+ {
s = &sites[siteidx];
siteidx += 1;
return(s);
}
- else
+ else
return( (struct Site *)NULL);
}
-bool VoronoiDiagramGenerator::getNextDelaunay(int& ep0, double& ep0x, double& ep0y,
+bool VoronoiDiagramGenerator::getNextDelaunay(int& ep0, double& ep0x, double& ep0y,
int& ep1, double& ep1x, double& ep1y,
int& reg0, int& reg1)
{
@@ -1080,7 +1080,7 @@
reg1 = iterEdgeList->reg1nbr;
iterEdgeList = iterEdgeList->next;
-
+
return true;
}
Modified: trunk/matplotlib/lib/matplotlib/delaunay/__init__.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/delaunay/__init__.py 2009-07-23 22:23:04 UTC (rev 7292)
+++ trunk/matplotlib/lib/matplotlib/delaunay/__init__.py 2009-07-24 02:09:20 UTC (rev 7293)
@@ -8,4 +8,4 @@
from matplotlib._delaunay import delaunay
from triangulate import *
from interpolate import *
-__version__ = "0.1"
+__version__ = "0.2"
Modified: trunk/matplotlib/lib/matplotlib/delaunay/_delaunay.cpp
===================================================================
--- trunk/matplotlib/lib/matplotlib/delaunay/_delaunay.cpp 2009-07-23 22:23:04 UTC (rev 7292)
+++ trunk/matplotlib/lib/matplotlib/delaunay/_delaunay.cpp 2009-07-24 02:09:20 UTC (rev 7293)
@@ -12,8 +12,8 @@
extern "C" {
-static void reorder_edges(int npoints, int ntriangles,
- double *x, double *y,
+static void reorder_edges(int npoints, int ntriangles,
+ double *x, double *y,
int *edge_db, int *tri_edges, int *tri_nbrs)
{
int neighbors[3], nodes[3];
@@ -69,7 +69,7 @@
// Not trusting me? Okay, let's go through it:
// We have three edges to deal with and three nodes. Without loss
- // of generality, let's label the nodes A, B, and C with (A, B)
+ // of generality, let's label the nodes A, B, and C with (A, B)
// forming the first edge in the order they arrive on input.
// Then there are eight possibilities as to how the other edge-tuples
// may be labeled, but only two variations that are going to affect the
@@ -85,7 +85,7 @@
// The second test we need to perform is for counter-clockwiseness.
// Again, there are only two variations that will affect the outcome:
// either ABC is counter-clockwise, or it isn't. In the former case,
- // we're done setting the node order, we just need to associate the
+ // we're done setting the node order, we just need to associate the
// appropriate neighbor triangles with their opposite nodes, something
// which can be done by inspection. In the latter case, to order the
// nodes counter-clockwise, we only have to switch B and C to get
@@ -113,8 +113,8 @@
static PyObject* getMesh(int npoints, double *x, double *y)
{
- PyObject *vertices = NULL, *edge_db = NULL, *tri_edges = NULL, *tri_nbrs = NULL;
- PyObject *temp = NULL;
+ PyObject *vertices, *edge_db, *tri_edges, *tri_nbrs;
+ PyObject *temp;
int tri0, tri1, reg0, reg1;
double tri0x, tri0y, tri1x, tri1y;
int length, numtri, i, j;
@@ -136,21 +136,21 @@
dim[0] = length;
dim[1] = 2;
edge_db = PyArray_SimpleNew(2, dim, PyArray_INT);
- if (!edge_db) goto exit;
+ if (!edge_db) goto fail;
edge_db_ptr = (int*)PyArray_DATA(edge_db);
-
+
dim[0] = numtri;
vertices = PyArray_SimpleNew(2, dim, PyArray_DOUBLE);
- if (!vertices) goto exit;
+ if (!vertices) goto fail;
vertices_ptr = (double*)PyArray_DATA(vertices);
dim[1] = 3;
tri_edges = PyArray_SimpleNew(2, dim, PyArray_INT);
- if (!tri_edges) goto exit;
+ if (!tri_edges) goto fail;
tri_edges_ptr = (int*)PyArray_DATA(tri_edges);
tri_nbrs = PyArray_SimpleNew(2, dim, PyArray_INT);
- if (!tri_nbrs) goto exit;
+ if (!tri_nbrs) goto fail;
tri_nbrs_ptr = (int*)PyArray_DATA(tri_nbrs);
for (i=0; i<(3*numtri); i++) {
@@ -192,17 +192,25 @@
// tri_edges contains lists of edges; convert to lists of nodes in
// counterclockwise order and reorder tri_nbrs to match. Each node
// corresponds to the edge opposite it in the triangle.
- reorder_edges(npoints, numtri, x, y, edge_db_ptr, tri_edges_ptr,
+ reorder_edges(npoints, numtri, x, y, edge_db_ptr, tri_edges_ptr,
tri_nbrs_ptr);
temp = Py_BuildValue("(OOOO)", vertices, edge_db, tri_edges, tri_nbrs);
+ if (!temp) goto fail;
- exit:
+ Py_DECREF(vertices);
+ Py_DECREF(edge_db);
+ Py_DECREF(tri_edges);
+ Py_DECREF(tri_nbrs);
+
+ return temp;
+
+fail:
Py_XDECREF(vertices);
Py_XDECREF(edge_db);
Py_XDECREF(tri_edges);
Py_XDECREF(tri_nbrs);
- return temp;
+ return NULL;
}
static PyObject *linear_planes(int ntriangles, double *x, double *y, double *z,
@@ -213,7 +221,7 @@
int i;
double *planes_ptr;
double x02, y02, z02, x12, y12, z12, xy0212;
-
+
dims[0] = ntriangles;
dims[1] = 3;
planes = PyArray_SimpleNew(2, dims, PyArray_DOUBLE);
@@ -232,15 +240,15 @@
xy0212 = y02/y12;
INDEX3(planes_ptr,i,0) = (z02 - z12 * xy0212) / (x02 - x12 * xy0212);
INDEX3(planes_ptr,i,1) = (z12 - INDEX3(planes_ptr,i,0)*x12) / y12;
- INDEX3(planes_ptr,i,2) = (z[INDEX3(nodes,i,2)] -
- INDEX3(planes_ptr,i,0)*x[INDEX3(nodes,i,2)] -
+ INDEX3(planes_ptr,i,2) = (z[INDEX3(nodes,i,2)] -
+ INDEX3(planes_ptr,i,0)*x[INDEX3(nodes,i,2)] -
INDEX3(planes_ptr,i,1)*y[INDEX3(nodes,i,2)]);
} else {
xy0212 = x02/x12;
INDEX3(planes_ptr,i,1) = (z02 - z12 * xy0212) / (y02 - y12 * xy0212);
INDEX3(planes_ptr,i,0) = (z12 - INDEX3(planes_ptr,i,1)*y12) / x12;
- INDEX3(planes_ptr,i,2) = (z[INDEX3(nodes,i,2)] -
- INDEX3(planes_ptr,i,0)*x[INDEX3(nodes,i,2)] -
+ INDEX3(planes_ptr,i,2) = (z[INDEX3(nodes,i,2)] -
+ INDEX3(planes_ptr,i,0)*x[INDEX3(nodes,i,2)] -
INDEX3(planes_ptr,i,1)*y[INDEX3(nodes,i,2)]);
}
}
@@ -248,24 +256,24 @@
return (PyObject*)planes;
}
-static double linear_interpolate_single(double targetx, double targety,
+static double linear_interpolate_single(double targetx, double targety,
double *x, double *y, int *nodes, int *neighbors,
PyObject *planes, double defvalue, int start_triangle, int *end_triangle)
{
double *planes_ptr;
planes_ptr = (double*)PyArray_DATA(planes);
if (start_triangle == -1) start_triangle = 0;
- *end_triangle = walking_triangles(start_triangle, targetx, targety,
+ *end_triangle = walking_triangles(start_triangle, targetx, targety,
x, y, nodes, neighbors);
if (*end_triangle == -1) return defvalue;
- return (targetx*INDEX3(planes_ptr,*end_triangle,0) +
+ return (targetx*INDEX3(planes_ptr,*end_triangle,0) +
targety*INDEX3(planes_ptr,*end_triangle,1) +
INDEX3(planes_ptr,*end_triangle,2));
}
-static PyObject *linear_interpolate_grid(double x0, double x1, int xsteps,
+static PyObject *linear_interpolate_grid(double x0, double x1, int xsteps,
double y0, double y1, int ysteps,
- PyObject *planes, double defvalue,
+ PyObject *planes, double defvalue,
int npoints, double *x, double *y, int *nodes, int *neighbors)
{
int ix, iy;
@@ -304,10 +312,10 @@
static PyObject *compute_planes_method(PyObject *self, PyObject *args)
{
PyObject *pyx, *pyy, *pyz, *pynodes;
- PyObject *x = NULL, *y = NULL, *z = NULL, *nodes = NULL;
+ PyObject *x, *y, *z, *nodes;
int npoints, ntriangles;
- PyObject *planes = NULL;
+ PyObject *planes;
if (!PyArg_ParseTuple(args, "OOOO", &pyx, &pyy, &pyz, &pynodes)) {
return NULL;
@@ -315,52 +323,58 @@
x = PyArray_FROMANY(pyx, PyArray_DOUBLE, 1, 1, NPY_IN_ARRAY);
if (!x) {
PyErr_SetString(PyExc_ValueError, "x must be a 1-D array of floats");
- goto exit;
+ goto fail;
}
y = PyArray_FROMANY(pyy, PyArray_DOUBLE, 1, 1, NPY_IN_ARRAY);
if (!y) {
PyErr_SetString(PyExc_ValueError, "y must be a 1-D array of floats");
- goto exit;
+ goto fail;
}
z = PyArray_FROMANY(pyz, PyArray_DOUBLE, 1, 1, NPY_IN_ARRAY);
if (!z) {
PyErr_SetString(PyExc_ValueError, "z must be a 1-D array of floats");
- goto exit;
+ goto fail;
}
npoints = PyArray_DIM(x, 0);
if ((PyArray_DIM(y, 0) != npoints) || (PyArray_DIM(z, 0) != npoints)) {
PyErr_SetString(PyExc_ValueError, "x,y,z arrays must be of equal length");
- goto exit;
+ goto fail;
}
nodes = PyArray_FROMANY(pynodes, PyArray_INT, 2, 2, NPY_IN_ARRAY);
if (!nodes) {
PyErr_SetString(PyExc_ValueError, "nodes must be a 2-D array of ints");
- goto exit;
+ goto fail;
}
ntriangles = PyArray_DIM(nodes, 0);
if (PyArray_DIM(nodes, 1) != 3) {
PyErr_SetString(PyExc_ValueError, "nodes must have shape (ntriangles, 3)");
- goto exit;
+ goto fail;
}
- planes = linear_planes(ntriangles, (double*)PyArray_DATA(x),
+ planes = linear_planes(ntriangles, (double*)PyArray_DATA(x),
(double*)PyArray_DATA(y), (double*)PyArray_DATA(z), (int*)PyArray_DATA(nodes));
-exit:
+ Py_DECREF(x);
+ Py_DECREF(y);
+ Py_DECREF(z);
+ Py_DECREF(nodes);
+
+ return planes;
+
+fail:
Py_XDECREF(x);
Py_XDECREF(y);
Py_XDECREF(z);
Py_XDECREF(nodes);
-
- return planes;
+ return NULL;
}
static PyObject *linear_interpolate_method(PyObject *self, PyObject *args)
{
double x0, x1, y0, y1, defvalue;
int xsteps, ysteps;
- PyObject *pyplanes, *pyx, *pyy, *pynodes, *pyneighbors, *grid = NULL;
- PyObject *planes = NULL, *x = NULL, *y = NULL, *nodes = NULL, *neighbors = NULL;
+ PyObject *pyplanes, *pyx, *pyy, *pynodes, *pyneighbors, *grid;
+ PyObject *planes, *x, *y, *nodes, *neighbors;
int npoints;
@@ -371,47 +385,54 @@
x = PyArray_FROMANY(pyx, PyArray_DOUBLE, 1, 1, NPY_IN_ARRAY);
if (!x) {
PyErr_SetString(PyExc_ValueError, "x must be a 1-D array of floats");
- goto exit;
+ goto fail;
}
y = PyArray_FROMANY(pyy, PyArray_DOUBLE, 1, 1, NPY_IN_ARRAY);
if (!y) {
PyErr_SetString(PyExc_ValueError, "y must be a 1-D array of floats");
- goto exit;
+ goto fail;
}
npoints = PyArray_DIM(x, 0);
if (PyArray_DIM(y, 0) != npoints) {
PyErr_SetString(PyExc_ValueError, "x,y arrays must be of equal length");
- goto exit;
+ goto fail;
}
planes = PyArray_FROMANY(pyplanes, PyArray_DOUBLE, 2, 2, NPY_IN_ARRAY);
if (!planes) {
PyErr_SetString(PyExc_ValueError, "planes must be a 2-D array of floats");
- goto exit;
+ goto fail;
}
nodes = PyArray_FROMANY(pynodes, PyArray_INT, 2, 2, NPY_IN_ARRAY);
if (!nodes) {
PyErr_SetString(PyExc_ValueError, "nodes must be a 2-D array of ints");
- goto exit;
+ goto fail;
}
neighbors = PyArray_FROMANY(pyneighbors, PyArray_INT, 2, 2, NPY_IN_ARRAY);
if (!neighbors) {
PyErr_SetString(PyExc_ValueError, "neighbors must be a 2-D array of ints");
- goto exit;
+ goto fail;
}
grid = linear_interpolate_grid(x0, x1, xsteps, y0, y1, ysteps,
(PyObject*)planes, defvalue, npoints,
(double*)PyArray_DATA(x), (double*)PyArray_DATA(y),
(int*)PyArray_DATA(nodes), (int*)PyArray_DATA(neighbors));
+
+ Py_DECREF(x);
+ Py_DECREF(y);
+ Py_DECREF(planes);
+ Py_DECREF(nodes);
+ Py_DECREF(neighbors);
- exit:
+ return grid;
+
+fail:
Py_XDECREF(x);
Py_XDECREF(y);
Py_XDECREF(planes);
Py_XDECREF(nodes);
Py_XDECREF(neighbors);
-
- return grid;
+ return NULL;
}
// Thanks to C++'s memory rules, we can't use the usual "goto fail;" method of
@@ -434,7 +455,7 @@
{
PyObject *pyx, *pyy, *pyz, *pycenters, *pynodes, *pyneighbors, *pyintx, *pyinty;
PyObject *x = NULL, *y = NULL, *z = NULL, *centers = NULL, *nodes = NULL,
- *neighbors = NULL, *intx = NULL, *inty = NULL, *intz = NULL;
+ *neighbors = NULL, *intx = NULL, *inty = NULL, *intz;
double defvalue;
int size, npoints, ntriangles;
@@ -485,7 +506,7 @@
return NULL;
}
ntriangles = PyArray_DIM(neighbors, 0);
- if ((PyArray_DIM(nodes, 0) != ntriangles) ||
+ if ((PyArray_DIM(nodes, 0) != ntriangles) ||
(PyArray_DIM(centers, 0) != ntriangles)) {
PyErr_SetString(PyExc_ValueError, "centers,nodes,neighbors must be of equal length");
CLEANUP
@@ -521,13 +542,13 @@
return NULL;
}
- NaturalNeighbors nn(npoints, ntriangles,
+ NaturalNeighbors nn(npoints, ntriangles,
(double*)PyArray_DATA(x), (double*)PyArray_DATA(y),
- (double*)PyArray_DATA(centers), (int*)PyArray_DATA(nodes),
+ (double*)PyArray_DATA(centers), (int*)PyArray_DATA(nodes),
(int*)PyArray_DATA(neighbors));
size = PyArray_Size(intx);
- nn.interpolate_unstructured((double*)PyArray_DATA(z), size,
- (double*)PyArray_DATA(intx), (double*)PyArray_DATA(inty),
+ nn.interpolate_unstructured((double*)PyArray_DATA(z), size,
+ (double*)PyArray_DATA(intx), (double*)PyArray_DATA(inty),
(double*)PyArray_DATA(intz), defvalue);
Py_XDECREF(x);
@@ -554,13 +575,13 @@
static PyObject *nn_interpolate_method(PyObject *self, PyObject *args)
{
PyObject *pyx, *pyy, *pyz, *pycenters, *pynodes, *pyneighbors, *grid;
- PyObject *x = NULL, *y = NULL, *z = NULL, *centers = NULL, *nodes = NULL, *neighbors = NULL;
+ PyObject *x, *y, *z, *centers, *nodes, *neighbors;
double x0, x1, y0, y1, defvalue;
int xsteps, ysteps;
int npoints, ntriangles;
intp dims[2];
- if (!PyArg_ParseTuple(args, "ddiddidOOOOOO", &x0, &x1, &xsteps,
+ if (!PyArg_ParseTuple(args, "ddiddidOOOOOO", &x0, &x1, &xsteps,
&y0, &y1, &ysteps, &defvalue, &pyx, &pyy, &pyz, &pycenters, &pynodes,
&pyneighbors)) {
return NULL;
@@ -608,7 +629,7 @@
return NULL;
}
ntriangles = PyArray_DIM(neighbors, 0);
- if ((PyArray_DIM(nodes, 0) != ntriangles) ||
+ if ((PyArray_DIM(nodes, 0) != ntriangles) ||
(PyArray_DIM(centers, 0) != ntriangles)) {
PyErr_SetString(PyExc_ValueError, "centers,nodes,neighbors must be of equal length");
CLEANUP
@@ -623,11 +644,11 @@
return NULL;
}
- NaturalNeighbors nn(npoints, ntriangles,
+ NaturalNeighbors nn(npoints, ntriangles,
(double*)PyArray_DATA(x), (double*)PyArray_DATA(y),
- (double*)PyArray_DATA(centers), (int*)PyArray_DATA(nodes),
+ (double*)PyArray_DATA(centers), (int*)PyArray_DATA(nodes),
(int*)PyArray_DATA(neighbors));
- nn.interpolate_grid((double*)PyArray_DATA(z),
+ nn.interpolate_grid((double*)PyArray_DATA(z),
x0, x1, xsteps,
y0, y1, ysteps,
(double*)PyArray_DATA(grid),
@@ -642,8 +663,8 @@
static PyObject *delaunay_method(PyObject *self, PyObject *args)
{
- PyObject *pyx, *pyy, *mesh = NULL;
- PyObject *x = NULL, *y = NULL;
+ PyObject *pyx, *pyy, *mesh;
+ PyObject *x, *y;
int npoints;
if (!PyArg_ParseTuple(args, "OO", &pyx, &pyy)) {
@@ -652,31 +673,37 @@
x = PyArray_FROMANY(pyx, PyArray_DOUBLE, 1, 1, NPY_IN_ARRAY);
if (!x) {
PyErr_SetString(PyExc_ValueError, "x must be a 1-D array of floats");
- goto exit;
+ goto fail;
}
y = PyArray_FROMANY(pyy, PyArray_DOUBLE, 1, 1, NPY_IN_ARRAY);
if (!y) {
PyErr_SetString(PyExc_ValueError, "y must be a 1-D array of floats");
- goto exit;
+ goto fail;
}
npoints = PyArray_DIM(x, 0);
if (PyArray_DIM(y, 0) != npoints) {
PyErr_SetString(PyExc_ValueError, "x and y must have the same length");
- goto exit;
+ goto fail;
}
mesh = getMesh(npoints, (double*)PyArray_DATA(x), (double*)PyArray_DATA(y));
- exit:
+ if (!mesh) goto fail;
+
+ Py_DECREF(x);
+ Py_DECREF(y);
+
+ return mesh;
+
+fail:
Py_XDECREF(x);
Py_XDECREF(y);
-
- return mesh;
+ return NULL;
}
static PyMethodDef delaunay_methods[] = {
- {"delaunay", (PyCFunction)delaunay_method, METH_VARARGS,
+ {"delaunay", (PyCFunction)delaunay_method, METH_VARARGS,
"Compute the Delaunay triangulation of a cloud of 2-D points.\n\n"
"circumcenters, edges, tri_points, tri_neighbors = delaunay(x, y)\n\n"
"x, y -- shape-(npoints,) arrays of floats giving the X and Y coordinates of the points\n"
@@ -703,7 +730,7 @@
PyMODINIT_FUNC init_delaunay(void)
{
PyObject* m;
- m = Py_InitModule3("_delaunay", delaunay_methods,
+ m = Py_InitModule3("_delaunay", delaunay_methods,
"Tools for computing the Delaunay triangulation and some operations on it.\n"
);
if (m == NULL)
Modified: trunk/matplotlib/lib/matplotlib/delaunay/triangulate.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/delaunay/triangulate.py 2009-07-23 22:23:04 UTC (rev 7292)
+++ trunk/matplotlib/lib/matplotlib/delaunay/triangulate.py 2009-07-24 02:09:20 UTC (rev 7293)
@@ -1,8 +1,10 @@
import warnings
+# 2.3 compatibility
try:
set
except NameError:
- from sets import Set as set
+ import sets
+ set = sets.Set
import numpy as np
@@ -96,7 +98,7 @@
# Find the indices of the unique entries
j_sorted = np.lexsort(keys=(self.x, self.y))
mask_unique = np.hstack([
- True,
+ True,
(np.diff(self.x[j_sorted]) != 0) | (np.diff(self.y[j_sorted]) != 0),
])
return j_sorted[mask_unique]
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <lee...@us...> - 2009-07-23 22:23:23
|
Revision: 7292
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7292&view=rev
Author: leejjoon
Date: 2009-07-23 22:23:04 +0000 (Thu, 23 Jul 2009)
Log Message:
-----------
axes_grid: tick_out support for axisline.AxisArtist
Modified Paths:
--------------
trunk/matplotlib/lib/mpl_toolkits/axes_grid/axislines.py
Modified: trunk/matplotlib/lib/mpl_toolkits/axes_grid/axislines.py
===================================================================
--- trunk/matplotlib/lib/mpl_toolkits/axes_grid/axislines.py 2009-07-23 21:59:15 UTC (rev 7291)
+++ trunk/matplotlib/lib/mpl_toolkits/axes_grid/axislines.py 2009-07-23 22:23:04 UTC (rev 7292)
@@ -650,10 +650,16 @@
from matplotlib.lines import Line2D
class Ticks(Line2D):
- def __init__(self, ticksize, **kwargs):
+ def __init__(self, ticksize, tick_out=False, **kwargs):
+ """
+ ticksize : ticksize
+ tick_out : tick is directed outside (rotated by 180 degree) if True. default is False.
+ """
self.ticksize = ticksize
self.locs_angles = []
+ self.set_tick_out(tick_out)
+
self._axis = kwargs.pop("axis", None)
if self._axis is not None:
if "color" not in kwargs:
@@ -664,7 +670,18 @@
super(Ticks, self).__init__([0.], [0.], **kwargs)
self.set_snap(True)
+ def set_tick_out(self, b):
+ """
+ set True if tick need to be rotated by 180 degree.
+ """
+ self._tick_out = b
+ def get_tick_out(self):
+ """
+ Return True if the tick will be rotated by 180 degree.
+ """
+ return self._tick_out
+
def get_color(self):
if self._color == 'auto':
if self._axis is not None:
@@ -735,8 +752,11 @@
offset = renderer.points_to_pixels(size)
marker_scale = Affine2D().scale(offset, offset)
+ tick_out = self.get_tick_out()
for loc, angle, _ in self.locs_angles_labels:
+ if tick_out:
+ angle += 180
marker_rotation = Affine2D().rotate_deg(angle)
#marker_rotation.clear().rotate_deg(angle)
marker_transform = marker_scale + marker_rotation
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <lee...@us...> - 2009-07-23 21:59:31
|
Revision: 7291
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7291&view=rev
Author: leejjoon
Date: 2009-07-23 21:59:15 +0000 (Thu, 23 Jul 2009)
Log Message:
-----------
axes_grid: axisline respect rcParam's tick.direction
Modified Paths:
--------------
trunk/matplotlib/lib/mpl_toolkits/axes_grid/axislines.py
Modified: trunk/matplotlib/lib/mpl_toolkits/axes_grid/axislines.py
===================================================================
--- trunk/matplotlib/lib/mpl_toolkits/axes_grid/axislines.py 2009-07-23 21:36:51 UTC (rev 7290)
+++ trunk/matplotlib/lib/mpl_toolkits/axes_grid/axislines.py 2009-07-23 21:59:15 UTC (rev 7291)
@@ -434,6 +434,13 @@
if self.passthru_pt[1 - self.nth_coord] > 0.5:
angle = 180+angle
+
+ # take care the tick direction
+ if self.nth_coord == 0 and rcParams["xtick.direction"] == "out":
+ angle += 180
+ elif self.nth_coord == 1 and rcParams["ytick.direction"] == "out":
+ angle += 180
+
major = self.axis.major
majorLocs = major.locator()
major.formatter.set_locs(majorLocs)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <evi...@us...> - 2009-07-23 21:36:57
|
Revision: 7290
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7290&view=rev
Author: evilguru
Date: 2009-07-23 21:36:51 +0000 (Thu, 23 Jul 2009)
Log Message:
-----------
Try deleting the mathtex folder to get svn:externals working.
Removed Paths:
-------------
branches/mathtex/lib/mathtex/
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <evi...@us...> - 2009-07-23 21:32:28
|
Revision: 7289
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7289&view=rev
Author: evilguru
Date: 2009-07-23 21:32:21 +0000 (Thu, 23 Jul 2009)
Log Message:
-----------
Use svn:external to pull-in mathtex.
Modified Paths:
--------------
branches/mathtex/lib/matplotlib/sphinxext/mathmpl.py
Added Paths:
-----------
branches/mathtex/lib/mathtex/
Property Changed:
----------------
branches/mathtex/
Property changes on: branches/mathtex
___________________________________________________________________
Added: svn:externals
+ lib/mathtex http://mathtex.googlecode.com/svn/trunk/
Modified: branches/mathtex/lib/matplotlib/sphinxext/mathmpl.py
===================================================================
--- branches/mathtex/lib/matplotlib/sphinxext/mathmpl.py 2009-07-23 18:25:39 UTC (rev 7288)
+++ branches/mathtex/lib/matplotlib/sphinxext/mathmpl.py 2009-07-23 21:32:21 UTC (rev 7289)
@@ -9,10 +9,7 @@
from docutils.parsers.rst import directives
import warnings
-from matplotlib import rcParams
-from matplotlib.mathtext import MathTextParser
-rcParams['mathtext.fontset'] = 'cm'
-mathtext_parser = MathTextParser("Bitmap")
+from mathtex.mathtex_main import Mathtex
# Define LaTeX math node:
class latex_math(nodes.General, nodes.Element):
@@ -44,21 +41,18 @@
# This uses mathtext to render the expression
def latex2png(latex, filename, fontset='cm'):
latex = "$%s$" % latex
- orig_fontset = rcParams['mathtext.fontset']
- rcParams['mathtext.fontset'] = fontset
- if os.path.exists(filename):
- depth = mathtext_parser.get_depth(latex, dpi=100)
- else:
+
+ m = Mathtex(latex, 'bakoma')
+
+ if not os.path.exists(filename):
try:
- depth = mathtext_parser.to_png(filename, latex, dpi=100)
+ m.save(filename)
except:
warnings.warn("Could not render math expression %s" % latex,
Warning)
- depth = 0
- rcParams['mathtext.fontset'] = orig_fontset
sys.stdout.write("#")
sys.stdout.flush()
- return depth
+ return m.depth
# LaTeX to HTML translation stuff:
def latex2html(node, source):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2009-07-23 18:25:41
|
Revision: 7288
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7288&view=rev
Author: jswhit
Date: 2009-07-23 18:25:39 +0000 (Thu, 23 Jul 2009)
Log Message:
-----------
check for nonuniform grid spacing when using inter='linear' in griddata.
update griddata_demo.py (negative seeds not allowed in numpy svn mtrand)
Modified Paths:
--------------
trunk/matplotlib/examples/pylab_examples/griddata_demo.py
trunk/matplotlib/lib/matplotlib/mlab.py
Modified: trunk/matplotlib/examples/pylab_examples/griddata_demo.py
===================================================================
--- trunk/matplotlib/examples/pylab_examples/griddata_demo.py 2009-07-23 12:10:18 UTC (rev 7287)
+++ trunk/matplotlib/examples/pylab_examples/griddata_demo.py 2009-07-23 18:25:39 UTC (rev 7288)
@@ -4,7 +4,7 @@
import numpy as np
# make up data.
#npts = int(raw_input('enter # of random points to plot:'))
-seed(-1)
+seed(0)
npts = 200
x = uniform(-2,2,npts)
y = uniform(-2,2,npts)
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2009-07-23 12:10:18 UTC (rev 7287)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2009-07-23 18:25:39 UTC (rev 7288)
@@ -2717,6 +2717,14 @@
interp = tri.nn_interpolator(z)
zo = interp(xi,yi)
elif interp == 'linear':
+ # make sure grid has constant dx, dy
+ dx = xi[0,1:]-xi[0,0:-1]
+ dy = yi[1:,0]-yi[0:-1,0]
+ epsx = np.finfo(xi.dtype).resolution
+ epsy = np.finfo(yi.dtype).resolution
+ if dx.max()-dx.min() > epsx or dy.max()-dy.min() > epsy:
+ raise ValueError("output grid must have constant spacing"
+ " when using interp='linear'")
interp = tri.linear_interpolator(z)
zo = interp[yi.min():yi.max():complex(0,yi.shape[0]),
xi.min():xi.max():complex(0,xi.shape[1])]
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|