From: <ef...@us...> - 2007-09-09 22:41:38
|
Revision: 3819 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=3819&view=rev Author: efiring Date: 2007-09-09 15:41:36 -0700 (Sun, 09 Sep 2007) Log Message: ----------- Factored plotting part of pylab.py into pyplot.py Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/boilerplate.py trunk/matplotlib/examples/rc_traits.py trunk/matplotlib/lib/matplotlib/__init__.py trunk/matplotlib/lib/matplotlib/config/mplconfig.py trunk/matplotlib/lib/matplotlib/config/rcsetup.py trunk/matplotlib/lib/matplotlib/mlab.py trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf trunk/matplotlib/lib/matplotlib/pylab.py Added Paths: ----------- trunk/matplotlib/lib/matplotlib/pyplot.py Removed Paths: ------------- trunk/matplotlib/examples/gdtest.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2007-09-09 00:41:17 UTC (rev 3818) +++ trunk/matplotlib/CHANGELOG 2007-09-09 22:41:36 UTC (rev 3819) @@ -1,3 +1,12 @@ +2007-09-09 Split out the plotting part of pylab and put it in + pyplot.py; removed numerix from the remaining pylab.py, + which imports everything from pyplot.py. The intention + is that apart from cleanups, the result of importing + from pylab is nearly unchanged, but there is the + new alternative of importing from pyplot to get + the state-engine graphics without all the numeric + functions. - EF + 2007-09-08 Eliminated gd and paint backends - EF 2007-09-06 .bmp file format is now longer an alias for .raw @@ -8,12 +17,12 @@ Now it doesn't crash Preview.app. - JKS 2007-09-06 Refactored image saving code so that all GUI backends can - save most image types. See FILETYPES for a matrix of - backends and their supported file types. - Backend canvases should no longer write their own print_figure() - method -- instead they should write a print_xxx method for - each filetype they can output and add an entry to their - class-scoped filetypes dictionary. - MGD + save most image types. See FILETYPES for a matrix of + backends and their supported file types. + Backend canvases should no longer write their own print_figure() + method -- instead they should write a print_xxx method for + each filetype they can output and add an entry to their + class-scoped filetypes dictionary. - MGD 2007-09-05 Fixed Qt version reporting in setupext.py - DSD Modified: trunk/matplotlib/boilerplate.py =================================================================== --- trunk/matplotlib/boilerplate.py 2007-09-09 00:41:17 UTC (rev 3818) +++ trunk/matplotlib/boilerplate.py 2007-09-09 22:41:36 UTC (rev 3819) @@ -29,7 +29,7 @@ return ret if Axes.%(func)s.__doc__ is not None: %(func)s.__doc__ = dedent(Axes.%(func)s.__doc__) + \"\"\" -Addition kwargs: hold = [True|False] overrides default hold state\"\"\" +Additional kwargs: hold = [True|False] overrides default hold state\"\"\" """ _fmtmisc = """\ @@ -74,6 +74,8 @@ 'plot', 'plot_date', 'psd', + 'quiver', + 'quiverkey', 'scatter', 'semilogx', 'semilogy', @@ -82,8 +84,6 @@ 'stem', 'step', 'vlines', - 'quiver', - 'quiverkey', 'xcorr', ) @@ -104,7 +104,6 @@ 'pcolormesh' : 'gci._current = ret', 'imshow' : 'gci._current = ret', 'spy' : 'gci._current = ret', - 'quiver2' : 'gci._current = ret', 'quiver' : 'gci._current = ret', 'specgram' : 'gci._current = ret[-1]', @@ -129,11 +128,13 @@ # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def %(name)s(): - 'set the default colormap to %(name)s and apply to current image if any. See help(colormaps) for more information' + ''' + set the default colormap to %(name)s and apply to current image if any. + See help(colormaps) for more information + ''' rc('image', cmap='%(name)s') im = gci() - if im is not None: im.set_cmap(cm.%(name)s) draw_if_interactive() Deleted: trunk/matplotlib/examples/gdtest.py =================================================================== --- trunk/matplotlib/examples/gdtest.py 2007-09-09 00:41:17 UTC (rev 3818) +++ trunk/matplotlib/examples/gdtest.py 2007-09-09 22:41:36 UTC (rev 3819) @@ -1,34 +0,0 @@ -#!/usr/bin/env python -import matplotlib -matplotlib.use('GD') -from pylab import * - -def f(t): - s1 = cos(2*pi*t) - e1 = exp(-t) - return multiply(s1,e1) - -t1 = arange(0.0, 5.0, .1) -t2 = arange(0.0, 5.0, 0.02) -t3 = arange(0.0, 2.0, 0.01) - - -if 1: - subplot(211) - l = plot(t1, f(t1), 'k-^') - setp(l, 'markerfacecolor', 'r') - xlim(0,5) - title('A tale of 2 subplots', fontsize=12) - ylabel('Signal 1', fontsize=10) - - subplot(212) - l = plot(t1, f(t1), 'k->') - xlim(0,5) - ylabel('Signal 2', fontsize=10) - xlabel('time (s)', fontsize=10, fontname='Courier') - -ax = gca() - - -#savefig('gdtest', dpi=150) -show() Modified: trunk/matplotlib/examples/rc_traits.py =================================================================== --- trunk/matplotlib/examples/rc_traits.py 2007-09-09 00:41:17 UTC (rev 3818) +++ trunk/matplotlib/examples/rc_traits.py 2007-09-09 22:41:36 UTC (rev 3819) @@ -128,8 +128,8 @@ antialiased = flexible_true_trait timezones = 'UTC', 'US/Central', 'ES/Eastern' # fixme: and many more -backends = ('GTKAgg', 'Cairo', 'FltkAgg', 'GD', 'GDK', 'GTK', 'Agg', - 'GTKCairo', 'Paint', 'PS', 'SVG', 'Template', 'TkAgg', +backends = ('GTKAgg', 'Cairo', 'FltkAgg', 'GDK', 'GTK', 'Agg', + 'GTKCairo', 'PS', 'SVG', 'Template', 'TkAgg', 'WX') class RC(traits.HasTraits): Modified: trunk/matplotlib/lib/matplotlib/__init__.py =================================================================== --- trunk/matplotlib/lib/matplotlib/__init__.py 2007-09-09 00:41:17 UTC (rev 3818) +++ trunk/matplotlib/lib/matplotlib/__init__.py 2007-09-09 22:41:36 UTC (rev 3819) @@ -530,16 +530,16 @@ class RcParams(dict): - + """A dictionary object including validation - + validating functions are defined and associated with rc parameters in rcsetup.py """ - + validate = dict([ (key, converter) for key, (default, converter) in \ defaultParams.iteritems() ]) - + def __setitem__(self, key, val): try: if key in _deprecated_map.keys(): @@ -620,7 +620,7 @@ ret['datapath'] = get_data_path() verbose.report('loaded rc file %s'%fname) - + return ret Modified: trunk/matplotlib/lib/matplotlib/config/mplconfig.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2007-09-09 00:41:17 UTC (rev 3818) +++ trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2007-09-09 22:41:36 UTC (rev 3819) @@ -39,7 +39,7 @@ key = val optional comment val should be valid python syntax, just as you would use when setting - properties using rcParams. This should become more obvious by inspecting + properties using rcParams. This should become more obvious by inspecting the default values listed herein. Colors: for the color values below, you can either use @@ -50,7 +50,7 @@ - a legal html color name, eg red, blue, darkslategray Interactivity: see http://matplotlib.sourceforge.net/interactive.html. - + ### CONFIGURATION BEGINS HERE ### """ @@ -61,15 +61,15 @@ numerix = T.Trait('numpy', 'numpy', 'numeric', 'numarray') maskedarray = T.false units = T.false - + class backend(TConfig): """Valid backends are: 'GTKAgg', 'GTKCairo', 'QtAgg', 'Qt4Agg', 'TkAgg', 'Agg', 'Cairo', 'PS', 'PDF', 'SVG'""" use = T.Trait('TkAgg', mplT.BackendHandler()) - + class cairo(TConfig): format = T.Trait('png', 'png', 'ps', 'pdf', 'svg') - + class tk(TConfig): """ window_focus : Maintain shell focus for TkAgg @@ -78,7 +78,7 @@ window_focus = T.false pythoninspect = T.false - + class ps(TConfig): papersize = T.Trait('letter', 'auto', 'letter', 'legal', 'ledger', 'A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', @@ -87,22 +87,22 @@ 'B8', 'B9', 'B10') useafm = T.false fonttype = T.Trait(3, 42) - + class distiller(TConfig): use = T.Trait(None, None, 'ghostscript', 'xpdf', False) resolution = T.Float(6000) - + class pdf(TConfig): compression = T.Range(0, 9, 6) fonttype = T.Trait(3, 42) inheritcolor = T.false use14corefonts = T.false - + class svg(TConfig): image_inline = T.true image_noscale = T.false embed_chars = T.true - + class lines(TConfig): linewidth = T.Float(1.0) linestyle = T.Trait('-','--','-.', ':', 'steps', '', ' ', None) @@ -122,10 +122,10 @@ linewidth = T.Float(1.0) facecolor = T.Trait('blue', mplT.ColorHandler()) edgecolor = T.Trait('black', mplT.ColorHandler()) - antialiased = T.true + antialiased = T.true class font(TConfig): - family = T.Trait('sans-serif', 'sans-serif', 'serif', 'cursive', + family = T.Trait('sans-serif', 'sans-serif', 'serif', 'cursive', 'fantasy', 'monospace') style = T.Trait('normal', 'normal', 'italic', 'oblique') variant = T.Trait('normal', 'normal', 'small-caps') @@ -136,16 +136,16 @@ 'expanded', 'extra-expanded', 'ultra-expanded', 'wider', 'narrower') size = T.Float(12.0) - serif = T.ListStr(["Bitstream Vera Serif", "New Century Schoolbook", - "Century Schoolbook L", "Utopia", "ITC Bookman", "Bookman", - "Nimbus Roman No9 L", "Times New Roman", "Times", "Palatino", + serif = T.ListStr(["Bitstream Vera Serif", "New Century Schoolbook", + "Century Schoolbook L", "Utopia", "ITC Bookman", "Bookman", + "Nimbus Roman No9 L", "Times New Roman", "Times", "Palatino", "Charter", "serif"]) - sans_serif = T.ListStr(["Bitstream Vera Sans", "Lucida Grande", "Verdana", - "Geneva", "Lucid", "Arial", "Helvetica", "Avant Garde", + sans_serif = T.ListStr(["Bitstream Vera Sans", "Lucida Grande", "Verdana", + "Geneva", "Lucid", "Arial", "Helvetica", "Avant Garde", "sans-serif"]) - cursive = T.ListStr(["Apple Chancery", "Textile", "Zapf Chancery", "Sand", + cursive = T.ListStr(["Apple Chancery", "Textile", "Zapf Chancery", "Sand", "cursive"]) - fantasy = T.ListStr(["Comic Sans MS", "Chicago", "Charcoal", "Impact", "Western", + fantasy = T.ListStr(["Comic Sans MS", "Chicago", "Charcoal", "Impact", "Western", "fantasy"]) monospace = T.ListStr(["Bitstream Vera Sans Mono", "Andale Mono", "Nimbus Mono L", "Courier New", "Courier", "Fixed", "Terminal", "monospace"]) @@ -153,12 +153,12 @@ class text(TConfig): color = T.Trait('black',mplT.ColorHandler()) usetex = T.false - + class latex(TConfig): unicode = T.false preamble = T.ListStr([]) dvipnghack = T.false - + class mathtext(TConfig): cal = T.Trait('cursive' , mplT.FontconfigPatternHandler()) rm = T.Trait('serif' , mplT.FontconfigPatternHandler()) @@ -182,16 +182,16 @@ 'large', 'x-large', 'xx-large', T.Float) labelcolor = T.Trait('black', mplT.ColorHandler()) axisbelow = T.false - + class formatter(TConfig): limits = T.List(T.Float, [-7, 7], minlen=2, maxlen=2) - + class xticks(TConfig): color = T.Trait('black', mplT.ColorHandler()) labelsize = T.Trait('small', 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', T.Float) direction = T.Trait('in', 'out') - + class major(TConfig): size = T.Float(4) pad = T.Float(4) @@ -205,7 +205,7 @@ labelsize = T.Trait('small', 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', T.Float) direction = T.Trait('in', 'out') - + class major(TConfig): size = T.Float(4) pad = T.Float(4) @@ -220,8 +220,8 @@ linewidth = T.Float(0.5) class legend(TConfig): - loc = T.Trait('upper right', 'best', 'upper right', 'upper left', - 'lower left', 'lower right', 'right', 'center left', + loc = T.Trait('upper right', 'best', 'upper right', 'upper left', + 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center') isaxes = T.true numpoints = T.Int(3) @@ -264,26 +264,26 @@ class contour(TConfig): negative_linestyle = T.Trait('dashed', 'dashed', 'solid') - + class savefig(TConfig): dpi = T.Float(100) facecolor = T.Trait('white', mplT.ColorHandler()) edgecolor = T.Trait('white', mplT.ColorHandler()) orientation = T.Trait('portrait', 'portrait', 'landscape') - + class verbose(TConfig): level = T.Trait('silent', 'silent', 'helpful', 'debug', 'debug-annoying') fileo = T.Trait('sys.stdout', 'sys.stdout', T.File) class RcParamsWrapper(dict): - + """A backwards-compatible interface to a traited config object """ - + def __init__(self, tconfig): self.tconfig = tconfig - + self.tconfig_map = { 'backend' : (self.tconfig.backend, 'use'), 'numerix' : (self.tconfig, 'numerix'), @@ -337,7 +337,7 @@ 'text.latex.unicode' : (self.tconfig.text.latex, 'unicode'), 'text.latex.preamble' : (self.tconfig.text.latex, 'preamble'), 'text.dvipnghack' : (self.tconfig.text.latex, 'dvipnghack'), - + 'mathtext.cal' : (self.tconfig.mathtext, 'cal'), 'mathtext.rm' : (self.tconfig.mathtext, 'rm'), 'mathtext.tt' : (self.tconfig.mathtext, 'tt'), @@ -455,7 +455,7 @@ def keys(self): return self.tconfig_map.keys() - + def has_key(self, val): return self.tconfig_map.has_key(val) @@ -466,7 +466,7 @@ except AttributeError: for key, val in arg: self[key] = val - + for key in kwargs: self[key] = kwargs[key] Modified: trunk/matplotlib/lib/matplotlib/config/rcsetup.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/rcsetup.py 2007-09-09 00:41:17 UTC (rev 3818) +++ trunk/matplotlib/lib/matplotlib/config/rcsetup.py 2007-09-09 22:41:36 UTC (rev 3819) @@ -70,8 +70,8 @@ return fonttype validate_backend = ValidateInStrings('backend',[ - 'Agg2', 'Agg', 'Aqt', 'Cairo', 'CocoaAgg', 'EMF', 'GD', 'GDK', - 'GTK', 'GTKAgg', 'GTKCairo', 'FltkAgg', 'Paint', 'Pdf', 'PS', + 'Agg2', 'Agg', 'Aqt', 'Cairo', 'CocoaAgg', 'EMF', 'GDK', + 'GTK', 'GTKAgg', 'GTKCairo', 'FltkAgg', 'Pdf', 'PS', 'QtAgg', 'Qt4Agg', 'SVG', 'Template', 'TkAgg', 'WX', 'WXAgg', ], ignorecase=True) @@ -143,7 +143,7 @@ if len(s)==6 and s.isalnum(): # looks like hex return '#' + s - + if len(s)==7 and s.startswith('#') and s[1:].isalnum(): return s @@ -198,11 +198,11 @@ return float(s) except ValueError: raise ValueError('not a valid font size') - + def validate_font_properties(s): parse_fontconfig_pattern(s) return s - + validate_verbose = ValidateInStrings('verbose',[ 'silent', 'helpful', 'debug', 'debug-annoying', ]) @@ -367,7 +367,7 @@ 'mathtext.sf' : ['sans\-serif', validate_font_properties], 'mathtext.use_cm' : [True, validate_bool], 'mathtext.fallback_to_cm' : [True, validate_bool], - + 'image.aspect' : ['equal', validate_aspect], # equal, auto, a number 'image.interpolation' : ['bilinear', str], 'image.cmap' : ['jet', str], # one of gray, jet, etc Modified: trunk/matplotlib/lib/matplotlib/mlab.py =================================================================== --- trunk/matplotlib/lib/matplotlib/mlab.py 2007-09-09 00:41:17 UTC (rev 3818) +++ trunk/matplotlib/lib/matplotlib/mlab.py 2007-09-09 22:41:36 UTC (rev 3819) @@ -1937,7 +1937,7 @@ return npy.max(npy.sum(npy.absolute((npy.transpose(x))), axis=0)) elif y=='fro': xx = npy.dot(x.transpose(), x) - return npy.sqrt(asum(npy.diag(xx), axis=0)) + return npy.sqrt(npy.sum(npy.diag(xx), axis=0)) else: raise ValueError('Second argument not permitted for matrices') Modified: trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf =================================================================== --- trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf 2007-09-09 00:41:17 UTC (rev 3818) +++ trunk/matplotlib/lib/matplotlib/mpl-data/matplotlib.conf 2007-09-09 22:41:36 UTC (rev 3819) @@ -3,32 +3,32 @@ # This is a sample matplotlib configuration file. It should be placed # in HOME/.matplotlib/matplotlibrc (unix/linux like systems) and # C:\Documents and Settings\yourname\.matplotlib (win32 systems) -# +# # By default, the installer will overwrite the existing file in the install # path, so if you want to preserve yours, please move it to your HOME dir and # set the environment variable if necessary. -# +# # This file is best viewed in a editor which supports ini or conf mode syntax # highlighting. -# +# # Blank lines, or lines starting with a comment symbol, are ignored, # as are trailing comments. Other lines must have the format -# +# # key = val optional comment -# +# # val should be valid python syntax, just as you would use when setting -# properties using rcParams. This should become more obvious by inspecting +# properties using rcParams. This should become more obvious by inspecting # the default values listed herein. -# +# # Colors: for the color values below, you can either use # - a matplotlib color string, such as r, k, or b # - an rgb tuple, such as (1.0, 0.5, 0.0) # - a hex string, such as #ff00ff or ff00ff # - a scalar grayscale intensity such as 0.75 # - a legal html color name, eg red, blue, darkslategray -# +# # Interactivity: see http://matplotlib.sourceforge.net/interactive.html. -# +# # ### CONFIGURATION BEGINS HERE ### # a value of type 'str' @@ -42,7 +42,7 @@ # 'Africa/Abidjan' or 'Africa/Accra' or 'Africa/Addis_Ababa' or 'Africa/Algiers' # or 'Africa/Asmara' or 'Africa/Asmera' or 'Africa/Bamako' or 'Africa/Bangui' o # r 'Africa/Banjul' or 'Africa/Bissau' or 'Africa/Blantyre' or 'Africa/Brazzavil -# <...snipped 10590 chars...> +# <...snipped 10590 chars...> # or 'Turkey' or 'UCT' or 'US/Alaska' or 'US/Aleutian' or 'US/Arizona' or 'US/Ce # ntral' or 'US/East-Indiana' or 'US/Eastern' or 'US/Hawaii' or 'US/Indiana-Star # ke' or 'US/Michigan' or 'US/Mountain' or 'US/Pacific' or 'US/Pacific-New' or ' @@ -72,14 +72,14 @@ # name like 'orange', a hex color like '#efefef', a grayscale intensity # like '0.5', or an RGBA tuple (1,0,0,1) labelcolor = 'black' - # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium' + # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium' # or 'large' or 'x-large' or 'xx-large' labelsize = 'medium' # a value of type 'float' linewidth = 1.0 # one of 0, on, false, 1, no, n, y, off, yes, true polargrid = True - # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium' + # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium' # or 'large' or 'x-large' or 'xx-large' titlesize = 'large' @@ -191,7 +191,7 @@ serif = ['Bitstream Vera Serif', 'New Century Schoolbook', 'Century Schoolbook L', 'Utopia', 'ITC Bookman', 'Bookman', 'Nimbus Roman No9 L', 'Times New Roman', 'Times', 'Palatino', 'Charter', 'serif'] # a value of type 'float' size = 12.0 - # 'ultra-condensed' or 'extra-condensed' or 'condensed' or 'semi-condensed' + # 'ultra-condensed' or 'extra-condensed' or 'condensed' or 'semi-condensed' # or 'normal' or 'semi-expanded' or 'expanded' or 'extra-expanded' or 'ultra # -expanded' or 'wider' or 'narrower' stretch = 'normal' @@ -218,11 +218,11 @@ aspect = 'equal' # 'Accent' or 'Accent_r' or 'Blues' or 'Blues_r' or 'BrBG' or 'BrBG_r' or 'B # uGn' or 'BuGn_r' or 'BuPu' or 'BuPu_r' or 'Dark2' or 'Dark2_r' or 'GnBu' o - # r 'GnBu_r' or 'Greens' or 'Greens_r' or 'Greys' or 'Greys_r' or 'OrRd' or - # <...snipped 1010 chars...> - # ist_stern' or 'gist_stern_r' or 'gist_yarg' or 'gist_yarg_r' or 'gray' or + # r 'GnBu_r' or 'Greens' or 'Greens_r' or 'Greys' or 'Greys_r' or 'OrRd' or + # <...snipped 1010 chars...> + # ist_stern' or 'gist_stern_r' or 'gist_yarg' or 'gist_yarg_r' or 'gray' or # 'gray_r' or 'hot' or 'hot_r' or 'hsv' or 'hsv_r' or 'jet' or 'jet_r' or 'p - # ink' or 'pink_r' or 'prism' or 'prism_r' or 'spectral' or 'spectral_r' or + # ink' or 'pink_r' or 'prism' or 'prism_r' or 'spectral' or 'spectral_r' or # 'spring' or 'spring_r' or 'summer' or 'summer_r' or 'winter' or 'winter_r' cmap = 'jet' # 'bilinear' or 'nearest' or 'bicubic' or 'spline16' or 'spline36' or 'hanni @@ -237,7 +237,7 @@ [legend] # a value of type 'float' axespad = 0.02 - # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium' + # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium' # or 'large' or 'x-large' or 'xx-large' fontsize = 'medium' # a value of type 'float' @@ -362,7 +362,7 @@ color = 'black' # 'in' or 'out' direction = 'in' - # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium' + # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium' # or 'large' or 'x-large' or 'xx-large' labelsize = 'small' @@ -385,7 +385,7 @@ color = 'black' # 'in' or 'out' direction = 'in' - # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium' + # a value of type 'float' or 'xx-small' or 'x-small' or 'small' or 'medium' # or 'large' or 'x-large' or 'xx-large' labelsize = 'small' @@ -399,4 +399,4 @@ # a value of type 'float' pad = 4.0 # a value of type 'float' - size = 2.0 \ No newline at end of file + size = 2.0 Modified: trunk/matplotlib/lib/matplotlib/pylab.py =================================================================== --- trunk/matplotlib/lib/matplotlib/pylab.py 2007-09-09 00:41:17 UTC (rev 3818) +++ trunk/matplotlib/lib/matplotlib/pylab.py 2007-09-09 22:41:36 UTC (rev 3819) @@ -124,7 +124,7 @@ fliplr - flip the rows of a matrix up/down flipud - flip the columns of a matrix left/right linspace - a linear spaced vector of N values from min to max inclusive - logspace - a log spaced vector of N values from min to max inclusive + logspace - a log spaced vector of N values from min to max inclusive meshgrid - repeat x and y to make regular matrices ones - an array of ones rand - an array from the uniform distribution [0,1] @@ -198,54 +198,21 @@ exception of those in mlab.py provided by matplotlib. """ import sys, warnings -import cm -import _pylab_helpers -import mlab #so I can override hist, psd, etc... -from axes import Axes, PolarAxes -import backends from cbook import flatten, is_string_like, exception_to_str, popd, \ silent_list, iterable, enumerate, dedent -from colors import Normalize, normalize # latter for backwards compat. -from cm import get_cmap -from figure import Figure, figaspect -import image -from matplotlib import rcParams, rcParamsDefault, get_backend -from backend_bases import FigureCanvasBase -from artist import getp, get -from artist import setp as _setp +import matplotlib.numerix as nx +import numpy as npy +from matplotlib import mpl # pulls in most modules -import matplotlib.cbook as cbook -from matplotlib.mlab import csv2rec - -# a hack to keep old versions of ipython working with mpl after bug -# fix #1209354 -if 'IPython.Shell' in sys.modules: - from backends import new_figure_manager, draw_if_interactive, show -else: - from backends import pylab_setup - new_figure_manager, draw_if_interactive, show = pylab_setup() - - - -from image import imread as _imread -from lines import Line2D -from text import Text, Annotation -from patches import Polygon, Rectangle, Circle, Arrow -from transforms import blend_xy_sep_transform -from widgets import SubplotTool, Button, Slider, Widget - -import numerix as nx - -import numpy as npy -from matplotlib import mpl # catch more than an import error here, since the src could fail too, # eg a bad pytz install. I don't want to break all of matplotlib for # date support try: - from dates import date2num, num2date, datestr2num, strpdate2num, drange,\ + from matplotlib.dates import date2num, num2date,\ + datestr2num, strpdate2num, drange,\ epoch2num, num2epoch, mx2num,\ DateFormatter, IndexDateFormatter, DateLocator,\ RRuleLocator, YearLocator, MonthLocator, WeekdayLocator,\ @@ -256,24 +223,16 @@ __dates_all__ = [] pass else: - import dates - __dates_all__ = dates.__all__ + import matplotlib.dates + __dates_all__ = matplotlib.dates.__all__ -from ticker import TickHelper, Formatter, FixedFormatter, NullFormatter,\ - FuncFormatter, FormatStrFormatter, ScalarFormatter,\ - LogFormatter, LogFormatterExponent, LogFormatterMathtext,\ - Locator, IndexLocator, FixedLocator, NullLocator,\ - LinearLocator, LogLocator, AutoLocator, MultipleLocator,\ - MaxNLocator -import ticker -import matplotlib # bring all the symbols in so folks can import them from # pylab in one fell swoop -from numerix import array, zeros, shape, rank, size, fromstring,\ +from numpy.oldnumeric import array, zeros, shape, rank, size, fromstring,\ take, put, putmask, reshape, repeat, choose, searchsorted,\ - asum, cumsum, product, cumproduct, alltrue, sometrue, allclose,\ + cumsum, product, cumproduct, alltrue, sometrue, allclose,\ arrayrange, arange, asarray, convolve, swapaxes, concatenate,\ transpose, sort, argsort, argmax, argmin, innerproduct, dot,\ outerproduct, resize, indices, fromfunction, diagonal, trace,\ @@ -287,28 +246,32 @@ cosh, arccosh, arcsinh, arctanh, cross_correlate,\ pi, ArrayType, matrixmultiply -from numerix import Int8, UInt8, Int16, UInt16, Int32, UInt32, Float32,\ +from numpy.oldnumeric import sum as asum + +from numpy.oldnumeric import Int8, UInt8, Int16, UInt16, Int32, UInt32, Float32,\ Float64, Complex32, Complex64, Float, Int, Complex -from matplotlib.numerix.fft import fft -from matplotlib.numerix.linear_algebra import inverse, eigenvectors +from numpy.fft import fft # Why just fft? +from numpy.linalg import inv as inverse +from numpy.oldnumeric.linear_algebra import eigenvectors + # not quite the same as linalg.eig -#from matplotlib.numerix.mlab import rand,randn,eye,tri,diag,fliplr,flipud,rot90,tril,triu,ptp,mean,msort,median,std,cumsum,prod,cumprod,trapz,diff,cov,corrcoef,squeeze,kaiser,blackman,bartlett,hanning,hamming,sinc,eig,svd,angle,roots,amin, amax pymin, pymax = min, max -from matplotlib.numerix.mlab import * +from numpy.oldnumeric.mlab import * min, max = pymin, pymax +from numpy import amin, amax from matplotlib.mlab import window_hanning, window_none,\ conv, detrend, detrend_mean, detrend_none, detrend_linear,\ - corrcoef, polyfit, polyval, vander, entropy, normpdf,\ + polyfit, polyval, entropy, normpdf,\ levypdf, find, trapz, prepca, fix, rem, norm, orth, rank,\ sqrtm, prctile, center_matrix, rk4, exp_safe, amap,\ sum_flat, mean_flat, rms_flat, l1norm, l2norm, norm, frange,\ diagonal_matrix, base_repr, binary_repr, log2, ispower2,\ bivariate_normal, load, save, stineman_interp -from numpy import meshgrid, linspace, logspace +from numpy import meshgrid, linspace, logspace, corrcoef, vander """ problem syms @@ -326,2283 +289,7 @@ sign """ +from matplotlib.pyplot import * -from colorbar import colorbar_doc -def colorbar(mappable = None, cax=None,**kw): - if mappable is None: - mappable = gci() - ret = gcf().colorbar(mappable, cax = cax, **kw) - draw_if_interactive() - return ret -colorbar.__doc__ = colorbar_doc -def colors(): - """ - This is a do nothing function to provide you with help on how - matplotlib handles colors. - - Commands which take color arguments can use several formats to - specify the colors. For the basic builtin colors, you can use a - single letter - - b : blue - g : green - r : red - c : cyan - m : magenta - y : yellow - k : black - w : white - - - For a greater range of colors, you have two options. You can - specify the color using an html hex string, as in - - color = '#eeefff' - - or you can pass an R,G,B tuple, where each of R,G,B are in the - range [0,1]. - - You can also use any legal html name for a color, like 'red', - 'burlywood' and 'chartreuse' - - The example below creates a subplot with a dark - slate gray background - - subplot(111, axisbg=(0.1843, 0.3098, 0.3098)) - - Here is an example that creates a pale turqoise title - - title('Is this the best color?', color='#afeeee') - - """ - pass - -def plotting(): - """ - Plotting commands - axes - Create a new axes - axis - Set or return the current axis limits - bar - make a bar chart - boxplot - make a box and whiskers chart - cla - clear current axes - clabel - label a contour plot - clf - clear a figure window - close - close a figure window - colorbar - add a colorbar to the current figure - cohere - make a plot of coherence - contour - make a contour plot - contourf - make a filled contour plot - csd - make a plot of cross spectral density - draw - force a redraw of the current figure - errorbar - make an errorbar graph - figlegend - add a legend to the figure - figimage - add an image to the figure, w/o resampling - figtext - add text in figure coords - figure - create or change active figure - fill - make filled polygons - gca - return the current axes - gcf - return the current figure - gci - get the current image, or None - get - get a handle graphics property - hist - make a histogram - hold - set the hold state on current axes - legend - add a legend to the axes - loglog - a log log plot - imread - load image file into array - imshow - plot image data - matshow - display a matrix in a new figure preserving aspect - pcolor - make a pseudocolor plot - plot - make a line plot - psd - make a plot of power spectral density - quiver - make a direction field (arrows) plot - rc - control the default params - savefig - save the current figure - scatter - make a scatter plot - set - set a handle graphics property - semilogx - log x axis - semilogy - log y axis - show - show the figures - specgram - a spectrogram plot - stem - make a stem plot - subplot - make a subplot (numrows, numcols, axesnum) - table - add a table to the axes - text - add some text at location x,y to the current axes - title - add a title to the current axes - xlabel - add an xlabel to the current axes - ylabel - add a ylabel to the current axes - - autumn - set the default colormap to autumn - bone - set the default colormap to bone - cool - set the default colormap to cool - copper - set the default colormap to copper - flag - set the default colormap to flag - gray - set the default colormap to gray - hot - set the default colormap to hot - hsv - set the default colormap to hsv - jet - set the default colormap to jet - pink - set the default colormap to pink - prism - set the default colormap to prism - spring - set the default colormap to spring - summer - set the default colormap to summer - winter - set the default colormap to winter - spectral - set the default colormap to spectral - - """ - pass - -def colormaps(): - """ - matplotlib provides the following colormaps. - - autumn bone cool copper flag gray hot hsv jet pink prism - spring summer winter spectral - - You can set the colormap for an image, pcolor, scatter, etc, - either as a keyword argumentdef con - - >>> imshow(X, cmap=cm.hot) - - or post-hoc using the corresponding pylab interface function - - >>> imshow(X) - >>> hot() - >>> jet() - - In interactive mode, this will update the colormap allowing you to - see which one works best for your data. - """ - pass - - - -def get_current_fig_manager(): - figManager = _pylab_helpers.Gcf.get_active() - if figManager is None: - gcf() # creates an active figure as a side effect - figManager = _pylab_helpers.Gcf.get_active() - return figManager - - -# note we check for __doc__ is not None since py2exe optimize removes -# the docstrings -def connect(s, func): - return get_current_fig_manager().canvas.mpl_connect(s, func) -if FigureCanvasBase.mpl_connect.__doc__ is not None: - connect.__doc__ = dedent(FigureCanvasBase.mpl_connect.__doc__) - -def disconnect(cid): - return get_current_fig_manager().canvas.mpl_disconnect(cid) -if FigureCanvasBase.mpl_disconnect.__doc__ is not None: - disconnect.__doc__ = dedent(FigureCanvasBase.mpl_disconnect.__doc__) - -def get_plot_commands(): return ( 'axes', 'axis', 'bar', 'boxplot', 'cla', 'clf', - 'close', 'colorbar', 'cohere', 'csd', 'draw', 'errorbar', - 'figlegend', 'figtext', 'figimage', 'figure', 'fill', 'gca', - 'gcf', 'gci', 'get', 'gray', 'barh', 'jet', 'hist', 'hold', 'imread', - 'imshow', 'legend', 'loglog', 'quiver', 'rc', 'pcolor', 'pcolormesh', 'plot', 'psd', - 'savefig', 'scatter', 'set', 'semilogx', 'semilogy', 'show', - 'specgram', 'stem', 'subplot', 'table', 'text', 'title', 'xlabel', - 'ylabel', 'pie', 'polar') - -def raise_msg_to_str(msg): - """msg is a return arg from a raise. Join with new lines""" - if not is_string_like(msg): - msg = '\n'.join(map(str, msg)) - return msg - - -#----- Now we get started with the matlab(TM) commands ----# - - - -def axis(*v, **kwargs): - """ - Set/Get the axis properties:: - - v = axis() returns the current axes as v = [xmin, xmax, ymin, ymax] - - axis(v) where v = [xmin, xmax, ymin, ymax] sets the min and max - of the x and y axes - - axis('off') turns off the axis lines and labels - - axis('equal') changes limits of x or y axis so that equal - increments of x and y have the same length; a circle - is circular. - - axis('scaled') achieves the same result by changing the - dimensions of the plot box instead of the axis data - limits. - - axis('tight') changes x and y axis limits such that all data is - shown. If all data is already shown, it will move it to the center - of the figure without modifying (xmax-xmin) or (ymax-ymin). Note - this is slightly different than in matlab. - - axis('image') is 'scaled' with the axis limits equal to the - data limits. - - axis('auto') or 'normal' (deprecated) restores default behavior; - axis limits are automatically scaled to make the data fit - comfortably within the plot box. - - if len(*v)==0, you can pass in xmin, xmax, ymin, ymax as kwargs - selectively to alter just those limits w/o changing the others. - See help(xlim) and help(ylim) for more information - - The xmin, xmax, ymin, ymax tuple is returned - - """ - ax = gca() - v = ax.axis(*v, **kwargs) - draw_if_interactive() - return v - - -def axes(*args, **kwargs): - """ - Add an axes at positon rect specified by:: - - axes() by itself creates a default full subplot(111) window axis - - axes(rect, axisbg='w') where rect=[left, bottom, width, height] in - normalized (0,1) units. axisbg is the background color for the - axis, default white - - axes(h) where h is an axes instance makes h the - current axis An Axes instance is returned - - kwargs: - - axisbg=color : the axes background color - frameon=False : don't display the frame - sharex=otherax : the current axes shares xaxis attribute with otherax - sharey=otherax : the current axes shares yaxis attribute with otherax - polar=True|False : use a polar axes or not - - Examples - - examples/axes_demo.py places custom axes. - examples/shared_axis_demo.py uses sharex and sharey - - - """ - - nargs = len(args) - if len(args)==0: return subplot(111, **kwargs) - if nargs>1: - raise TypeError('Only one non keyword arg to axes allowed') - arg = args[0] - - if isinstance(arg, Axes): - a = gcf().sca(arg) - else: - rect = arg - a = gcf().add_axes(rect, **kwargs) - draw_if_interactive() - return a - -def delaxes(*args): - """ - delaxes(ax) - remove ax from the current figure. If ax doesn't - exist an error will be raised. - - delaxes(): delete the current axes - """ - if not len(args): - ax = gca() - else: - ax = args[0] - ret = gcf().delaxes(ax) - draw_if_interactive() - return ret - - -def _get_target_images(target=None): - if target is None: - ax = gca() - all = ax.get_images() - - if not len(all): - raise RuntimeError('You must first define an image, eg with imshow') - - images = [all[-1]] - else: - if iterable(target): images = target - else: images = [target] - - return images - -def clim(vmin=None, vmax=None): - """ - Set the color limits of the current image - - To apply clim to all axes images do - - clim(0, 0.5) - - If either vmin or vmax is None, the image min/max respectively - will be used for color scaling. - - If you want to set the clim of multiple images, - use, for example for im in gca().get_images(): im.set_clim(0, - 0.05) - - """ - im = gci() - if im is None: - raise RuntimeError('You must first define an image, eg with imshow') - - im.set_clim(vmin, vmax) - draw_if_interactive() - -def close(*args): - """ - Close a figure window - - close() by itself closes the current figure - - close(num) closes figure number num - - close(h) where h is a figure handle(instance) closes that figure - - close('all') closes all the figure windows - """ - - if len(args)==0: - figManager = _pylab_helpers.Gcf.get_active() - if figManager is None: return - else: _pylab_helpers.Gcf.destroy(figManager.num) - elif len(args)==1: - arg = args[0] - if arg=='all': - for manager in _pylab_helpers.Gcf.get_all_fig_managers(): - _pylab_helpers.Gcf.destroy(manager.num) - elif isinstance(arg, int): - _pylab_helpers.Gcf.destroy(arg) - elif isinstance(arg, Figure): - for manager in _pylab_helpers.Gcf.get_all_fig_managers(): - if manager.canvas.figure==arg: - _pylab_helpers.Gcf.destroy(manager.num) - else: - raise TypeError('Unrecognized argument type %s to close'%type(arg)) - else: - raise TypeError('close takes 0 or 1 arguments') - - -def clf(): - """ - Clear the current figure - """ - gcf().clf() - draw_if_interactive() - - - -def draw(): - 'redraw the current figure' - get_current_fig_manager().canvas.draw() - -def figtext(*args, **kwargs): - - ret = gcf().text(*args, **kwargs) - draw_if_interactive() - return ret -if Figure.text.__doc__ is not None: - figtext.__doc__ = dedent(Figure.text.__doc__) - -def figimage(*args, **kwargs): - # allow callers to override the hold state by passing hold=True|False - ret = gcf().figimage(*args, **kwargs) - draw_if_interactive() - gci._current = ret - return ret -if Figure.figimage.__doc__ is not None: - figimage.__doc__ = dedent(Figure.figimage.__doc__) + """ -Addition kwargs: hold = [True|False] overrides default hold state""" - -def figlegend(handles, labels, loc, **kwargs): - """ - Place a legend in the figure. Labels are a sequence of - strings, handles is a sequence of line or patch instances, and - loc can be a string r an integer specifying the legend - location - - USAGE: - legend( (line1, line2, line3), - ('label1', 'label2', 'label3'), - 'upper right') - - See help(legend) for information about the location codes - - A matplotlib.legend.Legend instance is returned - """ - l= gcf().legend(handles, labels, loc, **kwargs) - draw_if_interactive() - return l - -def savefig(*args, **kwargs): - fig = gcf() - return fig.savefig(*args, **kwargs) -if Figure.savefig.__doc__ is not None: - savefig.__doc__ = dedent(Figure.savefig.__doc__) - - -def figure(num=None, # autoincrement if None, else integer from 1-N - figsize = None, # defaults to rc figure.figsize - dpi = None, # defaults to rc figure.dpi - facecolor = None, # defaults to rc figure.facecolor - edgecolor = None, # defaults to rc figure.edgecolor - frameon = True, - FigureClass = Figure, - **kwargs - ): - """ - figure(num = None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k') - - - Create a new figure and return a handle to it. If num=None, the figure - number will be incremented and a new figure will be created. The returned - figure objects have a .number attribute holding this number. - - If num is an integer, and figure(num) already exists, make it - active and return the handle to it. If figure(num) does not exist - it will be created. Numbering starts at 1, matlab style - - figure(1) - - If you are creating many figures, make sure you explicitly call "close" - on the figures you are not using, because this will enable pylab - to properly clean up the memory. - - kwargs: - - figsize - width x height in inches; defaults to rc figure.figsize - dpi - resolution; defaults to rc figure.dpi - facecolor - the background color; defaults to rc figure.facecolor - edgecolor - the border color; defaults to rc figure.edgecolor - - rcParams gives the default values from the matplotlibrc file - - FigureClass is a Figure or derived class that will be passed on to - new_figure_manager in the backends which allows you to hook custom - Figureclasses into the pylab interface. Additional kwargs will be - passed on to your figure init function - """ - - if figsize is None : figsize = rcParams['figure.figsize'] - if dpi is None : dpi = rcParams['figure.dpi'] - if facecolor is None : facecolor = rcParams['figure.facecolor'] - if edgecolor is None : edgecolor = rcParams['figure.edgecolor'] - - if num is None: - allnums = [f.num for f in _pylab_helpers.Gcf.get_all_fig_managers()] - if allnums: - num = max(allnums) + 1 - else: - num = 1 - - figManager = _pylab_helpers.Gcf.get_fig_manager(num) - if figManager is None: - if get_backend()=='PS': dpi = 72 - - figManager = new_figure_manager(num, figsize=figsize, dpi=dpi, facecolor=facecolor, edgecolor=edgecolor, frameon=frameon, FigureClass=FigureClass, **kwargs) - _pylab_helpers.Gcf.set_active(figManager) - figManager.canvas.figure.number = num - - draw_if_interactive() - return figManager.canvas.figure - -def gca(**kwargs): - """ - Return the current axis instance. This can be used to control - axis properties either using set or the Axes methods. - - Example: - - plot(t,s) - set(gca(), 'xlim', [0,10]) # set the x axis limits - - or - - plot(t,s) - a = gca() - a.set_xlim([0,10]) # does the same - """ - - ax = gcf().gca(**kwargs) - return ax - -def gcf(): - "Return a handle to the current figure" - - figManager = _pylab_helpers.Gcf.get_active() - if figManager is not None: - return figManager.canvas.figure - else: - return figure() - -def gci(): - """ - get the current ScalarMappable instance (image or patch - collection), or None if no images or patch collections have been - defined. The commands imshow and figimage create images - instances, and the commands pcolor and scatter create patch - collection instances - """ - return gci._current -gci._current = None - - -def sci(im): - """ - Set the current image (the target of colormap commands like jet, hot or clim) - """ - gci._current = im - - -def hold(b=None): - """ - Set the hold state. If hold is None (default), toggle the - hold state. Else set the hold state to boolean value b. - - Eg - hold() # toggle hold - hold(True) # hold is on - hold(False) # hold is off - - When hold is True, subsequent plot commands will be added to the - current axes. When hold is False, the current axes and figure - will be cleared on the next plot command - """ - - gcf().hold(b) - gca().hold(b) - rc('axes', hold=b) - -def ishold(): - """ - Return the hold status of the current axes - """ - return gca().ishold() - -def isinteractive(): - """ - Return the interactive status - """ - return matplotlib.is_interactive() - -def imread(*args, **kwargs): - return _imread(*args, **kwargs) -if _imread.__doc__ is not None: - imread.__doc__ = dedent(_imread.__doc__) - - - - -def rc(*args, **kwargs): - matplotlib.rc(*args, **kwargs) -if matplotlib.rc.__doc__ is not None: - rc.__doc__ = dedent(matplotlib.rc.__doc__) - -def rcdefaults(): - matplotlib.rcdefaults() - draw_if_interactive() -if matplotlib.rcdefaults.__doc__ is not None: - rcdefaults.__doc__ = dedent(matplotlib.rcdefaults.__doc__) - - -def subplot(*args, **kwargs): - """ - Create a subplot command, creating axes with - - subplot(numRows, numCols, plotNum) - - where plotNum=1 is the first plot number and increasing plotNums - fill rows first. max(plotNum)==numRows*numCols - - You can leave out the commas if numRows<=numCols<=plotNum<10, as - in - - subplot(211) # 2 rows, 1 column, first (upper) plot - - subplot(111) is the default axis - - The background color of the subplot can be specified via keyword - argument 'axisbg', which takes a color string or gdk.Color as value, as in - - subplot(211, axisbg='y') - - See help(axes) for additional information on axes and subplot - keyword arguments. - - New subplots that overlap old will delete the old axes. If you do - not want this behavior, use fig.add_subplot or the axes command. Eg - - from pylab import * - plot([1,2,3]) # implicitly creates subplot(111) - subplot(211) # overlaps, subplot(111) is killed - plot(rand(12), rand(12)) - - """ - - - fig = gcf() - a = fig.add_subplot(*args, **kwargs) - bbox = a.bbox - byebye = [] - for other in fig.axes: - if other==a: continue - if bbox.overlaps(other.bbox, ignoreend=True): - byebye.append(other) - for ax in byebye: delaxes(ax) - - draw_if_interactive() - return a - - -def twinx(ax=None): - """ - Make a second axes overlay ax (or the current axes if ax is None) - sharing the xaxis. The ticks for ax2 will be placed on the right, - and the ax2 instance is returned. See examples/two_scales.py - """ - if ax is None: - ax=gca() - - - ax2 = gcf().add_axes(ax.get_position(), sharex=ax, frameon=False) - ax2.yaxis.tick_right() - ax2.yaxis.set_label_position('right') - ax.yaxis.tick_left() - draw_if_interactive() - return ax2 - - -def twiny(ax=None): - """ - Make a second axes overlay ax (or the current axes if ax is None) - sharing the yaxis. The ticks for ax2 will be placed on the top, - and the ax2 instance is returned. - """ - if ax is None: - ax=gca() - - - ax2 = gcf().add_axes(ax.get_position(), sharey=ax, frameon=False) - ax2.xaxis.tick_top() - ax2.xaxis.set_label_position('top') - ax.xaxis.tick_bottom() - draw_if_interactive() - return ax2 - -def title(s, *args, **kwargs): - """ - Set the title of the current axis to s - - Default font override is: - override = { - 'fontsize' : 'medium', - 'verticalalignment' : 'bottom', - 'horizontalalignment' : 'center' - } - - See the text docstring for information of how override and the - optional args work - - """ - l = gca().set_title(s, *args, **kwargs) - draw_if_interactive() - return l - - - -def xlabel(s, *args, **kwargs): - """ - Set the x axis label of the current axis to s - - Default override is - - override = { - 'fontsize' : 'small', - 'verticalalignment' : 'top', - 'horizontalalignment' : 'center' - } - - See the text docstring for information of how override and - the optional args work - - """ - l = gca().set_xlabel(s, *args, **kwargs) - draw_if_interactive() - return l - -def ylabel(s, *args, **kwargs): - """ - Set the y axis label of the current axis to s - - Defaults override is - - override = { - 'fontsize' : 'small', - 'verticalalignment' : 'center', - 'horizontalalignment' : 'right', - 'rotation'='vertical' : } - - See the text docstring for information of how override and the - optional args work - - """ - l = gca().set_ylabel(s, *args, **kwargs) - draw_if_interactive() - return l - - - - - -def xlim(*args, **kwargs): - """ - Set/Get the xlimits of the current axes - - xmin, xmax = xlim() : return the current xlim - xlim( (xmin, xmax) ) : set the xlim to xmin, xmax - xlim( xmin, xmax ) : set the xlim to xmin, xmax - - If you do not specify args, you can pass the xmin and xmax as - kwargs, eg - - xlim(xmax=3) # adjust the max leaving min unchanged - xlim(xmin=1) # adjust the min leaving max unchanged - - The new axis limits are returned as a length 2 tuple - - """ - ax = gca() - ret = ax.set_xlim(*args, **kwargs) - draw_if_interactive() - return ret - - -def ylim(*args, **kwargs): - """ - Set/Get the ylimits of the current axes - - ymin, ymax = ylim() : return the current ylim - ylim( (ymin, ymax) ) : set the ylim to ymin, ymax - ylim( ymin, ymax ) : set the ylim to ymin, ymax - - If you do not specify args, you can pass the ymin and ymax as - kwargs, eg - - ylim(ymax=3) # adjust the max leaving min unchanged - ylim(ymin=1) # adjust the min leaving max unchanged - - The new axis limits are returned as a length 2 tuple - - """ - ax = gca() - ret = ax.set_ylim(*args, **kwargs) - draw_if_interactive() - return ret - - - - -def xticks(*args, **kwargs): - """ - Set/Get the xlimits of the current ticklocs, labels - - # return locs, labels where locs is an array of tick locations and - # labels is an array of tick labels. - locs, labels = xticks() - - # set the locations of the xticks - xticks( arange(6) ) - - # set the locations and labels of the xticks - xticks( arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue') ) - - The keyword args, if any, are text properties; see text for more - information on text properties. - """ - ax = gca() - - if len(args)==0: - locs = ax.get_xticks() - labels = ax.get_xticklabels() - elif len(args)==1: - locs = ax.set_xticks(args[0]) - labels = ax.get_xticklabels() - elif len(args)==2: - locs = ax.set_xticks(args[0]) - labels = ax.set_xticklabels(args[1], **kwargs) - else: raise TypeError('Illegal number of arguments to xticks') - if len(kwargs): - for l in labels: - l.update(kwargs) - - draw_if_interactive() - return locs, silent_list('Text xticklabel', labels) - - - -def rgrids(*args, **kwargs): - """ - Set/Get the radial locations of the gridlines and ticklabels - - With no args, simply return lines, labels where lines is an - array of radial gridlines (Line2D instances) and labels is an - array of tick labels (Text instances). - - lines, labels = rgrids() - - With arguments, the syntax is - - lines, labels = RGRIDS(radii, labels=None, angle=22.5, **kwargs) - - The labels will appear at radial distances radii at angle - - labels, if not None, is a len(radii) list of strings of the - labels to use at each angle. - - if labels is None, the self.rformatter will be used - - Return value is a list of lines, labels where the lines are - matplotlib.Line2D instances and the labels are matplotlib.Text - instances. Note that on input the labels argument is a list of - strings, and on output it is a list of Text instances - - Examples - # set the locations of the radial gridlines and labels - lines, labels = rgrids( (0.25, 0.5, 1.0) ) - - # set the locations and labels of the radial gridlines and labels - lines, labels = rgrids( (0.25, 0.5, 1.0), ('Tom', 'Dick', 'Harry' ) - - """ - ax = gca() - if not isinstance(ax, PolarAxes): - raise RuntimeError('rgrids only defined for polar axes') - if len(args)==0: - lines = ax.rgridlines() - labels = ax.rgridlabels() - else: - lines, labels = ax.set_rgrids(*args, **kwargs) - - draw_if_interactive() - return ( silent_list('Line2D rgridline', lines), - silent_list('Text rgridlabel', labels) ) - -def thetagrids(*args, **kwargs): - """ - Set/Get the theta locations of the gridlines and ticklabels - - If no arguments are passed, return lines, labels where lines is an - array of radial gridlines (Line2D instances) and labels is an - array of tick labels (Text instances). - - lines, labels = thetagrids() - - Otherwise the syntax is - - lines, labels = THETAGRIDS(angles, labels=None, fmt='%d', frac = 1.1) - - set the angles at which to place the theta grids (these gridlines - are equal along the theta dimension). angles is in degrees - - labels, if not None, is a len(angles) list of strings of the - labels to use at each angle. - - if labels is None, the labels with be fmt%angle - - frac is the fraction of the polar axes radius at which to place - the label (1 is the edge).Eg 1.05 isd outside the axes and 0.95 - is inside the axes - - Return value is a list of lines, labels where the lines are - matplotlib.Line2D instances and the labels are matplotlib.Text - instances. Note that on input the labels argument is a list of - strings, and on output it is a list of Text instances - - Examples: - - # set the locations of the radial gridlines and labels - lines, labels = thetagrids( range(45,360,90) ) - - # set the locations and labels of the radial gridlines and labels - lines, labels = thetagrids( range(45,360,90), ('NE', 'NW', 'SW','SE') ) - """ - ax = gca() - if not isinstance(ax, PolarAxes): - raise RuntimeError('rgrids only defined for polar axes') - if len(args)==0: - lines = ax.thetagridlines() - labels = ax.thetagridlabels() - else: - lines, labels = ax.set_thetagrids(*args, **kwargs) - - draw_if_interactive() - return (silent_list('Line2D thetagridline', lines), - silent_list('Text thetagridlabel', labels) - ) - -def yticks(*args, **kwargs): - """ - Set/Get the ylimits of the current ticklocs, labels - - # return locs, labels where locs is an array of tick locations and - # labels is an array of tick labels. - locs, labels = yticks() - - # set the locations of the yticks - yticks( arange(6) ) - - # set the locations and labels of the yticks - yticks( arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue') ) - - The keyword args, if any, are text properties; see text for more - information on text properties. - """ - ax = gca() - - if len(args)==0: - locs = ax.get_yticks() - labels = ax.get_yticklabels() - elif len(args)==1: - locs = ax.set_yticks(args[0]) - labels = ax.get_yticklabels() - elif len(args)==2: - locs = ax.set_yticks(args[0]) - labels = ax.set_yticklabels(args[1], **kwargs) - else: raise TypeError('Illegal number of arguments to yticks') - if len(kwargs): - for l in labels: - l.update(kwargs) - - draw_if_interactive() - - return ( locs, - silent_list('Text yticklabel', labels) - ) - -def polar(*args, **kwargs): - """ - POLAR(theta, r) - - Make a polar plot. Multiple theta, r arguments are supported, - with format strings, as in plot. - """ - ax = gca(polar=True) - ret = ax.plot(*args, **kwargs) - draw_if_interactive() - return ret - -def over(func, *args, **kwargs): - """ - Call func(*args, **kwargs) with hold(True) and then restore the hold state - """ - h = ishold() - hold(True) - func(*args, **kwargs) - hold(h) - -def ioff(): - 'turn interactive mode off' - matplotlib.interactive(False) - -def ion(): - 'turn interactive mode on' - matplotlib.interactive(True) - -def switch_backend(newbackend): - """ - Swtich the default backend to newbackend. This feature is - EXPERIMENTAL, and is only expected to work switching to an image - backend. Eg, if you have a bunch of PS scripts that you want to - run from an interactive ipython session, yuo may want to switch to - the PS backend before running them to avoid having a bunch of GUI - windows popup. If you try to interactively switch from one GUI - backend to another, you will explode. - - Calling this command will close all open windows. - """ - close('all') - global new_figure_manager, draw_if_interactive, show - matplotlib.use(newbackend) - reload(backends) - from backends import new_figure_manager, draw_if_interactive, show - -def matshow(A, fignum=None, **kw): - """Display an array as a matrix in a new figure window. - - The origin is set at the upper left hand corner and rows (first dimension - of the array) are displayed horizontally. The aspect ratio of the figure - window is that of the array, unless this would make an excessively - short or narrow figure. - - Tick labels for the xaxis are placed on top. - - With one exception, keyword arguments are passed to - imshow(). - - Special keyword argument which is NOT passed to imshow(): - - - fignum(None): by default, matshow() creates a new figure window with - automatic numbering. If ... [truncated message content] |