From: <md...@us...> - 2008-06-11 15:49:22
|
Revision: 5471 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5471&view=rev Author: mdboom Date: 2008-06-11 08:49:11 -0700 (Wed, 11 Jun 2008) Log Message: ----------- Fix some mathtext scaling bugs Add new mathtext symbols Use mathtext to render math in the docs (the dog-fooding patch!) Move PNG reading/writing to its own module and remove it from _backend_agg and _image Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/doc/conf.py trunk/matplotlib/doc/devel/outline.rst trunk/matplotlib/doc/sphinxext/mathpng.py trunk/matplotlib/doc/users/mathtext.rst trunk/matplotlib/examples/pylab_examples/mathtext_examples.py trunk/matplotlib/lib/matplotlib/_mathtext_data.py trunk/matplotlib/lib/matplotlib/backends/backend_agg.py trunk/matplotlib/lib/matplotlib/backends/backend_svg.py trunk/matplotlib/lib/matplotlib/image.py trunk/matplotlib/lib/matplotlib/mathtext.py trunk/matplotlib/lib/matplotlib/texmanager.py trunk/matplotlib/matplotlibrc.template trunk/matplotlib/setup.py trunk/matplotlib/setupext.py trunk/matplotlib/src/_backend_agg.cpp trunk/matplotlib/src/_backend_agg.h trunk/matplotlib/src/_image.cpp trunk/matplotlib/src/_image.h trunk/matplotlib/src/ft2font.cpp trunk/matplotlib/src/ft2font.h Added Paths: ----------- trunk/matplotlib/doc/sphinxext/math_symbol_table.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2008-06-11 15:31:21 UTC (rev 5470) +++ trunk/matplotlib/CHANGELOG 2008-06-11 15:49:11 UTC (rev 5471) @@ -1,3 +1,13 @@ +2008-06-11 Use matplotlib.mathtext to render math expressions in + online docs - MGD + +2008-06-11 Move PNG loading/saving to its own extension module, and + remove duplicate code in _backend_agg.cpp and _image.cpp + that does the same thing - MGD + +2008-06-11 Numerous mathtext bugfixes, primarily related to + dpi-independence - MGD + 2008-06-10 Bar now applies the label only to the first patch only, and sets '_nolegend_' for the other patch labels. This lets autolegend work as expected for hist and bar - see Modified: trunk/matplotlib/doc/conf.py =================================================================== --- trunk/matplotlib/doc/conf.py 2008-06-11 15:31:21 UTC (rev 5470) +++ trunk/matplotlib/doc/conf.py 2008-06-11 15:49:11 UTC (rev 5471) @@ -27,7 +27,7 @@ # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['mathpng', 'sphinx.ext.autodoc'] +extensions = ['mathpng', 'math_symbol_table', 'sphinx.ext.autodoc'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] @@ -150,7 +150,11 @@ latex_logo = None # Additional stuff for the LaTeX preamble. -latex_preamble = '' +latex_preamble = """ + \usepackage{amsmath} + \usepackage{amsfonts} + \usepackage{amssymb} +""" # Documents to append as an appendix to all manuals. latex_appendices = [] Modified: trunk/matplotlib/doc/devel/outline.rst =================================================================== --- trunk/matplotlib/doc/devel/outline.rst 2008-06-11 15:31:21 UTC (rev 5470) +++ trunk/matplotlib/doc/devel/outline.rst 2008-06-11 15:49:11 UTC (rev 5471) @@ -113,13 +113,29 @@ ported over to rest and included in the API so the links from the user's guide tutorial work. + - There's nothing in the mathtext module that I really consider a + "public" API (i.e. that would be useful to people just doing + plots). If mathtext.py were to be documented, I would put it in + the developer's docs. Maybe I should just take the link in the + user's guide out. - MGD + #. This section might also benefit from a little more detail on the customizations that are possible (eg an example fleshing out the rc options a little bit). Admittedly, this is pretty clear from readin ghte rc file, but it might be helpful to a newbie. + - The only rcParam that is currently useful is mathtext.fontset, + which is documented here. The others only apply when + mathtext.fontset == 'custom', which I'd like to declare + "unsupported". It's really hard to get a good set of math fonts + working that way, though it might be useful in a bind when + someone has to use a specific wacky font for mathtext and only + needs basics, like sub/superscripts. - MGD + #. There is still a TODO in the file to include a complete list of symbols + - Done. It's pretty extensive, thanks to STIX... - MGD + coding guide (reviewed by EF) ----------------------------- Added: trunk/matplotlib/doc/sphinxext/math_symbol_table.py =================================================================== --- trunk/matplotlib/doc/sphinxext/math_symbol_table.py (rev 0) +++ trunk/matplotlib/doc/sphinxext/math_symbol_table.py 2008-06-11 15:49:11 UTC (rev 5471) @@ -0,0 +1,164 @@ +symbols = [ + ["Lower-case Greek", + 5, + r"""\alpha \beta \gamma \chi \delta \epsilon \eta \iota \kappa + \lambda \mu \nu \omega \phi \pi \psi \rho \sigma \tau \theta + \upsilon \xi \zeta \digamma \varepsilon \varkappa \varphi + \varpi \varrho \varsigma \vartheta"""], + ["Upper-case Greek", + 6, + r"""\Delta \Gamma \Lambda \Omega \Phi \Pi \Psi \Sigma \Theta + \Upsilon \Xi \mho \nabla"""], + ["Hebrew", + 4, + r"""\aleph \beth \daleth \gimel"""], + ["Delimiters", + 6, + r"""| \{ \lfloor / \Uparrow \llcorner \vert \} \rfloor \backslash + \uparrow \lrcorner \| \langle \lceil [ \Downarrow \ulcorner + \Vert \rangle \rceil ] \downarrow \urcorner"""], + ["Big symbols", + 5, + r"""\bigcap \bigcup \bigodot \bigoplus \bigotimes \biguplus + \bigvee \bigwedge \coprod \oint \prod \sum \int"""], + ["Standard Function Names", + 4, + r"""\arccos \csc \ker \min \arcsin \deg \lg \Pr \arctan \det \lim + \gcd \ln \sup \cot \hom \log \tan \coth \inf \max \tanh + \sec \arg \dim \liminf \sin \cos \exp \limsup \sinh \cosh"""], + ["Binary Operation and Relation Symbols", + 3, + r"""\ast \pm \slash \cap \star \mp \cup \cdot \uplus + \triangleleft \circ \odot \sqcap \triangleright \bullet \ominus + \sqcup \bigcirc \oplus \wedge \diamond \oslash \vee + \bigtriangledown \times \otimes \dag \bigtriangleup \div \wr + \ddag \barwedge \veebar \boxplus \curlywedge \curlyvee \boxminus + \Cap \Cup \boxtimes \bot \top \dotplus \boxdot \intercal + \rightthreetimes \divideontimes \leftthreetimes \equiv \leq \geq + \perp \cong \prec \succ \mid \neq \preceq \succeq \parallel \sim + \ll \gg \bowtie \simeq \subset \supset \Join \approx \subseteq + \supseteq \ltimes \asymp \sqsubset \sqsupset \rtimes \doteq + \sqsubseteq \sqsupseteq \smile \propto \dashv \vdash \frown + \models \in \ni \notin \approxeq \leqq \geqq \lessgtr \leqslant + \geqslant \lesseqgtr \backsim \lessapprox \gtrapprox \lesseqqgtr + \backsimeq \lll \ggg \gtreqqless \triangleq \lessdot \gtrdot + \gtreqless \circeq \lesssim \gtrsim \gtrless \bumpeq \eqslantless + \eqslantgtr \backepsilon \Bumpeq \precsim \succsim \between + \doteqdot \precapprox \succapprox \pitchfork \Subset \Supset + \fallingdotseq \subseteqq \supseteqq \risingdotseq \sqsubset + \sqsupset \varpropto \preccurlyeq \succcurlyeq \Vdash \therefore + \curlyeqprec \curlyeqsucc \vDash \because \blacktriangleleft + \blacktriangleright \Vvdash \eqcirc \trianglelefteq + \trianglerighteq \neq \vartriangleleft \vartriangleright \ncong + \nleq \ngeq \nsubseteq \nmid \nsupseteq \nparallel \nless \ngtr + \nprec \nsucc \subsetneq \nsim \supsetneq \nVDash \precnapprox + \succnapprox \subsetneqq \nvDash \precnsim \succnsim \supsetneqq + \nvdash \lnapprox \gnapprox \ntriangleleft \ntrianglelefteq + \lneqq \gneqq \ntriangleright \lnsim \gnsim \ntrianglerighteq + \approxident \origof \imageof \coloneq \triangleeq \stareq \nsime + \dotminus \eqsim \nequiv \Equiv \measeq \napprox \eqless + \kernelcontraction \nsupset \doublebarwedge \nVdash \arceq + \backcong \Doteq \eqdef \wedgeq \questeq \eqgtr \cupdot + \veeeq \nsubset \eqcolon \ne + """], + ["Arrow Symbols", + 2, + r"""\leftarrow \longleftarrow \uparrow \Leftarrow \Longleftarrow + \Uparrow \rightarrow \longrightarrow \downarrow \Rightarrow + \Longrightarrow \Downarrow \leftrightarrow \updownarrow + \longleftrightarrow \updownarrow \Leftrightarrow + \Longleftrightarrow \Updownarrow \mapsto \longmapsto \nearrow + \hookleftarrow \hookrightarrow \searrow \leftharpoonup + \rightharpoonup \swarrow \leftharpoondown \rightharpoondown + \nwarrow \rightleftharpoons \leadsto \dashrightarrow + \dashleftarrow \leftleftarrows \leftrightarrows \Lleftarrow + \Rrightarrow \twoheadleftarrow \leftarrowtail \looparrowleft + \leftrightharpoons \curvearrowleft \circlearrowleft \Lsh + \upuparrows \upharpoonleft \downharpoonleft \multimap + \leftrightsquigarrow \rightrightarrows \rightleftarrows + \rightrightarrows \rightleftarrows \twoheadrightarrow + \rightarrowtail \looparrowright \rightleftharpoons + \curvearrowright \circlearrowright \Rsh \downdownarrows + \upharpoonright \downharpoonright \rightsquigarrow \nleftarrow + \nrightarrow \nLeftarrow \nRightarrow \nleftrightarrow + \nLeftrightarrow \to \Swarrow \Searrow \Nwarrow \Nearrow + \barleftarrow \mapsup \mapsdown \mapsfrom \rightarrowbar + \twoheaduparrow \updownarrowbar \leftsquigarrow \rightzigzagarrow + \twoheaddownarrow \downzigzagarrow + """], + ["Miscellaneous Symbols", + 3, + r"""\neg \invnot \turnednot \infty \forall \wp \exists \bigstar + \angle \partial \nexists \measuredangle \eth \emptyset + \sphericalangle \clubsuit \varnothing \complement \diamondsuit + \imath \Finv \triangledown \heartsuit \jmath \Game \spadesuit + \ell \hbar \vartriangle \cdots \hslash \vdots \blacksquare \ldots + \blacktriangle \ddots \sharp \prime \blacktriangledown \Im \flat + \backprime \Re \natural \circledS \P \O \copyright \ss \Ldsh + \frakZ \l \carriagereturn \circledR \S \sterling \L \yen \danger + \d \OE \AA \AE \scurel \oe \o \checkmark \Rdsh \ae \ac \prurel \$ + \iiint \iint \iint \oiiint"""] +] + +from docutils import nodes, statemachine +from docutils.parsers.rst import Directive +class math_symbol_table_directive(Directive): + has_content = True + def run(self): + def get_n(n, l): + part = [] + for x in l: + part.append(x) + if len(part) == n: + yield part + part = [] + yield part + + lines = [] + for category, columns, syms in symbols: + syms = syms.split() + syms.sort() + lines.append("**%s**" % category) + lines.append('') + max_width = 0 + for sym in syms: + max_width = max(max_width, len(sym)) + max_width = max_width * 2 + 16 + header = " " + (('=' * max_width) + ' ') * columns + format = '%%%ds' % max_width + for chunk in get_n(20, get_n(columns, syms)): + lines.append(header) + for part in chunk: + line = [] + for sym in part: + line.append(format % (":math:`%s` ``%s``" % (sym, sym))) + lines.append(" " + " ".join(line)) + lines.append(header) + lines.append('') + self.state_machine.insert_input(lines, "Symbol table") + return [] + +from docutils.parsers.rst import directives +directives.register_directive('math_symbol_table', + math_symbol_table_directive) + +if __name__ == "__main__": + # Do some verification of the tables + from matplotlib import _mathtext_data + + print "SYMBOLS NOT IN STIX:" + all_symbols = {} + for category, columns, syms in symbols: + if category == "Standard Function Names": + continue + syms = syms.split() + for sym in syms: + if len(sym) > 1: + all_symbols[sym[1:]] = None + if sym[1:] not in _mathtext_data.tex2uni: + print sym + + print "SYMBOLS NOT IN TABLE:" + for sym in _mathtext_data.tex2uni: + if sym not in all_symbols: + print sym Modified: trunk/matplotlib/doc/sphinxext/mathpng.py =================================================================== --- trunk/matplotlib/doc/sphinxext/mathpng.py 2008-06-11 15:31:21 UTC (rev 5470) +++ trunk/matplotlib/doc/sphinxext/mathpng.py 2008-06-11 15:49:11 UTC (rev 5471) @@ -3,7 +3,7 @@ from hashlib import md5 except ImportError: from md5 import md5 - + from docutils import nodes from docutils.writers.html4css1 import HTMLTranslator from sphinx.latexwriter import LaTeXTranslator @@ -39,7 +39,7 @@ else: class math_directive(Directive): has_content = True - def run(self): + def run(self): latex = ' '.join(self.content) node = latex_math(self.block_text) node['latex'] = latex @@ -75,26 +75,44 @@ LaTeXTranslator.depart_latex_math = depart_latex_math_latex from os.path import isfile + +# This calls out to LaTeX to render the expression +def latex2png(latex, name): + f = open('math.tex', 'w') + f.write(r"""\documentclass[12pt]{article} + \pagestyle{empty} + \begin{document}""") + if inline: + f.write('$%s$' % latex) + else: + f.write(r'\[ %s \]' % latex) + f.write('\end{document}') + f.close() + os.system('latex --interaction=nonstopmode math.tex > /dev/null') + os.system('dvipng -bgTransparent -Ttight --noghostscript -l10 ' + + '-o %s math.dvi > /dev/null' % name) + +# This uses mathtext to render the expression +def latex2png(latex, filename): + from matplotlib import rcParams + from matplotlib import _png + from matplotlib.mathtext import MathTextParser + rcParams['mathtext.fontset'] = 'cm' + mathtext_parser = MathTextParser("Bitmap") + ftimage = mathtext_parser.parse("$%s$" % latex, 120) + _png.write_png(ftimage.as_rgba_str(), ftimage.get_width(), + ftimage.get_height(), filename) + # LaTeX to HTML translation stuff: def latex2html(node, source): inline = isinstance(node.parent, nodes.TextElement) latex = node['latex'] - print latex - name = 'math-' + md5(latex).hexdigest()[-10:] - if not isfile('_static/%s.png' % name): - f = open('math.tex', 'w') - f.write(r"""\documentclass[12pt]{article} - \pagestyle{empty} - \begin{document}""") - if inline: - f.write('$%s$' % latex) - else: - f.write(r'\[ %s \]' % latex) - f.write('\end{document}') - f.close() - os.system('latex --interaction=nonstopmode math.tex > /dev/null') - os.system('dvipng -bgTransparent -Ttight --noghostscript -l10 ' + - '-o _static/%s.png math.dvi > /dev/null' % name) + print latex.encode("ascii", "backslashreplace") + name = 'math-%s' % md5(latex).hexdigest()[-10:] + dest = '_static/%s.png' % name + if not isfile(dest): + latex2png(latex, dest) + path = '_static' count = source.split('/doc/')[-1].count('/') for i in range(count): @@ -110,3 +128,4 @@ else: cls = 'class="center" ' return '<img src="%s/%s.png" %s%s/>' % (path, name, align, cls) + Modified: trunk/matplotlib/doc/users/mathtext.rst =================================================================== --- trunk/matplotlib/doc/users/mathtext.rst 2008-06-11 15:31:21 UTC (rev 5470) +++ trunk/matplotlib/doc/users/mathtext.rst 2008-06-11 15:49:11 UTC (rev 5471) @@ -3,13 +3,11 @@ Writing mathematical expressions ================================ - -You can use TeX markup in any matplotlib text string; see the -:mod:`matplotlib.mathtext` module documentation for details. Note -that you do not need to have TeX installed, since matplotlib ships its -own TeX expression parser, layout engine and fonts. The layout engine -is a fairly direct adaptation of the layout algorithms in Donald -Knuth's TeX, so the quality is quite good (matplotlib also provides a +You can use TeX markup in any matplotlib text string. Note that you +do not need to have TeX installed, since matplotlib ships its own TeX +expression parser, layout engine and fonts. The layout engine is a +fairly direct adaptation of the layout algorithms in Donald Knuth's +TeX, so the quality is quite good (matplotlib also provides a ``usetex`` option for those who do want to call out to TeX to generate their text (see :ref:`usetex-tutorial`). @@ -37,9 +35,6 @@ produces ":math:`\alpha > \beta`". -.. TODO: Include a complete list here - - Subscripts and superscripts --------------------------- @@ -106,7 +101,7 @@ Radicals -------- -Radicals can be produced with the ``\sqrt[]{}`` command. For example: +Radicals can be produced with the ``\sqrt[]{}`` command. For example:: r'$\sqrt{2}$' @@ -116,7 +111,7 @@ Any base can (optionally) be provided inside square brackets. Note that the base must be a simple expression, and can not contain layout -commands such as fractions or sub/superscripts. +commands such as fractions or sub/superscripts:: r'$\sqrt[3]{x}$' @@ -181,6 +176,42 @@ .. image:: ../_static/stixsans_fontset.png +Custom fonts +~~~~~~~~~~~~ + +mathtext also provides a way to use custom fonts for math. This +method is fairly tricky to use, and should be considered an +experimental feature for patient users only. By setting the rcParam +``mathtext.fontset`` to ``custom``, you can then set the following +parameters, which control which font file to use for a particular set +of math characters. + + ============================== ================================= + Parameter Corresponds to + ============================== ================================= + ``mathtext.it`` ``\mathit{}`` or default italic + ``mathtext.rm`` ``\mathrm{}`` Roman (upright) + ``mathtext.tt`` ``\mathtt{}`` Typewriter (monospace) + ``mathtext.bf`` ``\mathbf{}`` bold italic + ``mathtext.cal`` ``\mathcal{}`` calligraphic + ``mathtext.sf`` ``\mathsf{}`` sans-serif + ============================== ================================= + +Each parameter should be set to a fontconfig font descriptor (as +defined in the yet-to-be-written font chapter). + +.. TODO: Link to font chapter + +The fonts used should have a Unicode mapping in order to find any +non-Latin characters, such as Greek. If you want to use a math symbol +that is not contained in your custom fonts, you can set the rcParam +``mathtext.fallback_to_cm`` to ``True`` which will cause the mathtext +system to use characters from the default Computer Modern fonts +whenever a particular character can not be found in the custom font. + +Note that the math glyphs specified in Unicode have evolved over time, +and many fonts may not have glyphs in the correct place for mathtext. + Accents ------- @@ -211,19 +242,29 @@ ``\widetilde{xyz}`` :math:`\widetilde{xyz}` ============================== ================================= +Care should be taken when putting accents on lower-case i's and j's. +Note that in the following ``\mathi`` is used to avoid the extra dot +over the i:: + r"$\hat i\ \ \hat \imath$" + +.. math:: + + \hat i\ \ \hat \imath + Symbols ------- You can also use a large number of the TeX symbols, as in ``\infty``, -``\leftarrow``, ``\sum``, ``\int``; see :mod:`matplotlib.mathtext` for a -complete list. +``\leftarrow``, ``\sum``, ``\int``. +.. math_symbol_table:: + If a particular symbol does not have a name (as is true of many of the more obscure symbols in the STIX fonts), Unicode characters can also be used:: - ur'Generic symbol: $\u23ce$' + ur'$\u23ce$' Example ------- Modified: trunk/matplotlib/examples/pylab_examples/mathtext_examples.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/mathtext_examples.py 2008-06-11 15:31:21 UTC (rev 5470) +++ trunk/matplotlib/examples/pylab_examples/mathtext_examples.py 2008-06-11 15:49:11 UTC (rev 5471) @@ -5,7 +5,7 @@ import gc stests = [ - r'Kerning: AVA $AVA$ $$', + r'$x \doteq y$', r'\$100.00 $\alpha \_$', r'$\frac{\$100.00}{y}$', r'$x y$', Modified: trunk/matplotlib/lib/matplotlib/_mathtext_data.py =================================================================== --- trunk/matplotlib/lib/matplotlib/_mathtext_data.py 2008-06-11 15:31:21 UTC (rev 5470) +++ trunk/matplotlib/lib/matplotlib/_mathtext_data.py 2008-06-11 15:49:11 UTC (rev 5471) @@ -37,6 +37,8 @@ r'\}' : ('cmex10', 130), r'\leftangle' : ('cmex10', 97), r'\rightangle' : ('cmex10', 64), + r'\langle' : ('cmex10', 97), + r'\rangle' : ('cmex10', 64), r'\widehat' : ('cmex10', 15), r'\widetilde' : ('cmex10', 52), @@ -1758,6 +1760,54 @@ tex2uni = { 'widehat': 0x0302, 'widetilde': 0x0303, +'langle': 0x27e8, +'rangle': 0x27e9, +'perp': 0x27c2, +'neq': 0x2260, +'Join': 0x2a1d, +'leqslant': 0x2a7d, +'geqslant': 0x2a7e, +'lessapprox': 0x2a85, +'gtrapprox': 0x2a86, +'lesseqqgtr': 0x2a8b, +'gtreqqless': 0x2a8c, +'triangleeq': 0x225c, +'eqslantless': 0x2a95, +'eqslantgtr': 0x2a96, +'backepsilon': 0x03f6, +'precapprox': 0x2ab7, +'succapprox': 0x2ab8, +'fallingdotseq': 0x2252, +'subseteqq': 0x2ac5, +'supseteqq': 0x2ac6, +'varpropto': 0x221d, +'precnapprox': 0x2ab9, +'succnapprox': 0x2aba, +'subsetneqq': 0x2acb, +'supsetneqq': 0x2acc, +'lnapprox': 0x2ab9, +'gnapprox': 0x2aba, +'longleftarrow': 0x27f5, +'longrightarrow': 0x27f6, +'longleftrightarrow': 0x27f7, +'Longleftarrow': 0x27f8, +'Longrightarrow': 0x27f9, +'Longleftrightarrow': 0x27fa, +'longmapsto': 0x27fc, +'leadsto': 0x21dd, +'dashleftarrow': 0x290e, +'dashrightarrow': 0x290f, +'circlearrowleft': 0x21ba, +'circlearrowright': 0x21bb, +'leftrightsquigarrow': 0x21ad, +'leftsquigarrow': 0x219c, +'rightsquigarrow': 0x219d, +'Game': 0x2141, +'hbar': 0x0127, +'hslash': 0x210f, +'ldots': 0x22ef, +'vdots': 0x22ee, +'doteqdot': 0x2251, 'doteq': 8784, 'partial': 8706, 'gg': 8811, @@ -1922,7 +1972,7 @@ 'napprox': 8777, 'ast': 8727, 'twoheaduparrow': 8607, -'doublebarwedge ?': 8966, +'doublebarwedge': 8966, 'Sigma': 931, 'leftharpoonaccent': 8400, 'ntrianglelefteq': 8940, Modified: trunk/matplotlib/lib/matplotlib/backends/backend_agg.py =================================================================== --- trunk/matplotlib/lib/matplotlib/backends/backend_agg.py 2008-06-11 15:31:21 UTC (rev 5470) +++ trunk/matplotlib/lib/matplotlib/backends/backend_agg.py 2008-06-11 15:49:11 UTC (rev 5471) @@ -40,6 +40,7 @@ from matplotlib.transforms import Affine2D, Bbox from _backend_agg import RendererAgg as _RendererAgg +from matplotlib import _png backend_version = 'v2.2' @@ -302,5 +303,9 @@ renderer.dpi = self.figure.dpi if is_string_like(filename_or_obj): filename_or_obj = file(filename_or_obj, 'wb') - self.get_renderer()._renderer.write_png(filename_or_obj, self.figure.dpi) + renderer = self.get_renderer() + x = renderer._renderer.buffer_rgba(0, 0) + _png.write_png(renderer._renderer.buffer_rgba(0, 0), + renderer.width, renderer.height, + filename_or_obj, self.figure.dpi) renderer.dpi = original_dpi Modified: trunk/matplotlib/lib/matplotlib/backends/backend_svg.py =================================================================== --- trunk/matplotlib/lib/matplotlib/backends/backend_svg.py 2008-06-11 15:31:21 UTC (rev 5470) +++ trunk/matplotlib/lib/matplotlib/backends/backend_svg.py 2008-06-11 15:49:11 UTC (rev 5471) @@ -1,6 +1,6 @@ from __future__ import division -import os, codecs, base64, tempfile, urllib, gzip, md5 +import os, codecs, base64, tempfile, urllib, gzip, md5, cStringIO from matplotlib import verbose, __version__, rcParams from matplotlib.backend_bases import RendererBase, GraphicsContextBase,\ @@ -14,6 +14,7 @@ from matplotlib.mathtext import MathTextParser from matplotlib.path import Path from matplotlib.transforms import Affine2D +from matplotlib import _png from xml.sax.saxutils import escape as escape_xml_text @@ -46,6 +47,7 @@ self._char_defs = {} self._markers = {} self._path_collection_id = 0 + self._imaged = {} self.mathtext_parser = MathTextParser('SVG') svgwriter.write(svgProlog%(width,height,width,height)) @@ -267,33 +269,20 @@ ) if rcParams['svg.image_inline']: - class Base64Writer(object): - def __init__(self, write_method): - self._write_method = write_method - self._buffer = '' - def write(self, data): - self._buffer += data - while len(self._buffer) >= 64: - self._write_method(base64.encodestring(buffer[:64])) - self._write_method('\n') - self._buffer = self._buffer[64:] - def flush(self): - self._write_method(base64.encodestring(self._buffer)) - self._write_method('\n') - self._svgwriter.write("data:image/png;base64,\n") - base64writer = Base64Writer(self._svgwriter.write) - + stringio = cStringIO.StringIO() im.flipud_out() - im.write_png(base64writer) + rows, cols, buffer = im.as_rgba_str() + _png.write_png(buffer, cols, rows, stringio) im.flipud_out() - base64writer.flush() + self._svgwriter.write(base64.encodestring(stringio.getvalue())) else: self._imaged[self.basename] = self._imaged.get(self.basename,0) + 1 filename = '%s.image%d.png'%(self.basename, self._imaged[self.basename]) verbose.report( 'Writing image file for inclusion: %s' % filename) im.flipud_out() - im.write_png(filename) + rows, cols, buffer = im.as_rgba_str() + _png.write_png(buffer, cols, rows, filename) im.flipud_out() self._svgwriter.write(filename) Modified: trunk/matplotlib/lib/matplotlib/image.py =================================================================== --- trunk/matplotlib/lib/matplotlib/image.py 2008-06-11 15:31:21 UTC (rev 5470) +++ trunk/matplotlib/lib/matplotlib/image.py 2008-06-11 15:49:11 UTC (rev 5471) @@ -16,6 +16,7 @@ # For clarity, names from _image are given explicitly in this module: from matplotlib import _image +from matplotlib import _png # For user convenience, the names from _image are also imported into # the image namespace: @@ -256,12 +257,13 @@ """Write the image to png file with fname""" im = self.make_image() if noscale: - numrows,numcols = im.get_size() + numrows, numcols = im.get_size() im.reset_matrix() im.set_interpolation(0) im.resize(numcols, numrows) im.flipud_out() - im.write_png(fname) + rows, cols, buffer = im.as_rgba_str() + _png.write_png(buffer, cols, rows, fname) def set_data(self, A, shape=None): """ @@ -661,7 +663,8 @@ def write_png(self, fname): """Write the image to png file with fname""" im = self.make_image() - im.write_png(fname) + rows, cols, buffer = im.as_rgba_str() + _png.write_png(buffer, cols, rows, fname) def imread(fname): """ @@ -686,7 +689,7 @@ return pil_to_array(image) - handlers = {'png' :_image.readpng, + handlers = {'png' :_png.read_png, } basename, ext = os.path.splitext(fname) ext = ext.lower()[1:] Modified: trunk/matplotlib/lib/matplotlib/mathtext.py =================================================================== --- trunk/matplotlib/lib/matplotlib/mathtext.py 2008-06-11 15:31:21 UTC (rev 5470) +++ trunk/matplotlib/lib/matplotlib/mathtext.py 2008-06-11 15:49:11 UTC (rev 5471) @@ -655,8 +655,9 @@ return xHeight def get_underline_thickness(self, font, fontsize, dpi): - cached_font = self._get_font(font) - return (cached_font.font.underline_thickness / 64.0 / fontsize) * (dpi) + # This function used to grab underline thickness from the font, + # but that information is just too un-reliable, so it is now hardcoded. + return ((0.75 / 12.0) * fontsize * dpi) / 72.0 def get_kern(self, font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi): @@ -682,6 +683,8 @@ fontmap = {} def __init__(self, *args, **kwargs): + self._stix_fallback = StixFonts(*args, **kwargs) + TruetypeFonts.__init__(self, *args, **kwargs) if not len(self.fontmap): for key, val in self._fontmap.iteritems(): @@ -689,6 +692,7 @@ self.fontmap[key] = fullpath self.fontmap[val] = fullpath + _slanted_symbols = Set(r"\int \oint".split()) def _get_glyph(self, fontname, font_class, sym, fontsize): @@ -717,6 +721,7 @@ cached_font.charmap[num]) if symbol_name is None: + return self._stix_fallback._get_glyph(fontname, font_class, sym, fontsize) warn("Unrecognized symbol '%s'. Substituting with a dummy symbol." % sym.encode('ascii', 'backslashreplace'), MathTextWarning) fontname = 'it' @@ -868,6 +873,8 @@ return self.cm_fallback._get_glyph( fontname, 'it', sym, fontsize) else: + if fontname == 'it' and isinstance(self, StixFonts): + return self._get_glyph('rm', font_class, sym, fontsize) warn("Substituting with a dummy symbol.", MathTextWarning) fontname = 'rm' new_fontname = fontname @@ -2031,7 +2038,8 @@ bslash = Literal('\\') - accent = oneOf(self._accent_map.keys() + list(self._wide_accents)) + accent = oneOf(self._accent_map.keys() + + list(self._wide_accents)) function = oneOf(list(self._function_names)) @@ -2057,10 +2065,10 @@ unicode_range = u"\U00000080-\U0001ffff" symbol =(Regex(UR"([a-zA-Z0-9 +\-*/<>=:,.;!'@()\[\]|%s])|(\\[%%${}\[\]_|])" % unicode_range) - | Combine( + | (Combine( bslash + oneOf(tex2uni.keys()) - ) + ) + FollowedBy(Regex("[^a-zA-Z]"))) ).setParseAction(self.symbol).leaveWhitespace() c_over_c =(Suppress(bslash) @@ -2486,14 +2494,14 @@ if super is not None: hlist = HCentered([super]) hlist.hpack(width, 'exactly') - vlist.extend([hlist, Kern(rule_thickness * 2.0)]) + vlist.extend([hlist, Kern(rule_thickness * 3.0)]) hlist = HCentered([nucleus]) hlist.hpack(width, 'exactly') vlist.append(hlist) if sub is not None: hlist = HCentered([sub]) hlist.hpack(width, 'exactly') - vlist.extend([Kern(rule_thickness * 2.0), hlist]) + vlist.extend([Kern(rule_thickness * 3.0), hlist]) shift = hlist.height + hlist.depth + rule_thickness * 2.0 vlist = Vlist(vlist) vlist.shift_amount = shift + nucleus.depth * 0.5 Modified: trunk/matplotlib/lib/matplotlib/texmanager.py =================================================================== --- trunk/matplotlib/lib/matplotlib/texmanager.py 2008-06-11 15:31:21 UTC (rev 5470) +++ trunk/matplotlib/lib/matplotlib/texmanager.py 2008-06-11 15:49:11 UTC (rev 5471) @@ -38,7 +38,7 @@ import numpy as np import matplotlib as mpl from matplotlib import rcParams -from matplotlib._image import readpng +from matplotlib._png import read_png DEBUG = False @@ -364,7 +364,7 @@ if alpha is None: pngfile = self.make_png(tex, fontsize, dpi) - X = readpng(os.path.join(self.texcache, pngfile)) + X = read_png(os.path.join(self.texcache, pngfile)) if rcParams['text.dvipnghack'] is not None: hack = rcParams['text.dvipnghack'] Modified: trunk/matplotlib/matplotlibrc.template =================================================================== --- trunk/matplotlib/matplotlibrc.template 2008-06-11 15:31:21 UTC (rev 5470) +++ trunk/matplotlib/matplotlibrc.template 2008-06-11 15:49:11 UTC (rev 5471) @@ -162,6 +162,8 @@ # The following settings allow you to select the fonts in math mode. # They map from a TeX font name to a fontconfig font pattern. # These settings are only used if mathtext.fontset is 'custom'. +# Note that this "custom" mode is unsupported and may go away in the +# future. #mathtext.cal : cursive #mathtext.rm : serif #mathtext.tt : monospace Modified: trunk/matplotlib/setup.py =================================================================== --- trunk/matplotlib/setup.py 2008-06-11 15:31:21 UTC (rev 5470) +++ trunk/matplotlib/setup.py 2008-06-11 15:49:11 UTC (rev 5471) @@ -34,7 +34,7 @@ check_for_cairo, check_provide_traits, check_provide_pytz, \ check_provide_dateutil, check_provide_configobj, check_for_dvipng, \ check_for_ghostscript, check_for_latex, check_for_pdftops, \ - check_for_datetime, options + check_for_datetime, options, build_png #import distutils.sysconfig # jdh @@ -100,16 +100,20 @@ print_raw("") print_raw("OPTIONAL BACKEND DEPENDENCIES") +has_libpng = check_for_libpng() -if check_for_libpng() and options['build_agg']: +if has_libpng and options['build_agg']: build_agg(ext_modules, packages) rc['backend'] = 'Agg' else: rc['backend'] = 'SVG' -if options['build_image']: +if has_libpng and options['build_image']: build_image(ext_modules, packages) +if has_libpng and options['build_agg'] or options['build_image']: + build_png(ext_modules, packages) + if options['build_windowing'] and sys.platform=='win32': build_windowing(ext_modules, packages) Modified: trunk/matplotlib/setupext.py =================================================================== --- trunk/matplotlib/setupext.py 2008-06-11 15:31:21 UTC (rev 5470) +++ trunk/matplotlib/setupext.py 2008-06-11 15:49:11 UTC (rev 5471) @@ -79,6 +79,7 @@ True = True False = False +BUILT_PNG = False BUILT_AGG = False BUILT_FT2FONT = False BUILT_TTCONV = False @@ -248,9 +249,6 @@ status, output = commands.getstatusoutput( "%s %s %s" % (pkg_config_exec, flags, packages)) - #if packages.startswith('pygtk'): - # print 'status', status, output - # raise SystemExit if status == 0: for token in output.split(): attr = _flags.get(token[:2], None) @@ -570,12 +568,18 @@ import numpy module.include_dirs.append(numpy.get_include()) +def add_png_flags(module): + try_pkgconfig(module, 'libpng', 'png') + add_base_flags(module) + add_numpy_flags(module) + module.libraries.append('z') + module.include_dirs.extend(['.']) + module.libraries.extend(std_libs) + def add_agg_flags(module): 'Add the module flags to build extensions which use agg' # before adding the freetype flags since -z comes later - try_pkgconfig(module, 'libpng', 'png') - module.libraries.append('z') add_base_flags(module) add_numpy_flags(module) module.include_dirs.extend(['src', '%s/include'%AGG_VERSION, '.']) @@ -1201,7 +1205,26 @@ ext_modules.append(module) BUILT_WXAGG = True +def build_png(ext_modules, packages): + global BUILT_PNG + if BUILT_PNG: return # only build it if you you haven't already + deps = ['src/_png.cpp', 'src/mplutils.cpp'] + deps.extend(glob.glob('CXX/*.cxx')) + deps.extend(glob.glob('CXX/*.c')) + + module = Extension( + 'matplotlib._png', + deps, + include_dirs=numpy_inc_dirs, + ) + + add_png_flags(module) + ext_modules.append(module) + + BUILT_PNG = True + + def build_agg(ext_modules, packages): global BUILT_AGG if BUILT_AGG: return # only build it if you you haven't already Modified: trunk/matplotlib/src/_backend_agg.cpp =================================================================== --- trunk/matplotlib/src/_backend_agg.cpp 2008-06-11 15:31:21 UTC (rev 5470) +++ trunk/matplotlib/src/_backend_agg.cpp 2008-06-11 15:49:11 UTC (rev 5471) @@ -1356,136 +1356,7 @@ return Py::Object(); } -static void write_png_data(png_structp png_ptr, png_bytep data, png_size_t length) { - PyObject* py_file_obj = (PyObject*)png_get_io_ptr(png_ptr); - PyObject* write_method = PyObject_GetAttrString(py_file_obj, "write"); - PyObject* result = NULL; - if (write_method) - result = PyObject_CallFunction(write_method, (char *)"s#", data, length); - Py_XDECREF(write_method); - Py_XDECREF(result); -} - -static void flush_png_data(png_structp png_ptr) { - PyObject* py_file_obj = (PyObject*)png_get_io_ptr(png_ptr); - PyObject* flush_method = PyObject_GetAttrString(py_file_obj, "flush"); - PyObject* result = NULL; - if (flush_method) - result = PyObject_CallFunction(flush_method, (char *)""); - Py_XDECREF(flush_method); - Py_XDECREF(result); -} - -// this code is heavily adapted from the paint license, which is in -// the file paint.license (BSD compatible) included in this -// distribution. TODO, add license file to MANIFEST.in and CVS Py::Object -RendererAgg::write_png(const Py::Tuple& args) -{ - _VERBOSE("RendererAgg::write_png"); - - args.verify_length(1, 2); - - FILE *fp = NULL; - bool close_file = false; - Py::Object py_fileobj = Py::Object(args[0]); - if (py_fileobj.isString()) { - std::string fileName = Py::String(py_fileobj); - const char *file_name = fileName.c_str(); - if ((fp = fopen(file_name, "wb")) == NULL) - throw Py::RuntimeError( Printf("Could not open file %s", file_name).str() ); - close_file = true; - } else if (PyFile_CheckExact(py_fileobj.ptr())) { - fp = PyFile_AsFile(py_fileobj.ptr()); - } - else { - PyObject* write_method = PyObject_GetAttrString(py_fileobj.ptr(), "write"); - if (!(write_method && PyCallable_Check(write_method))) { - Py_XDECREF(write_method); - throw Py::TypeError("Object does not appear to be a 8-bit string path or a Python file-like object"); - } - Py_XDECREF(write_method); - } - - png_bytep *row_pointers = NULL; - png_structp png_ptr = NULL; - png_infop info_ptr = NULL; - - try { - struct png_color_8_struct sig_bit; - png_uint_32 row; - - row_pointers = new png_bytep[height]; - for (row = 0; row < height; ++row) { - row_pointers[row] = pixBuffer + row * width * 4; - } - - png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); - if (png_ptr == NULL) { - throw Py::RuntimeError("Could not create write struct"); - } - - info_ptr = png_create_info_struct(png_ptr); - if (info_ptr == NULL) { - throw Py::RuntimeError("Could not create info struct"); - } - - if (setjmp(png_ptr->jmpbuf)) { - throw Py::RuntimeError("Error building image"); - } - - if (fp) { - png_init_io(png_ptr, fp); - } else { - png_set_write_fn(png_ptr, (void*)py_fileobj.ptr(), - &write_png_data, &flush_png_data); - } - png_set_IHDR(png_ptr, info_ptr, - width, height, 8, - PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, - PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); - - // Save the dpi of the image in the file - if (args.size() == 2) { - double dpi = Py::Float(args[1]); - size_t dots_per_meter = (size_t)(dpi / (2.54 / 100.0)); - png_set_pHYs(png_ptr, info_ptr, dots_per_meter, dots_per_meter, PNG_RESOLUTION_METER); - } - - // this a a color image! - sig_bit.gray = 0; - sig_bit.red = 8; - sig_bit.green = 8; - sig_bit.blue = 8; - /* if the image has an alpha channel then */ - sig_bit.alpha = 8; - png_set_sBIT(png_ptr, info_ptr, &sig_bit); - - png_write_info(png_ptr, info_ptr); - png_write_image(png_ptr, row_pointers); - png_write_end(png_ptr, info_ptr); - - - } catch (...) { - if (fp && close_file) fclose(fp); - delete [] row_pointers; - /* Changed calls to png_destroy_write_struct to follow - http://www.libpng.org/pub/png/libpng-manual.txt. - This ensures the info_ptr memory is released. - */ - if (png_ptr && info_ptr) png_destroy_write_struct(&png_ptr, &info_ptr); - throw; - } - - png_destroy_write_struct(&png_ptr, &info_ptr); - delete [] row_pointers; - if (fp && close_file) fclose(fp); - - return Py::Object(); -} - - -Py::Object RendererAgg::tostring_rgb(const Py::Tuple& args) { //"Return the rendered buffer as an RGB string"; @@ -1763,8 +1634,6 @@ "draw_image(x, y, im)"); add_varargs_method("write_rgba", &RendererAgg::write_rgba, "write_rgba(fname)"); - add_varargs_method("write_png", &RendererAgg::write_png, - "write_png(fname, dpi=None)"); add_varargs_method("tostring_rgb", &RendererAgg::tostring_rgb, "s = tostring_rgb()"); add_varargs_method("tostring_argb", &RendererAgg::tostring_argb, Modified: trunk/matplotlib/src/_backend_agg.h =================================================================== --- trunk/matplotlib/src/_backend_agg.h 2008-06-11 15:31:21 UTC (rev 5470) +++ trunk/matplotlib/src/_backend_agg.h 2008-06-11 15:49:11 UTC (rev 5471) @@ -176,7 +176,6 @@ Py::Object write_rgba(const Py::Tuple & args); - Py::Object write_png(const Py::Tuple & args); Py::Object tostring_rgb(const Py::Tuple & args); Py::Object tostring_argb(const Py::Tuple & args); Py::Object tostring_bgra(const Py::Tuple & args); Modified: trunk/matplotlib/src/_image.cpp =================================================================== --- trunk/matplotlib/src/_image.cpp 2008-06-11 15:31:21 UTC (rev 5470) +++ trunk/matplotlib/src/_image.cpp 2008-06-11 15:49:11 UTC (rev 5471) @@ -1,11 +1,9 @@ -#include <png.h> - // To remove a gcc warning #ifdef _POSIX_C_SOURCE #undef _POSIX_C_SOURCE #endif -#include "Python.h" //after png.h due to setjmp bug +#include "Python.h" #include <string> #include <iostream> @@ -644,131 +642,7 @@ return Py::Object(); } -static void write_png_data(png_structp png_ptr, png_bytep data, png_size_t length) { - PyObject* py_file_obj = (PyObject*)png_get_io_ptr(png_ptr); - PyObject* write_method = PyObject_GetAttrString(py_file_obj, "write"); - PyObject* result = NULL; - if (write_method) - result = PyObject_CallFunction(write_method, (char *)"s#", data, length); - Py_XDECREF(write_method); - Py_XDECREF(result); -} -static void flush_png_data(png_structp png_ptr) { - PyObject* py_file_obj = (PyObject*)png_get_io_ptr(png_ptr); - PyObject* flush_method = PyObject_GetAttrString(py_file_obj, "flush"); - PyObject* result = NULL; - if (flush_method) - result = PyObject_CallFunction(flush_method, (char *)""); - Py_XDECREF(flush_method); - Py_XDECREF(result); -} - -// this code is heavily adapted from the paint license, which is in -// the file paint.license (BSD compatible) included in this -// distribution. TODO, add license file to MANIFEST.in and CVS -char Image::write_png__doc__[] = -"write_png(fname)\n" -"\n" -"Write the image to filename fname as png\n" -; -Py::Object -Image::write_png(const Py::Tuple& args) -{ - //small memory leak in this function - JDH 2004-06-08 - _VERBOSE("Image::write_png"); - - args.verify_length(1); - - FILE *fp = NULL; - Py::Object py_fileobj = Py::Object(args[0]); - if (py_fileobj.isString()) { - std::string fileName = Py::String(py_fileobj); - const char *file_name = fileName.c_str(); - if ((fp = fopen(file_name, "wb")) == NULL) - throw Py::RuntimeError( Printf("Could not open file %s", file_name).str() ); - } - else { - PyObject* write_method = PyObject_GetAttrString(py_fileobj.ptr(), "write"); - if (!(write_method && PyCallable_Check(write_method))) { - Py_XDECREF(write_method); - throw Py::TypeError("Object does not appear to be a path or a Python file-like object"); - } - Py_XDECREF(write_method); - } - - png_structp png_ptr; - png_infop info_ptr; - struct png_color_8_struct sig_bit; - png_uint_32 row=0; - - //todo: allocate on heap - png_bytep *row_pointers = NULL; - std::pair<agg::int8u*,bool> bufpair; - bufpair.first = NULL; - bufpair.second = false; - - try { - row_pointers = new png_bytep[rowsOut]; - if (!row_pointers) - throw Py::RuntimeError("Out of memory"); - - bufpair = _get_output_buffer(); - for (row = 0; row < rowsOut; ++row) - row_pointers[row] = bufpair.first + row * colsOut * 4; - - png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); - if (png_ptr == NULL) - throw Py::RuntimeError("Could not create write struct"); - - info_ptr = png_create_info_struct(png_ptr); - if (info_ptr == NULL) - throw Py::RuntimeError("Could not create info struct"); - - if (setjmp(png_ptr->jmpbuf)) - throw Py::RuntimeError("Error building image"); - - if (fp) { - png_init_io(png_ptr, fp); - } else { - png_set_write_fn(png_ptr, (void*)py_fileobj.ptr(), - &write_png_data, &flush_png_data); - } - png_set_IHDR(png_ptr, info_ptr, - colsOut, rowsOut, 8, - PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, - PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); - - // this a a color image! - sig_bit.gray = 0; - sig_bit.red = 8; - sig_bit.green = 8; - sig_bit.blue = 8; - /* if the image has an alpha channel then */ - sig_bit.alpha = 8; - png_set_sBIT(png_ptr, info_ptr, &sig_bit); - - png_write_info(png_ptr, info_ptr); - png_write_image(png_ptr, row_pointers); - png_write_end(png_ptr, info_ptr); - png_destroy_write_struct(&png_ptr, &info_ptr); - } catch (...) { - if (bufpair.second) delete [] bufpair.first; - if (fp) fclose(fp); - png_destroy_write_struct(&png_ptr, &info_ptr); - delete [] row_pointers; - throw; - } - - if (fp) fclose(fp); - delete [] row_pointers; - if (bufpair.second) delete [] bufpair.first; - - return Py::Object(); -} - - - char Image::set_aspect__doc__[] = "set_aspect(scheme)\n" "\n" @@ -812,7 +686,6 @@ add_varargs_method( "set_interpolation", &Image::set_interpolation, Image::set_interpolation__doc__); add_varargs_method( "set_resample", &Image::set_resample, Image::set_resample__doc__); add_varargs_method( "set_aspect", &Image::set_aspect, Image::set_aspect__doc__); - add_varargs_method( "write_png", &Image::write_png, Image::write_png__doc__); add_varargs_method( "set_bg", &Image::set_bg, Image::set_bg__doc__); add_varargs_method( "flipud_out", &Image::flipud_out, Image::flipud_out__doc__); add_varargs_method( "flipud_in", &Image::flipud_in, Image::flipud_in__doc__); @@ -901,118 +774,6 @@ } - -char _image_module_readpng__doc__[] = -"readpng(fname)\n" -"\n" -"Load an image from png file into a numerix array of MxNx4 float"; -Py::Object -_image_module::readpng(const Py::Tuple& args) { - - args.verify_length(1); - std::string fname = Py::String(args[0]); - - png_byte header[8]; // 8 is the maximum size that can be checked - - FILE *fp = fopen(fname.c_str(), "rb"); - if (!fp) - throw Py::RuntimeError(Printf("_image_module::readpng could not open PNG file %s for reading", fname.c_str()).str()); - - if (fread(header, 1, 8, fp) != 8) - throw Py::RuntimeError("_image_module::readpng: error reading PNG header"); - if (png_sig_cmp(header, 0, 8)) - throw Py::RuntimeError("_image_module::readpng: file not recognized as a PNG file"); - - - /* initialize stuff */ - png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); - - if (!png_ptr) - throw Py::RuntimeError("_image_module::readpng: png_create_read_struct failed"); - - png_infop info_ptr = png_create_info_struct(png_ptr); - if (!info_ptr) - throw Py::RuntimeError("_image_module::readpng: png_create_info_struct failed"); - - if (setjmp(png_jmpbuf(png_ptr))) - throw Py::RuntimeError("_image_module::readpng: error during init_io"); - - png_init_io(png_ptr, fp); - png_set_sig_bytes(png_ptr, 8); - - png_read_info(png_ptr, info_ptr); - - png_uint_32 width = info_ptr->width; - png_uint_32 height = info_ptr->height; - - // convert misc color types to rgb for simplicity - if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY || - info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) - png_set_gray_to_rgb(png_ptr); - else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) - png_set_palette_to_rgb(png_ptr); - - - int bit_depth = info_ptr->bit_depth; - if (bit_depth == 16) png_set_strip_16(png_ptr); - - - png_set_interlace_handling(png_ptr); - png_read_update_info(png_ptr, info_ptr); - - bool rgba = info_ptr->color_type == PNG_COLOR_TYPE_RGBA; - if ( (info_ptr->color_type != PNG_COLOR_TYPE_RGB) && !rgba) { - std::cerr << "Found color type " << (int)info_ptr->color_type << std::endl; - throw Py::RuntimeError("_image_module::readpng: cannot handle color_type"); - } - - /* read file */ - if (setjmp(png_jmpbuf(png_ptr))) - throw Py::RuntimeError("_image_module::readpng: error during read_image"); - - png_bytep *row_pointers = new png_bytep[height]; - png_uint_32 row; - - for (row = 0; row < height; row++) - row_pointers[row] = new png_byte[png_get_rowbytes(png_ptr,info_ptr)]; - - png_read_image(png_ptr, row_pointers); - - - - int dimensions[3]; - dimensions[0] = height; //numrows - dimensions[1] = width; //numcols - dimensions[2] = 4; - - PyArrayObject *A = (PyArrayObject *) PyArray_FromDims(3, dimensions, PyArray_FLOAT); - - - for (png_uint_32 y = 0; y < height; y++) { - png_byte* row = row_pointers[y]; - for (png_uint_32 x = 0; x < width; x++) { - - png_byte* ptr = (rgba) ? &(row[x*4]) : &(row[x*3]); - size_t offset = y*A->strides[0] + x*A->strides[1]; - //if ((y<10)&&(x==10)) std::cout << "r = " << ptr[0] << " " << ptr[0]/255.0 << std::endl; - *(float*)(A->data + offset + 0*A->strides[2]) = (float)(ptr[0]/255.0f); - *(float*)(A->data + offset + 1*A->strides[2]) = (float)(ptr[1]/255.0f); - *(float*)(A->data + offset + 2*A->strides[2]) = (float)(ptr[2]/255.0f); - *(float*)(A->data + offset + 3*A->strides[2]) = rgba ? (float)(ptr[3]/255.0f) : 1.0f; - } - } - - //free the png memory - png_read_end(png_ptr, info_ptr); - png_destroy_read_struct(&png_ptr, &info_ptr, png_infopp_NULL); - fclose(fp); - for (row = 0; row < height; row++) - delete [] row_pointers[row]; - delete [] row_pointers; - return Py::asObject((PyObject*)A); -} - - char _image_module_fromarray__doc__[] = "fromarray(A, isoutput)\n" "\n" Modified: trunk/matplotlib/src/_image.h =================================================================== --- trunk/matplotlib/src/_image.h 2008-06-11 15:31:21 UTC (rev 5470) +++ trunk/matplotlib/src/_image.h 2008-06-11 15:49:11 UTC (rev 5471) @@ -38,7 +38,6 @@ Py::Object get_interpolation(const Py::Tuple& args); Py::Object set_interpolation(const Py::Tuple& args); Py::Object set_aspect(const Py::Tuple& args); - Py::Object write_png(const Py::Tuple& args); Py::Object set_bg(const Py::Tuple& args); Py::Object flipud_out(const Py::Tuple& args); Py::Object flipud_in(const Py::Tuple& args); @@ -100,7 +99,6 @@ static char get_interpolation__doc__[]; static char set_interpolation__doc__[]; static char set_aspect__doc__[]; - static char write_png__doc__[]; static char set_bg__doc__[]; static char flipud_out__doc__[]; static char flipud_in__doc__[]; @@ -133,8 +131,6 @@ "frombyte"); add_varargs_method("frombuffer", &_image_module::frombuffer, "frombuffer"); - add_varargs_method("readpng", &_image_module::readpng, - "readpng"); add_varargs_method("from_images", &_image_module::from_images, "from_images"); add_varargs_method("pcolor", &_image_module::pcolor, @@ -153,7 +149,6 @@ Py::Object fromarray2 (const Py::Tuple &args); Py::Object pcolor (const Py::Tuple &args); Py::Object pcolor2 (const Py::Tuple &args); - Py::Object readpng (const Py::Tuple &args); Py::Object from_images (const Py::Tuple &args); static char _image_module_fromarray__doc__[]; Modified: trunk/matplotlib/src/ft2font.cpp =================================================================== --- trunk/matplotlib/src/ft2font.cpp 2008-06-11 15:31:21 UTC (rev 5470) +++ trunk/matplotlib/src/ft2font.cpp 2008-06-11 15:49:11 UTC (rev 5471) @@ -69,7 +69,9 @@ delete _rgbaCopy; } -void FT2Image::resize(unsigned long width, unsigned long height) { +void FT2Image::resize(long width, long height) { + if (width < 0) width = 1; + if (height < 0) height = 1; size_t numBytes = width*height; if (width != _width || height != _height) { Modified: trunk/matplotlib/src/ft2font.h =================================================================== --- trunk/matplotlib/src/ft2font.h 2008-06-11 15:31:21 UTC (rev 5470) +++ trunk/matplotlib/src/ft2font.h 2008-06-11 15:49:11 UTC (rev 5471) @@ -66,7 +66,7 @@ void makeRgbCopy(); void makeRgbaCopy(); - void resize(unsigned long width, unsigned long height); + void resize(long width, long height); }; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ef...@us...> - 2008-06-12 18:05:19
|
Revision: 5489 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5489&view=rev Author: efiring Date: 2008-06-12 11:05:16 -0700 (Thu, 12 Jun 2008) Log Message: ----------- Merged revisions 5488 via svnmerge from https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/v0_91_maint ........ r5488 | efiring | 2008-06-12 08:02:18 -1000 (Thu, 12 Jun 2008) | 2 lines Support hold in quiver, contour, contourf ........ Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/axes.py Property Changed: ---------------- trunk/matplotlib/ Property changes on: trunk/matplotlib ___________________________________________________________________ Name: svnmerge-integrated - /branches/v0_91_maint:1-5443 + /branches/v0_91_maint:1-5443,5488 Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2008-06-12 18:02:18 UTC (rev 5488) +++ trunk/matplotlib/lib/matplotlib/axes.py 2008-06-12 18:05:16 UTC (rev 5489) @@ -4921,6 +4921,7 @@ quiverkey.__doc__ = mquiver.QuiverKey.quiverkey_doc def quiver(self, *args, **kw): + if not self._hold: self.cla() q = mquiver.Quiver(self, *args, **kw) self.add_collection(q, False) self.update_datalim(q.XY) @@ -5578,11 +5579,13 @@ return ret def contour(self, *args, **kwargs): + if not self._hold: self.cla() kwargs['filled'] = False return mcontour.ContourSet(self, *args, **kwargs) contour.__doc__ = mcontour.ContourSet.contour_doc def contourf(self, *args, **kwargs): + if not self._hold: self.cla() kwargs['filled'] = True return mcontour.ContourSet(self, *args, **kwargs) contourf.__doc__ = mcontour.ContourSet.contour_doc This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2008-06-12 19:14:25
|
Revision: 5490 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5490&view=rev Author: jdh2358 Date: 2008-06-12 12:14:21 -0700 (Thu, 12 Jun 2008) Log Message: ----------- added array and png helper funcs to mathtext Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/doc/sphinxext/mathpng.py trunk/matplotlib/lib/matplotlib/mathtext.py trunk/matplotlib/setupext.py trunk/matplotlib/src/ft2font.cpp trunk/matplotlib/src/ft2font.h Added Paths: ----------- trunk/matplotlib/examples/api/mathtext_asarray.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2008-06-12 18:05:16 UTC (rev 5489) +++ trunk/matplotlib/CHANGELOG 2008-06-12 19:14:21 UTC (rev 5490) @@ -1,3 +1,9 @@ +2008-06-12 Added some helper functions to the mathtext parser to + return bitmap arrays or write pngs to make it easier to use + mathtext outside the context of an mpl figure. modified + the mathpng sphinxext to use the mathtext png save + functionality + 2008-06-11 Use matplotlib.mathtext to render math expressions in online docs - MGD Modified: trunk/matplotlib/doc/sphinxext/mathpng.py =================================================================== --- trunk/matplotlib/doc/sphinxext/mathpng.py 2008-06-12 18:05:16 UTC (rev 5489) +++ trunk/matplotlib/doc/sphinxext/mathpng.py 2008-06-12 19:14:21 UTC (rev 5490) @@ -92,17 +92,20 @@ os.system('dvipng -bgTransparent -Ttight --noghostscript -l10 ' + '-o %s math.dvi > /dev/null' % name) + +from matplotlib import rcParams +from matplotlib.mathtext import MathTextParser +rcParams['mathtext.fontset'] = 'cm' +mathtext_parser = MathTextParser("Bitmap") + + # This uses mathtext to render the expression def latex2png(latex, filename): - from matplotlib import rcParams - from matplotlib import _png - from matplotlib.mathtext import MathTextParser - rcParams['mathtext.fontset'] = 'cm' - mathtext_parser = MathTextParser("Bitmap") - ftimage = mathtext_parser.parse("$%s$" % latex, 120) - _png.write_png(ftimage.as_rgba_str(), ftimage.get_width(), - ftimage.get_height(), filename) + if os.path.exists(filename): + return + mathtext_parser.to_png(filename, "$%s$" % latex, dpi=120) + # LaTeX to HTML translation stuff: def latex2html(node, source): inline = isinstance(node.parent, nodes.TextElement) Added: trunk/matplotlib/examples/api/mathtext_asarray.py =================================================================== --- trunk/matplotlib/examples/api/mathtext_asarray.py (rev 0) +++ trunk/matplotlib/examples/api/mathtext_asarray.py 2008-06-12 19:14:21 UTC (rev 5490) @@ -0,0 +1,19 @@ +""" +Load a mathtext image as numpy array +""" + +import numpy as np +import matplotlib.mathtext as mathtext +import matplotlib.pyplot as plt + +parser = mathtext.MathTextParser("Bitmap") + +parser.to_png('test2.png', r'$\left[\left\lfloor\frac{5}{\frac{\left(3\right)}{4}} y\right)\right]$', color='green', fontsize=14, dpi=100) + + +rgba = parser.to_rgba(r'IQ: $\sigma_i=15$', color='blue', fontsize=20, dpi=200) + +fig = plt.figure() +fig.figimage(rgba.astype(float)/255., 100, 100) + +plt.show() Modified: trunk/matplotlib/lib/matplotlib/mathtext.py =================================================================== --- trunk/matplotlib/lib/matplotlib/mathtext.py 2008-06-12 18:05:16 UTC (rev 5489) +++ trunk/matplotlib/lib/matplotlib/mathtext.py 2008-06-12 19:14:21 UTC (rev 5490) @@ -180,7 +180,7 @@ from warnings import warn from numpy import inf, isinf - +import numpy as np from matplotlib.pyparsing import Combine, Group, Optional, Forward, \ Literal, OneOrMore, ZeroOrMore, ParseException, Empty, \ ParseResults, Suppress, oneOf, StringEnd, ParseFatalException, \ @@ -197,6 +197,10 @@ latex_to_standard, tex2uni, latex_to_cmex, stix_virtual_fonts from matplotlib import get_data_path, rcParams + + +import matplotlib.colors as mcolors +import matplotlib._png as _png #################### @@ -2724,3 +2728,74 @@ font_output.mathtext_backend = None return result + + def to_mask(self, texstr, dpi=120, fontsize=14): + """ + return an NxM uint8 alpha ubyte mask array of rasterized tex + + ''texstr'' + A valid mathtext string, eg r'IQ: $\sigma_i=15$' + + ''dpi'' + The dots-per-inch to render the text + + ''fontsize'' + The font size in points + """ + assert(self._output=="bitmap") + prop = FontProperties(size=fontsize) + ftimage = self.parse(texstr, dpi=dpi, prop=prop) + + x = ftimage.as_array() + return x + + def to_rgba(self, texstr, color='black', dpi=120, fontsize=14): + """ + return an NxMx4 RGBA array of ubyte rasterized tex + + ''texstr'' + A valid mathtext string, eg r'IQ: $\sigma_i=15$' + + ''color'' + A valid matplotlib color argument + + ''dpi'' + The dots-per-inch to render the text + + ''fontsize'' + The font size in points + """ + x = self.to_mask(texstr, dpi=dpi, fontsize=fontsize) + + r, g, b = mcolors.colorConverter.to_rgb(color) + RGBA = np.zeros((x.shape[0], x.shape[1], 4), dtype=np.uint8) + RGBA[:,:,0] = int(255*r) + RGBA[:,:,1] = int(255*g) + RGBA[:,:,2] = int(255*b) + RGBA[:,:,3] = x + return RGBA + + def to_png(self, filename, texstr, color='black', dpi=120, fontsize=14): + """ + + ''filename'' + A writable filename or fileobject + + ''texstr'' + A valid mathtext string, eg r'IQ: $\sigma_i=15$' + + ''color'' + A valid matplotlib color argument + + ''dpi'' + The dots-per-inch to render the text + + ''fontsize'' + The font size in points + + """ + + rgba = self.to_rgba(texstr, color=color, dpi=dpi, fontsize=fontsize) + numrows, numcols, tmp = rgba.shape + return _png.write_png(rgba.tostring(), numcols, numrows, filename) + Modified: trunk/matplotlib/setupext.py =================================================================== --- trunk/matplotlib/setupext.py 2008-06-12 18:05:16 UTC (rev 5489) +++ trunk/matplotlib/setupext.py 2008-06-12 19:14:21 UTC (rev 5490) @@ -589,6 +589,7 @@ def add_ft2font_flags(module): 'Add the module flags to ft2font extension' + add_numpy_flags(module) if not get_pkgconfig(module, 'freetype2'): module.libraries.extend(['freetype', 'z']) add_base_flags(module) Modified: trunk/matplotlib/src/ft2font.cpp =================================================================== --- trunk/matplotlib/src/ft2font.cpp 2008-06-12 18:05:16 UTC (rev 5489) +++ trunk/matplotlib/src/ft2font.cpp 2008-06-12 19:14:21 UTC (rev 5490) @@ -2,6 +2,9 @@ #include "mplutils.h" #include <sstream> +#define PY_ARRAY_TYPES_PREFIX NumPy +#include "numpy/arrayobject.h" + #define FIXED_MAJOR(val) (*((short *) &val+1)) #define FIXED_MINOR(val) (*((short *) &val+0)) @@ -251,6 +254,41 @@ ); } +char FT2Image::as_array__doc__[] = +"x = image.as_array()\n" +"\n" +"Return the image buffer as a width x height numpy array of ubyte \n" +"\n" +; +Py::Object +FT2Image::py_as_array(const Py::Tuple & args) { + _VERBOSE("FT2Image::as_array"); + args.verify_length(0); + + int dimensions[2]; + dimensions[0] = get_height(); //numrows + dimensions[1] = get_width(); //numcols + + + PyArrayObject *A = (PyArrayObject *) PyArray_SimpleNewFromData(2, dimensions, PyArray_UBYTE, _buffer); + + /* + + PyArrayObject *A = (PyArrayObject *) PyArray_FromDims(2, dimensions, PyArray_UBYTE); + + + unsigned char *src = _buffer; + unsigned char *src_end = src + (dimensions[0] * dimensions[1]); + unsigned char *dst = (unsigned char *)A->data; + + while (src != src_end) { + *dst++ = *src++; + } + */ + + return Py::asObject((PyObject*)A); +} + void FT2Image::makeRgbCopy() { if (!_isDirty) return; @@ -1697,6 +1735,8 @@ FT2Image::draw_rect__doc__); add_varargs_method("draw_rect_filled", &FT2Image::py_draw_rect_filled, FT2Image::draw_rect_filled__doc__); + add_varargs_method("as_array", &FT2Image::py_as_array, + FT2Image::as_array__doc__); add_varargs_method("as_str", &FT2Image::py_as_str, FT2Image::as_str__doc__); add_varargs_method("as_rgb_str", &FT2Image::py_as_rgb_str, @@ -1834,6 +1874,7 @@ initft2font(void) { static ft2font_module* ft2font = new ft2font_module; + import_array(); Py::Dict d = ft2font->moduleDictionary(); d["SCALABLE"] = Py::Int(FT_FACE_FLAG_SCALABLE); @@ -1885,5 +1926,6 @@ } ft2font_module::~ft2font_module() { + FT_Done_FreeType( _ft2Library ); } Modified: trunk/matplotlib/src/ft2font.h =================================================================== --- trunk/matplotlib/src/ft2font.h 2008-06-12 18:05:16 UTC (rev 5489) +++ trunk/matplotlib/src/ft2font.h 2008-06-12 19:14:21 UTC (rev 5490) @@ -45,6 +45,8 @@ Py::Object py_draw_rect(const Py::Tuple & args); static char draw_rect_filled__doc__ []; Py::Object py_draw_rect_filled(const Py::Tuple & args); + static char as_array__doc__ []; + Py::Object py_as_array(const Py::Tuple & args); static char as_str__doc__ []; Py::Object py_as_str(const Py::Tuple & args); static char as_rgb_str__doc__ []; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2008-06-12 20:01:25
|
Revision: 5495 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5495&view=rev Author: jdh2358 Date: 2008-06-12 13:01:24 -0700 (Thu, 12 Jun 2008) Log Message: ----------- revereted to manual array data fill in ft2font.as_array Modified Paths: -------------- trunk/matplotlib/Makefile trunk/matplotlib/src/ft2font.cpp Modified: trunk/matplotlib/Makefile =================================================================== --- trunk/matplotlib/Makefile 2008-06-12 19:48:23 UTC (rev 5494) +++ trunk/matplotlib/Makefile 2008-06-12 20:01:24 UTC (rev 5495) @@ -32,4 +32,14 @@ CFLAGS="-Os -arch i386 -arch ppc" LDFLAGS="-Os -arch i386 -arch ppc" python setup.py build +jdh_doc_snapshot: + svn up;\ + python setup.py install --prefix=~/dev;\ + cd doc;\ + rm -rf build;\ + python make.py html;\ + python make.py sf + + + Modified: trunk/matplotlib/src/ft2font.cpp =================================================================== --- trunk/matplotlib/src/ft2font.cpp 2008-06-12 19:48:23 UTC (rev 5494) +++ trunk/matplotlib/src/ft2font.cpp 2008-06-12 20:01:24 UTC (rev 5495) @@ -270,10 +270,10 @@ dimensions[1] = get_width(); //numcols - PyArrayObject *A = (PyArrayObject *) PyArray_SimpleNewFromData(2, dimensions, PyArray_UBYTE, _buffer); + //PyArrayObject *A = (PyArrayObject *) PyArray_SimpleNewFromData(2, dimensions, PyArray_UBYTE, _buffer); - /* + PyArrayObject *A = (PyArrayObject *) PyArray_FromDims(2, dimensions, PyArray_UBYTE); @@ -284,8 +284,8 @@ while (src != src_end) { *dst++ = *src++; } - */ + return Py::asObject((PyObject*)A); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2008-06-13 12:46:31
|
Revision: 5502 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5502&view=rev Author: mdboom Date: 2008-06-13 05:46:20 -0700 (Fri, 13 Jun 2008) Log Message: ----------- Correct label location in pie chart. Thanks Benoit Hirbec! Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/axes.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2008-06-13 12:20:35 UTC (rev 5501) +++ trunk/matplotlib/CHANGELOG 2008-06-13 12:46:20 UTC (rev 5502) @@ -1,3 +1,6 @@ +2008-06-13 Change pie chart label alignment to avoid having labels + overwrite the pie - MGD + 2008-06-12 Added some helper functions to the mathtext parser to return bitmap arrays or write pngs to make it easier to use mathtext outside the context of an mpl figure. modified Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2008-06-13 12:20:35 UTC (rev 5501) +++ trunk/matplotlib/lib/matplotlib/axes.py 2008-06-13 12:46:20 UTC (rev 5502) @@ -3953,10 +3953,11 @@ xt = x + labeldistance*radius*math.cos(thetam) yt = y + labeldistance*radius*math.sin(thetam) + label_alignment = xt > 0 and 'left' or 'right' t = self.text(xt, yt, label, size=rcParams['xtick.labelsize'], - horizontalalignment='center', + horizontalalignment=label_alignment, verticalalignment='center') texts.append(t) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2008-06-13 15:05:43
|
Revision: 5508 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5508&view=rev Author: jdh2358 Date: 2008-06-13 08:04:49 -0700 (Fri, 13 Jun 2008) Log Message: ----------- fixed list of backends in the rc template Modified Paths: -------------- trunk/matplotlib/matplotlibrc.template trunk/matplotlib/src/ft2font.cpp Modified: trunk/matplotlib/matplotlibrc.template =================================================================== --- trunk/matplotlib/matplotlibrc.template 2008-06-13 14:57:50 UTC (rev 5507) +++ trunk/matplotlib/matplotlibrc.template 2008-06-13 15:04:49 UTC (rev 5508) @@ -19,8 +19,8 @@ # such as 0.75 - a legal html color name, eg red, blue, darkslategray #### CONFIGURATION BEGINS HERE -# the default backend; one of GTK GTKAgg GTKCairo FltkAgg QtAgg TkAgg -# WX WXAgg Agg Cairo GD GDK Paint PS PDF SVG Template +# the default backend; one of GTK GTKAgg GTKCairo CocoaAgg FltkAgg +# QtAgg Qt4Agg TkAgg WX WXAgg Agg Cairo GDK PS PDF SVG Template backend : %(backend)s numerix : %(numerix)s # numpy, Numeric or numarray #maskedarray : False # True to use external maskedarray module Modified: trunk/matplotlib/src/ft2font.cpp =================================================================== --- trunk/matplotlib/src/ft2font.cpp 2008-06-13 14:57:50 UTC (rev 5507) +++ trunk/matplotlib/src/ft2font.cpp 2008-06-13 15:04:49 UTC (rev 5508) @@ -265,15 +265,15 @@ _VERBOSE("FT2Image::as_array"); args.verify_length(0); - int dimensions[2]; + npy_intp dimensions[2]; dimensions[0] = get_height(); //numrows dimensions[1] = get_width(); //numcols - //PyArrayObject *A = (PyArrayObject *) PyArray_SimpleNewFromData(2, dimensions, PyArray_UBYTE, _buffer); + PyArrayObject *A = (PyArrayObject *) PyArray_SimpleNewFromData(2, dimensions, PyArray_UBYTE, _buffer); + /* - PyArrayObject *A = (PyArrayObject *) PyArray_FromDims(2, dimensions, PyArray_UBYTE); @@ -284,8 +284,8 @@ while (src != src_end) { *dst++ = *src++; } + */ - return Py::asObject((PyObject*)A); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2008-06-13 19:49:21
|
Revision: 5519 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5519&view=rev Author: jdh2358 Date: 2008-06-13 12:49:16 -0700 (Fri, 13 Jun 2008) Log Message: ----------- some updates to the autobuild Modified Paths: -------------- trunk/matplotlib/Makefile trunk/matplotlib/doc/faq/installing_faq.rst trunk/matplotlib/doc/index.rst trunk/matplotlib/doc/make.py trunk/matplotlib/doc/pyplots/text_commands.py trunk/matplotlib/doc/pyplots/text_layout.py trunk/matplotlib/doc/sphinxext/plot_directive.py trunk/matplotlib/lib/matplotlib/cbook.py Modified: trunk/matplotlib/Makefile =================================================================== --- trunk/matplotlib/Makefile 2008-06-13 19:23:21 UTC (rev 5518) +++ trunk/matplotlib/Makefile 2008-06-13 19:49:16 UTC (rev 5519) @@ -37,9 +37,9 @@ python setup.py install --prefix=~/dev;\ cd doc;\ rm -rf build;\ - python make.py html;\ - python make.py sf + python make.py clean html latex sf; + Modified: trunk/matplotlib/doc/faq/installing_faq.rst =================================================================== --- trunk/matplotlib/doc/faq/installing_faq.rst 2008-06-13 19:23:21 UTC (rev 5518) +++ trunk/matplotlib/doc/faq/installing_faq.rst 2008-06-13 19:49:16 UTC (rev 5519) @@ -40,6 +40,12 @@ import matplotlib print matplotlib.get_configdir() + A typical location for the config directory is :file:`.matplotlib`, and the following + caches may need to be cleared after a major update:: + + rm -rf ~/.matplotlib/tex.cache + rm -rf ~/.matplotlib/fontManager.cache + .. _what-is-a-backend: What is a backend? @@ -175,7 +181,7 @@ `sourceforge download <http://sourceforge.net/project/platformdownload.php?group_id=80706>`_ site. Choose the files that match your version of python (eg -``py2.5`` if you instaslled Python 2.5) and have the ``exe`` +``py2.5`` if you installed Python 2.5) which have the ``exe`` extension. If you haven't already installed python, you can get the official version from the `python web site <http://python.org/download/>`_. There are also two packaged Modified: trunk/matplotlib/doc/index.rst =================================================================== --- trunk/matplotlib/doc/index.rst 2008-06-13 19:23:21 UTC (rev 5518) +++ trunk/matplotlib/doc/index.rst 2008-06-13 19:49:16 UTC (rev 5519) @@ -5,6 +5,8 @@ Welcome to matplotlib's documentation! ====================================== +Download `PDF <http://matplotlib.sf.net/doc/Matplotlib.pdf>`_ + Contents: .. toctree:: @@ -22,3 +24,8 @@ * :ref:`modindex` * :ref:`search` + +.. _ipython: http://ipython.scipy.org +.. _numpy: http://numpy.scipy.org +.. _scipy: http://scipy.org +.. _vtk: http://www.vtk.org Modified: trunk/matplotlib/doc/make.py =================================================================== --- trunk/matplotlib/doc/make.py 2008-06-13 19:23:21 UTC (rev 5518) +++ trunk/matplotlib/doc/make.py 2008-06-13 19:49:16 UTC (rev 5519) @@ -17,6 +17,7 @@ def sf(): 'push a copy to the sf site' os.system('cd build; rsync -avz html jd...@ma...:/home/groups/m/ma/matplotlib/htdocs/doc/ -essh') + os.system('cd build/latex; scp Matplotlib.pdf jd...@ma...:/home/groups/m/ma/matplotlib/htdocs/doc/') def figs(): os.system('cd users/figures/ && python make.py') @@ -56,7 +57,8 @@ print 'latex build has not been tested on windows' def clean(): - shutil.rmtree('build') + if os.path.exists('build'): + shutil.rmtree('build') for fname in glob.glob('pyplots/*.png') + glob.glob('pyplots/*.pdf'): os.remove(fname) Modified: trunk/matplotlib/doc/pyplots/text_commands.py =================================================================== --- trunk/matplotlib/doc/pyplots/text_commands.py 2008-06-13 19:23:21 UTC (rev 5518) +++ trunk/matplotlib/doc/pyplots/text_commands.py 2008-06-13 19:49:16 UTC (rev 5519) @@ -5,23 +5,23 @@ fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold') ax = fig.add_subplot(111) - +fig.subplots_adjust(top=0.85) ax.set_title('axes title') ax.set_xlabel('xlabel') ax.set_ylabel('ylabel') -ax.text(5, 8, 'boxed italics text in data coords', style='italic', +ax.text(3, 8, 'boxed italics text in data coords', style='italic', bbox={'facecolor':'red', 'alpha':0.5, 'pad':10}) -ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=20) +ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15) -ax.text(4, 3, unicode('unicode: Institut f\374r Festk\366rperphysik', 'latin-1')) +ax.text(3, 2, unicode('unicode: Institut f\374r Festk\366rperphysik', 'latin-1')) ax.text(0.95, 0.01, 'colored text in axes coords', verticalalignment='bottom', horizontalalignment='right', transform=ax.transAxes, - color='green', fontsize=20) + color='green', fontsize=15) ax.plot([2], [1], 'o') Modified: trunk/matplotlib/doc/pyplots/text_layout.py =================================================================== --- trunk/matplotlib/doc/pyplots/text_layout.py 2008-06-13 19:23:21 UTC (rev 5518) +++ trunk/matplotlib/doc/pyplots/text_layout.py 2008-06-13 19:49:16 UTC (rev 5519) @@ -8,7 +8,7 @@ top = bottom + height fig = plt.figure() -ax = fig.add_subplot(111) +ax = fig.add_axes([0,0,1,1]) # axes coordinates are 0,0 is bottom left and 1,1 is upper right p = patches.Rectangle( Modified: trunk/matplotlib/doc/sphinxext/plot_directive.py =================================================================== --- trunk/matplotlib/doc/sphinxext/plot_directive.py 2008-06-13 19:23:21 UTC (rev 5518) +++ trunk/matplotlib/doc/sphinxext/plot_directive.py 2008-06-13 19:49:16 UTC (rev 5519) @@ -106,7 +106,6 @@ for format, dpi in formats: outname = os.path.join(outdir, '%s.%s' % (basename, format)) plt.savefig(outname, dpi=dpi) - print ' all figures made' def run(arguments, options, state_machine, lineno): reference = directives.uri(arguments[0]) Modified: trunk/matplotlib/lib/matplotlib/cbook.py =================================================================== --- trunk/matplotlib/lib/matplotlib/cbook.py 2008-06-13 19:23:21 UTC (rev 5518) +++ trunk/matplotlib/lib/matplotlib/cbook.py 2008-06-13 19:49:16 UTC (rev 5519) @@ -1031,7 +1031,20 @@ return result +def recursive_remove(path): + if os.path.isdir(path): + for fname in glob.glob(os.path.join(path, '*')) + glob.glob(os.path.join(path, '.*')): + if os.path.isdir(fname): + recursive_remove(fname) + os.removedirs(fname) + else: + os.remove(fname) + #os.removedirs(path) + else: + os.remove(path) + + # a dict to cross-map linestyle arguments _linestyles = [('-', 'solid'), ('--', 'dashed'), This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ds...@us...> - 2008-06-13 20:15:44
|
Revision: 5521 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5521&view=rev Author: dsdale Date: 2008-06-13 13:15:42 -0700 (Fri, 13 Jun 2008) Log Message: ----------- keep static figures with dynamically generated ones, but commit the figures to svn so they will not be auto-generated. This way we can be consistent in the way we include figures using the plot directive Modified Paths: -------------- trunk/matplotlib/doc/devel/documenting_mpl.rst trunk/matplotlib/doc/pyplots/make.py trunk/matplotlib/doc/pyplots/matplotlibrc trunk/matplotlib/doc/users/usetex.rst trunk/matplotlib/lib/matplotlib/__init__.py trunk/matplotlib/lib/matplotlib/rcsetup.py Added Paths: ----------- trunk/matplotlib/doc/pyplots/README trunk/matplotlib/doc/pyplots/tex_demo.hires.png trunk/matplotlib/doc/pyplots/tex_demo.pdf trunk/matplotlib/doc/pyplots/tex_demo.png trunk/matplotlib/doc/pyplots/tex_demo.py trunk/matplotlib/doc/pyplots/tex_unicode_demo.hires.png trunk/matplotlib/doc/pyplots/tex_unicode_demo.pdf trunk/matplotlib/doc/pyplots/tex_unicode_demo.png trunk/matplotlib/doc/pyplots/tex_unicode_demo.py Removed Paths: ------------- trunk/matplotlib/doc/_static/tex_demo.hires.png trunk/matplotlib/doc/_static/tex_demo.pdf trunk/matplotlib/doc/_static/tex_demo.png trunk/matplotlib/doc/_static/tex_unicode_demo.hires.png trunk/matplotlib/doc/_static/tex_unicode_demo.pdf trunk/matplotlib/doc/_static/tex_unicode_demo.png trunk/matplotlib/doc/static_figs/README trunk/matplotlib/doc/static_figs/make.py Deleted: trunk/matplotlib/doc/_static/tex_demo.hires.png =================================================================== (Binary files differ) Deleted: trunk/matplotlib/doc/_static/tex_demo.pdf =================================================================== --- trunk/matplotlib/doc/_static/tex_demo.pdf 2008-06-13 19:56:24 UTC (rev 5520) +++ trunk/matplotlib/doc/_static/tex_demo.pdf 2008-06-13 20:15:42 UTC (rev 5521) @@ -1,2834 +0,0 @@ -%PDF-1.4 -%\xAC\xDC \xAB\xBA -1 0 obj -<< /Type /Catalog /Pages 3 0 R >> -endobj -2 0 obj -<< /CreationDate (D:20080613135832-04'00') -/Producer (matplotlib pdf backend) -/Creator (matplotlib 0.98.0, http://matplotlib.sf.net) >> -endobj -3 0 obj -<< /Count 1 /Kids [ 4 0 R ] /Type /Pages >> -endobj -4 0 obj -<< /Contents 5 0 R /Type /Page /Resources 10 0 R /Parent 3 0 R -/MediaBox [ 0 0 432 288 ] >> -endobj -10 0 obj -<< /Pattern 8 0 R /XObject 9 0 R /Font 6 0 R /ExtGState 7 0 R -/ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> -endobj -5 0 obj -<< /Filter /FlateDecode /Length 11 0 R >> -stream -x\x9C\xCDYM\x8F]5\x9D\xB5\xFF\xC1\xEC\xCC.Yĩ\xBB\Fb\x83"Eb$\xA0H\xC0\x82\x8F2J\x830\xFC\xFD9\xF6}/\xFD\x9E}\xE9<u\xA4\xCE,\x92n\xFB\x96\xCB\xF6\xA9\xE3Se\xB7ħ\x91\xE3s\xFC{(R\xBC\x8EY?_\x8E\x9F\xE2\x8E\xDF\xE8\xF5O\xF4\x87a\xF7$dM\xFDsr\x8CP\xEF?G\xE3屡\x94\xF2p\xD2\xCD\xCE\xC3^~;ik.ɢ\xE3\xFFW\xCF\xE2\x97\xF1\x971\xC7ώ3 -X\x9C%+\xB0\x94\x96\x8C -{\x93ׅ3̤&Qe\xCB\xDCWS4\xF3 \xA2I\x85\xB3\xB5Z밯\x89$Gᚚre\xD5\xEC}\x89\x86i\xB0z\xE6\xC4\xD9+\xA9\xF6^\x85\x95!M\xE4DZ-g\xEE\xFD5i\x93\xC8M\x93\xCC\xEBlV\xD1_)9ܰk2f\xCD\xD4T[\xEF\xCFI)\xAE\x92 -{)R\xBC\xF5U֚\xAAE\xC6\xE4\xF5dV\xE7$\x8C\xEE\xECX\x93\x93Za\x92ޟ\x93U \xAC%5i\xE2Yͭ\xF7{b\xC1\xACثT\xAA\L\xB9\xEF\xA9q*\xD83\xDC37\xC3VǬ\xAD$,\xA6\xC1;\xBB\xB5\xB1\xF4\xDEl8;\xE7\\xF36'#4\xADH\xAC\xBE\xDCJ#3\xFD%e\xF2`%i\xAE\xE8sk\x87\xC3\xE4\x96c1ĥ5-\xA5#\x80 ![\xA2\x93I\x99K\xAA\xD5BƎ\xCD\xC5 -[\xB5\xD1\xDFN\x89ةW/J"#\xDA,\x82\xE5\x816X\x94a\x9DU\x8B\x8FU -\xA6\xCB9\x80\xA5eG<\xA8n\xF6\xAD\xD3k#(b\x8D\xC9ќ\x8D\xD49wzC\x87\xAF\x8B |
From: <jd...@us...> - 2008-06-13 20:54:20
|
Revision: 5524 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5524&view=rev Author: jdh2358 Date: 2008-06-13 13:54:18 -0700 (Fri, 13 Jun 2008) Log Message: ----------- tried some svg and ps extensions but bailing for now because of usetex issues Modified Paths: -------------- trunk/matplotlib/Makefile trunk/matplotlib/doc/sphinxext/plot_directive.py trunk/matplotlib/doc/users/customizing.rst trunk/matplotlib/doc/users/pyplot_tutorial.rst Modified: trunk/matplotlib/Makefile =================================================================== --- trunk/matplotlib/Makefile 2008-06-13 20:40:36 UTC (rev 5523) +++ trunk/matplotlib/Makefile 2008-06-13 20:54:18 UTC (rev 5524) @@ -37,7 +37,9 @@ python setup.py install --prefix=~/dev;\ cd doc;\ rm -rf build;\ - python make.py clean html latex sf; + python make.py clean;\ + svn up;\ + python make.py html latex sf; Modified: trunk/matplotlib/doc/sphinxext/plot_directive.py =================================================================== --- trunk/matplotlib/doc/sphinxext/plot_directive.py 2008-06-13 20:40:36 UTC (rev 5523) +++ trunk/matplotlib/doc/sphinxext/plot_directive.py 2008-06-13 20:54:18 UTC (rev 5524) @@ -45,7 +45,7 @@ [ `<../%(srcdir)s/%(reference)s>`__, `png <../%(srcdir)s/%(basename)s.hires.png>`__, - `pdf <../%(srcdir)s/%(basename)s.pdf>`__ ] + `pdf <../%(srcdir)s/%(basename)s.pdf>`__] .. image:: ../%(srcdir)s/%(basename)s.png %(options)s @@ -64,7 +64,7 @@ [ `py <../%(srcdir)s/%(reference)s>`__, `png <../%(srcdir)s/%(basename)s.hires.png>`__, - `pdf <../%(srcdir)s/%(basename)s.pdf>`__ ] + `pdf <../%(srcdir)s/%(basename)s.pdf>`__] .. image:: ../%(srcdir)s/%(basename)s.png %(options)s @@ -83,7 +83,8 @@ fullpath = str(fullpath) # todo, why is unicode breaking this formats = [('png', 100), ('hires.png', 200), - ('pdf', 72)] + ('pdf', 72), + ] basedir, fname = os.path.split(fullpath) basename, ext = os.path.splitext(fname) @@ -105,8 +106,10 @@ mplshell.magic_run(fullpath) for format, dpi in formats: outname = os.path.join(outdir, '%s.%s' % (basename, format)) + if os.path.exists(outname): continue plt.savefig(outname, dpi=dpi) + def run(arguments, options, state_machine, lineno): reference = directives.uri(arguments[0]) basename, ext = os.path.splitext(reference) Modified: trunk/matplotlib/doc/users/customizing.rst =================================================================== --- trunk/matplotlib/doc/users/customizing.rst 2008-06-13 20:40:36 UTC (rev 5523) +++ trunk/matplotlib/doc/users/customizing.rst 2008-06-13 20:54:18 UTC (rev 5524) @@ -6,8 +6,8 @@ .. _customizing-with-matplotlibrc-files: -The matplotlibrc File -===================== +The :file:`matplotlibrc` file +============================= matplotlib uses :file:`matplotlibrc` configuration files to customize all kinds of properties, which we call `rc settings` or `rc parameters`. You can control Modified: trunk/matplotlib/doc/users/pyplot_tutorial.rst =================================================================== --- trunk/matplotlib/doc/users/pyplot_tutorial.rst 2008-06-13 20:40:36 UTC (rev 5523) +++ trunk/matplotlib/doc/users/pyplot_tutorial.rst 2008-06-13 20:54:18 UTC (rev 5524) @@ -5,7 +5,7 @@ *************** :mod:`matplotlib.pyplot` is a collection of command style functions -that make matplotlib work like matlab. Each ``pyplot`` function makes +that make matplotlib work like matlab. Each ``pyplot`` function makes some change to a figure: eg, create a figure, create a plotting area in a figure, plot some lines in a plotting area, decorate the plot with labels, etc.... :mod:`matplotlib.pyplot` is stateful, in that it This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ds...@us...> - 2008-06-15 23:05:37
|
Revision: 5550 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5550&view=rev Author: dsdale Date: 2008-06-15 16:05:34 -0700 (Sun, 15 Jun 2008) Log Message: ----------- add axis and cbook to api reference Modified Paths: -------------- trunk/matplotlib/doc/api/index.rst trunk/matplotlib/lib/matplotlib/axis.py trunk/matplotlib/lib/matplotlib/cbook.py Modified: trunk/matplotlib/doc/api/index.rst =================================================================== --- trunk/matplotlib/doc/api/index.rst 2008-06-15 20:38:00 UTC (rev 5549) +++ trunk/matplotlib/doc/api/index.rst 2008-06-15 23:05:34 UTC (rev 5550) @@ -14,5 +14,7 @@ matplotlib_configuration_api.rst artist_api.rst axes_api.rst + axis_api.rst + cbook_api.rst pyplot_api.rst index_backend_api.rst Modified: trunk/matplotlib/lib/matplotlib/axis.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axis.py 2008-06-15 20:38:00 UTC (rev 5549) +++ trunk/matplotlib/lib/matplotlib/axis.py 2008-06-15 23:05:34 UTC (rev 5550) @@ -23,19 +23,38 @@ 1 refers to the bottom of the plot for xticks and the left for yticks 2 refers to the top of the plot for xticks and the right for yticks - Publicly accessible attributes + Publicly accessible attributes: - tick1line : a Line2D instance - tick2line : a Line2D instance - gridline : a Line2D instance - label1 : a Text instance - label2 : a Text instance - gridOn : a boolean which determines whether to draw the tickline - tick1On : a boolean which determines whether to draw the 1st tickline - tick2On : a boolean which determines whether to draw the 2nd tickline - label1On : a boolean which determines whether to draw tick label - label2On : a boolean which determines whether to draw tick label + :attr:`tick1line` + a Line2D instance + :attr:`tick2line` + a Line2D instance + + :attr:`gridline` + a Line2D instance + + :attr:`label1` + a Text instance + + :attr:`label2` + a Text instance + + :attr:`gridOn` + a boolean which determines whether to draw the tickline + + :attr:`tick1On` + a boolean which determines whether to draw the 1st tickline + + :attr:`tick2On` + a boolean which determines whether to draw the 2nd tickline + + :attr:`label1On` + a boolean which determines whether to draw tick label + + :attr:`label2On` + a boolean which determines whether to draw tick label + """ def __init__(self, axes, loc, label, size = None, # points @@ -111,7 +130,8 @@ return self.figure.dpi * self._pad / 72.0 def contains(self, mouseevent): - """Test whether the mouse event occured in the Tick marks. + """ + Test whether the mouse event occured in the Tick marks. This function always returns false. It is more useful to test if the axis as a whole contains the mouse rather than the set of tick marks. Modified: trunk/matplotlib/lib/matplotlib/cbook.py =================================================================== --- trunk/matplotlib/lib/matplotlib/cbook.py 2008-06-15 20:38:00 UTC (rev 5549) +++ trunk/matplotlib/lib/matplotlib/cbook.py 2008-06-15 23:05:34 UTC (rev 5550) @@ -40,7 +40,7 @@ class todatetime(converter): 'convert to a datetime or None' def __init__(self, fmt='%Y-%m-%d', missing='Null', missingval=None): - 'use a time.strptime format string for conversion' + 'use a :func:`time.strptime` format string for conversion' converter.__init__(self, missing, missingval) self.fmt = fmt @@ -54,7 +54,7 @@ class todate(converter): 'convert to a date or None' def __init__(self, fmt='%Y-%m-%d', missing='Null', missingval=None): - 'use a time.strptime format string for conversion' + 'use a :func:`time.strptime` format string for conversion' converter.__init__(self, missing, missingval) self.fmt = fmt def __call__(self, s): @@ -84,7 +84,7 @@ class CallbackRegistry: """ Handle registering and disconnecting for a set of signals and - callbacks + callbacks:: signals = 'eat', 'drink', 'be merry' @@ -109,7 +109,7 @@ """ def __init__(self, signals): - 'signals is a sequence of valid signals' + '*signals* is a sequence of valid signals' self.signals = set(signals) # callbacks is a dict mapping the signal to a dictionary # mapping callback id to the callback function @@ -117,7 +117,7 @@ self._cid = 0 def _check_signal(self, s): - 'make sure s is a valid signal or raise a ValueError' + 'make sure *s* is a valid signal or raise a ValueError' if s not in self.signals: signals = list(self.signals) signals.sort() @@ -125,7 +125,7 @@ def connect(self, s, func): """ - register func to be called when a signal s is generated + register *func* to be called when a signal *s* is generated func will be called """ self._check_signal(s) @@ -135,7 +135,7 @@ def disconnect(self, cid): """ - disconnect the callback registered with callback id cid + disconnect the callback registered with callback id *cid* """ for eventname, callbackd in self.callbacks.items(): try: del callbackd[cid] @@ -144,8 +144,8 @@ def process(self, s, *args, **kwargs): """ - process signal s. All of the functions registered to receive - callbacks on s will be called with *args and **kwargs + process signal *s*. All of the functions registered to receive + callbacks on *s* will be called with *\*args* and *\*\*kwargs* """ self._check_signal(s) for func in self.callbacks[s].values(): @@ -194,42 +194,42 @@ def unique(x): - 'Return a list of unique elements of x' + 'Return a list of unique elements of *x*' return dict([ (val, 1) for val in x]).keys() def iterable(obj): - 'return true if obj is iterable' + 'return true if *obj* is iterable' try: len(obj) except: return 0 return 1 def is_string_like(obj): - 'return true if obj looks like a string' + 'return true if *obj* looks like a string' if hasattr(obj, 'shape'): return 0 try: obj + '' except (TypeError, ValueError): return 0 return 1 def is_writable_file_like(obj): - 'return true if obj looks like a file object' + 'return true if *obj* looks like a file object' return hasattr(obj, 'write') and callable(obj.write) def is_scalar(obj): - 'return true if ob is not string like and is not iterable' + 'return true if *obj* is not string like and is not iterable' return is_string_like(obj) or not iterable(obj) def is_numlike(obj): - 'return true if obj looks like a number' + 'return true if *obj* looks like a number' try: obj+1 except TypeError: return False else: return True def to_filehandle(fname, flag='r', return_opened=False): """ - fname can be a filename or a file handle. Support for gzipped - files is automatic, if the filename ends in .gz. flag is a - read/write flag for file + *fname* can be a filename or a file handle. Support for gzipped + files is automatic, if the filename ends in .gz. *flag* is a + read/write flag for :func:`file` """ if is_string_like(fname): if fname.endswith('.gz'): @@ -275,18 +275,19 @@ Sort by attribute or item - Example usage: - sort = Sorter() + Example usage:: - list = [(1, 2), (4, 8), (0, 3)] - dict = [{'a': 3, 'b': 4}, {'a': 5, 'b': 2}, {'a': 0, 'b': 0}, - {'a': 9, 'b': 9}] + sort = Sorter() + list = [(1, 2), (4, 8), (0, 3)] + dict = [{'a': 3, 'b': 4}, {'a': 5, 'b': 2}, {'a': 0, 'b': 0}, + {'a': 9, 'b': 9}] - sort(list) # default sort - sort(list, 1) # sort by index 1 - sort(dict, 'a') # sort a list of dicts by key 'a' + sort(list) # default sort + sort(list, 1) # sort by index 1 + sort(dict, 'a') # sort a list of dicts by key 'a' + """ def _helper(self, data, aux, inplace): @@ -324,19 +325,19 @@ """ All-in-one multiple-string-substitution class - Example usage: + Example usage:: - text = "Larry Wall is the creator of Perl" - adict = { - "Larry Wall" : "Guido van Rossum", - "creator" : "Benevolent Dictator for Life", - "Perl" : "Python", - } + text = "Larry Wall is the creator of Perl" + adict = { + "Larry Wall" : "Guido van Rossum", + "creator" : "Benevolent Dictator for Life", + "Perl" : "Python", + } - print multiple_replace(adict, text) + print multiple_replace(adict, text) - xlat = Xlator(adict) - print xlat.xlat(text) + xlat = Xlator(adict) + print xlat.xlat(text) """ def _make_regex(self): @@ -344,11 +345,11 @@ return re.compile("|".join(map(re.escape, self.keys()))) def __call__(self, match): - """ Handler invoked for each regex match """ + """ Handler invoked for each regex *match* """ return self[match.group(0)] def xlat(self, text): - """ Translate text, returns the modified text. """ + """ Translate *text*, returns the modified text. """ return self._make_regex().sub(self, text) @@ -424,7 +425,7 @@ get_realpath_and_stat = GetRealpathAndStat() def dict_delall(d, keys): - 'delete all of the keys from the dict d' + 'delete all of the *keys* from the :class:`dict` *d*' for key in keys: try: del d[key] except KeyError: pass @@ -464,10 +465,13 @@ def get_split_ind(seq, N): - """seq is a list of words. Return the index into seq such that - len(' '.join(seq[:ind])<=N """ + *seq* is a list of words. Return the index into seq such that:: + len(' '.join(seq[:ind])<=N + + """ + sLen = 0 # todo: use Alex's xrange pattern from the cbook for efficiency for (word, ind) in zip(seq, range(len(seq))): @@ -477,7 +481,7 @@ def wrap(prefix, text, cols): - 'wrap text with prefix at length cols' + 'wrap *text* with *prefix* at length *cols*' pad = ' '*len(prefix.expandtabs()) available = cols - len(pad) @@ -504,14 +508,13 @@ _dedent_regex = {} def dedent(s): """ - Remove excess indentation from docstrings. + Remove excess indentation from docstring *s*. - Discards any leading blank lines, then removes up to - n whitespace characters from each line, where n is - the number of leading whitespace characters in the - first line. It differs from textwrap.dedent in its - deletion of leading blank lines and its use of the - first non-blank line to determine the indentation. + Discards any leading blank lines, then removes up to n whitespace + characters from each line, where n is the number of leading + whitespace characters in the first line. It differs from + textwrap.dedent in its deletion of leading blank lines and its use + of the first non-blank line to determine the indentation. It is also faster in most cases. """ @@ -546,6 +549,7 @@ def listFiles(root, patterns='*', recurse=1, return_folders=0): """ Recursively list files + from Parmar and Martelli in the Python Cookbook """ import os.path, fnmatch @@ -575,8 +579,8 @@ def get_recursive_filelist(args): """ - Recurs all the files and dirs in args ignoring symbolic links and - return the files as a list of strings + Recurs all the files and dirs in *args* ignoring symbolic links + and return the files as a list of strings """ files = [] @@ -593,7 +597,7 @@ def pieces(seq, num=2): - "Break up the seq into num tuples" + "Break up the *seq* into *num* tuples" start = 0 while 1: item = seq[start:start+num] @@ -611,8 +615,8 @@ def allequal(seq): """ - return true if all elements of seq compare equal. If seq is 0 or - 1 length, return True + return true if all elements of *seq* compare equal. If *seq* is 0 + or 1 length, return *True* """ if len(seq)<2: return True val = seq[0] @@ -637,10 +641,11 @@ def allpairs(x): """ - return all possible pairs in sequence x + return all possible pairs in sequence *x* - Condensed by Alex Martelli from this thread on c.l.python - http://groups.google.com/groups?q=all+pairs+group:*python*&hl=en&lr=&ie=UTF-8&selm=mailman.4028.1096403649.5135.python-list%40python.org&rnum=1 + Condensed by Alex Martelli from this thread_ on c.l.python + + .. _thread: http://groups.google.com/groups?q=all+pairs+group:*python*&hl=en&lr=&ie=UTF-8&selm=mailman.4028.1096403649.5135.python-list%40python.org&rnum=1 """ return [ (s, f) for i, f in enumerate(x) for s in x[i+1:] ] @@ -650,15 +655,17 @@ # python 2.2 dicts don't have pop--but we don't support 2.2 any more def popd(d, *args): """ - Should behave like python2.3 pop method; d is a dict + Should behave like python2.3 :meth:`dict.pop` method; *d* is a + :class:`dict`:: - # returns value for key and deletes item; raises a KeyError if key - # is not in dict - val = popd(d, key) + # returns value for key and deletes item; raises a KeyError if key + # is not in dict + val = popd(d, key) - # returns value for key if key exists, else default. Delete key, - # val item if it exists. Will not raise a KeyError - val = popd(d, key, default) + # returns value for key if key exists, else default. Delete key, + # val item if it exists. Will not raise a KeyError + val = popd(d, key, default) + """ if len(args)==1: key = args[0] @@ -744,8 +751,8 @@ def bubble(self, o): """ - raise o to the top of the stack and return o. o must be in - the stack + raise *o* to the top of the stack and return *o*. *o* must be + in the stack """ if o not in self._elements: @@ -761,7 +768,7 @@ return o def remove(self, o): - 'remove element o from the stack' + 'remove element *o* from the stack' if o not in self._elements: raise ValueError('Unknown element o') old = self._elements[:] @@ -776,7 +783,7 @@ def finddir(o, match, case=False): """ - return all attributes of o which match string in match. if case + return all attributes of *o* which match string in match. if case is True require an exact case match. """ if case: @@ -787,7 +794,7 @@ return [orig for name, orig in names if name.find(match)>=0] def reverse_dict(d): - 'reverse the dictionary -- may lose data if values are not uniq!' + 'reverse the dictionary -- may lose data if values are not unique!' return dict([(v,k) for k,v in d.items()]) @@ -808,7 +815,7 @@ _safezip_msg = 'In safezip, len(args[0])=%d but len(args[%d])=%d' def safezip(*args): - 'make sure args are equal len before zipping' + 'make sure *args* are equal len before zipping' Nx = len(args[0]) for i, arg in enumerate(args[1:]): if len(arg) != Nx: @@ -870,12 +877,16 @@ def print_cycles(objects, outstream=sys.stdout, show_progress=False): """ - objects: A list of objects to find cycles in. It is often useful - to pass in gc.garbage to find the cycles that are - preventing some objects from being garbage collected. - outstream: The stream for output. - show_progress: If True, print the number of objects reached as they are - found. + *objects* + A list of objects to find cycles in. It is often useful to + pass in gc.garbage to find the cycles that are preventing some + objects from being garbage collected. + + *outstream* + The stream for output. + + *show_progress* + If True, print the number of objects reached as they are found. """ import gc from types import FrameType @@ -936,9 +947,9 @@ together into disjoint sets when a full-blown graph data structure would be overkill. - Objects can be joined using .join(), tested for connectedness - using .joined(), and all disjoint sets can be retreived using - .get(). + Objects can be joined using :meth:`join`, tested for connectedness + using :meth:`joined`, and all disjoint sets can be retreived using + :meth:`get`. The objects being joined must be hashable. @@ -987,7 +998,7 @@ def joined(self, a, b): """ - Returns True if a and b are members of the same set. + Returns True if *a* and *b* are members of the same set. """ mapping = self._mapping try: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ds...@us...> - 2008-06-15 23:53:18
|
Revision: 5551 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5551&view=rev Author: dsdale Date: 2008-06-15 16:53:06 -0700 (Sun, 15 Jun 2008) Log Message: ----------- added cm and collections to api reference Modified Paths: -------------- trunk/matplotlib/doc/api/index.rst trunk/matplotlib/lib/matplotlib/cm.py trunk/matplotlib/lib/matplotlib/collections.py Modified: trunk/matplotlib/doc/api/index.rst =================================================================== --- trunk/matplotlib/doc/api/index.rst 2008-06-15 23:05:34 UTC (rev 5550) +++ trunk/matplotlib/doc/api/index.rst 2008-06-15 23:53:06 UTC (rev 5551) @@ -16,5 +16,7 @@ axes_api.rst axis_api.rst cbook_api.rst + cm_api.rst + collections_api.rst pyplot_api.rst index_backend_api.rst Modified: trunk/matplotlib/lib/matplotlib/cm.py =================================================================== --- trunk/matplotlib/lib/matplotlib/cm.py 2008-06-15 23:05:34 UTC (rev 5550) +++ trunk/matplotlib/lib/matplotlib/cm.py 2008-06-15 23:53:06 UTC (rev 5551) @@ -13,7 +13,7 @@ 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 """ if name is None: name = mpl.rcParams['image.cmap'] if lut is None: lut = mpl.rcParams['image.lut'] @@ -29,8 +29,9 @@ def __init__(self, norm=None, cmap=None): """ - norm is a colors.normalize instance to map luminance to 0-1 - cmap is a cm colormap instance + *norm* is an instance of :class:`colors.Normalize` or one of + its subclasses, used to map luminance to 0-1. *cmap* is a + :mod:`cm` colormap instance, for example :data:`cm.jet` """ self.callbacksSM = cbook.CallbackRegistry(( @@ -50,10 +51,10 @@ self.colorbar = im, ax def to_rgba(self, x, alpha=1.0, bytes=False): - '''Return a normalized rgba array corresponding to x. - If x is already an rgb array, insert alpha; if it is - already rgba, return it unchanged. - If bytes is True, return rgba as 4 uint8s instead of 4 floats. + '''Return a normalized rgba array corresponding to *x*. If *x* + is already an rgb array, insert *alpha*; if it is already + rgba, return it unchanged. If *bytes* is True, return rgba as + 4 uint8s instead of 4 floats. ''' try: if x.ndim == 3: @@ -79,7 +80,7 @@ return x def set_array(self, A): - 'Set the image array from numpy array A' + 'Set the image array from numpy array *A*' self._A = A self.update_dict['array'] = True @@ -97,8 +98,8 @@ def set_clim(self, vmin=None, vmax=None): """ - set the norm limits for image scaling; if vmin is a length2 - sequence, interpret it as (vmin, vmax) which is used to + set the norm limits for image scaling; if *vmin* is a length2 + sequence, interpret it as ``(vmin, vmax)`` which is used to support setp ACCEPTS: a length 2 sequence of floats Modified: trunk/matplotlib/lib/matplotlib/collections.py =================================================================== --- trunk/matplotlib/lib/matplotlib/collections.py 2008-06-15 23:05:34 UTC (rev 5550) +++ trunk/matplotlib/lib/matplotlib/collections.py 2008-06-15 23:53:06 UTC (rev 5551) @@ -1,10 +1,11 @@ """ Classes for the efficient drawing of large collections of objects that -share most properties, eg a large number of line segments or polygons +share most properties, e.g. a large number of line segments or +polygons. The classes are not meant to be as flexible as their single element -counterparts (eg you may not be able to select all line styles) but -they are meant to be fast for common use cases (eg a bunch of solid +counterparts (e.g. you may not be able to select all line styles) but +they are meant to be fast for common use cases (e.g. a bunch of solid line segemnts) """ import math, warnings @@ -24,32 +25,34 @@ All properties in a collection must be sequences or scalars; if scalars, they will be converted to sequences. The - property of the ith element of the collection is the + property of the ith element of the collection is:: - prop[i % len(props)]. + prop[i % len(props)] - kwargs are: + Keyword arguments and default values: - edgecolors=None, - facecolors=None, - linewidths=None, - antialiaseds = None, - offsets = None, - transOffset = transforms.IdentityTransform(), - norm = None, # optional for cm.ScalarMappable - cmap = None, # ditto + * *edgecolors*: None + * *facecolors*: None + * *linewidths*: None + * *antialiaseds*: None + * *offsets*: None + * *transOffset*: transforms.IdentityTransform() + * *norm*: None (optional for + :class:`matplotlib.cm.ScalarMappable`) + * *cmap*: None (optional for + :class:`matplotlib.cm.ScalarMappable`) - offsets and transOffset are used to translate the patch after - rendering (default no offsets) + *offsets* and *transOffset* are used to translate the patch after + rendering (default no offsets). - If any of edgecolors, facecolors, linewidths, antialiaseds are - None, they default to their patch.* rc params setting, in sequence - form. + If any of *edgecolors*, *facecolors*, *linewidths*, *antialiaseds* + are None, they default to their :data:`matplotlib.rcParams` patch + setting, in sequence form. - The use of ScalarMappable is optional. If the ScalarMappable - matrix _A is not None (ie a call to set_array has been made), at - draw time a call to scalar mappable will be made to set the face - colors. + The use of :class:`~matplotlib.cm.ScalarMappable` is optional. If + the :class:`~matplotlib.cm.ScalarMappable` matrix _A is not None + (ie a call to set_array has been made), at draw time a call to + scalar mappable will be made to set the face colors. """ _offsets = np.array([], np.float_) _transOffset = transforms.IdentityTransform() @@ -193,7 +196,8 @@ """ Test whether the mouse event occurred in the collection. - Returns T/F, dict(ind=itemlist), where every item in itemlist contains the event. + Returns True | False, ``dict(ind=itemlist)``, where every + item in itemlist contains the event. """ if callable(self._contains): return self._contains(self,mouseevent) @@ -215,9 +219,9 @@ def set_linewidths(self, lw): """ - Set the linewidth(s) for the collection. lw can be a scalar or a - sequence; if it is a sequence the patches will cycle through the - sequence + Set the linewidth(s) for the collection. *lw* can be a scalar + or a sequence; if it is a sequence the patches will cycle + through the sequence ACCEPTS: float or sequence of floats """ @@ -228,7 +232,7 @@ def set_linestyles(self, ls): """ Set the linestyles(s) for the collection. - ACCEPTS: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq) ] + ACCEPTS: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq) ] """ try: dashd = backend_bases.GraphicsContextBase.dashd @@ -280,7 +284,7 @@ def set_color(self, c): """ Set both the edgecolor and the facecolor. - See set_facecolor and set_edgecolor. + See :meth:`set_facecolor` and :meth:`set_edgecolor`. ACCEPTS: matplotlib color arg or sequence of rgba tuples """ @@ -289,10 +293,10 @@ def set_facecolor(self, c): """ - Set the facecolor(s) of the collection. c can be a matplotlib - color arg (all patches have same color), or a a sequence or - rgba tuples; if it is a sequence the patches will cycle - through the sequence + Set the facecolor(s) of the collection. *c* can be a + matplotlib color arg (all patches have same color), or a + sequence or rgba tuples; if it is a sequence the patches will + cycle through the sequence ACCEPTS: matplotlib color arg or sequence of rgba tuples """ @@ -307,9 +311,10 @@ def set_edgecolor(self, c): """ - Set the edgecolor(s) of the collection. c can be a matplotlib color - arg (all patches have same color), or a a sequence or rgba tuples; if - it is a sequence the patches will cycle through the sequence + Set the edgecolor(s) of the collection. *c* can be a + matplotlib color arg (all patches have same color), or a + sequence or rgba tuples; if it is a sequence the patches will + cycle through the sequence ACCEPTS: matplotlib color arg or sequence of rgba tuples """ @@ -320,7 +325,7 @@ def set_alpha(self, alpha): """ - Set the alpha tranparencies of the collection. Alpha must be + Set the alpha tranparencies of the collection. *alpha* must be a float. ACCEPTS: float @@ -364,23 +369,25 @@ # class is built so we define an initial set here for the init # function and they will be overridden after object defn artist.kwdocd['Collection'] = """\ - Valid Collection kwargs are: + Valid Collection keyword arguments: - edgecolors=None, - facecolors=None, - linewidths=None, - antialiaseds = None, - offsets = None, - transOffset = transforms.IdentityTransform(), - norm = None, # optional for cm.ScalarMappable - cmap = None, # ditto + * *edgecolors*: None + * *facecolors*: None + * *linewidths*: None + * *antialiaseds*: None + * *offsets*: None + * *transOffset*: transforms.IdentityTransform() + * *norm*: None (optional for + :class:`matplotlib.cm.ScalarMappable`) + * *cmap*: None (optional for + :class:`matplotlib.cm.ScalarMappable`) - offsets and transOffset are used to translate the patch after + *offsets* and *transOffset* are used to translate the patch after rendering (default no offsets) - If any of edgecolors, facecolors, linewidths, antialiaseds are - None, they default to their patch.* rc params setting, in sequence - form. + If any of *edgecolors*, *facecolors*, *linewidths*, *antialiaseds* + are None, they default to their :data:`matplotlib.rcParams` patch + setting, in sequence form. """ class QuadMesh(Collection): @@ -494,11 +501,11 @@ class PolyCollection(Collection): def __init__(self, verts, sizes = None, **kwargs): """ - verts is a sequence of ( verts0, verts1, ...) where verts_i is - a sequence of xy tuples of vertices, or an equivalent - numpy array of shape (nv,2). + *verts* is a sequence of ( *verts0*, *verts1*, ...) where + *verts_i* is a sequence of xy tuples of vertices, or an + equivalent :mod:`numpy` array of shape (nv,2). - sizes gives the area of the circle circumscribing the + *sizes* gives the area of the circle circumscribing the polygon in points^2 %(Collection)s @@ -532,9 +539,12 @@ """ def __init__(self, xranges, yrange, **kwargs): """ - xranges : sequence of (xmin, xwidth) - yrange : ymin, ywidth + *xranges* + sequence of (xmin, xwidth) + *yrange* + ymin, ywidth + %(Collection)s """ ymin, ywidth = yrange @@ -554,34 +564,38 @@ """ Draw a regular polygon with numsides. - * dpi is the figure dpi instance, and is required to do the - area scaling. + *dpi* + the figure dpi instance, and is required to do the + area scaling. - * numsides: the number of sides of the polygon + *numsides* + the number of sides of the polygon - * sizes gives the area of the circle circumscribing the - regular polygon in points^2 + *sizes* + gives the area of the circle circumscribing the + regular polygon in points^2 - * rotation is the rotation of the polygon in radians + *rotation* + the rotation of the polygon in radians %(Collection)s - Example: see examples/dynamic_collection.py for complete example + Example: see :file:`examples/dynamic_collection.py` for + complete example:: - offsets = np.random.rand(20,2) - facecolors = [cm.jet(x) for x in np.random.rand(20)] - black = (0,0,0,1) + offsets = np.random.rand(20,2) + facecolors = [cm.jet(x) for x in np.random.rand(20)] + black = (0,0,0,1) - collection = RegularPolyCollection( - numsides=5, # a pentagon - rotation=0, - sizes=(50,), - facecolors = facecolors, - edgecolors = (black,), - linewidths = (1,), - offsets = offsets, - transOffset = ax.transData, - ) + collection = RegularPolyCollection( + numsides=5, # a pentagon + rotation=0, sizes=(50,), + facecolors = facecolors, + edgecolors = (black,), + linewidths = (1,), + offsets = offsets, + transOffset = ax.transData, + ) """ Collection.__init__(self,**kwargs) self._sizes = sizes @@ -633,42 +647,57 @@ **kwargs ): """ - segments is a sequence of ( line0, line1, line2), where - linen = (x0, y0), (x1, y1), ... (xm, ym), or the - equivalent numpy array with two columns. - Each line can be a different length. + *segments* + a sequence of ( *line0*, *line1*, *line2*), where:: - colors must be a tuple of RGBA tuples (eg arbitrary color - strings, etc, not allowed). + linen = (x0, y0), (x1, y1), ... (xm, ym) - antialiaseds must be a sequence of ones or zeros + or the equivalent numpy array with two columns. Each line + can be a different length. - linestyles is a string or dash tuple. Legal string values are - solid|dashed|dashdot|dotted. The dash tuple is (offset, onoffseq) - where onoffseq is an even length tuple of on and off ink in points. + *colors* + must be a tuple of RGBA tuples (eg arbitrary color + strings, etc, not allowed). - If linewidths, colors_, or antialiaseds is None, they default to - their rc params setting, in sequence form. + *antialiaseds* + must be a sequence of ones or zeros - If offsets and transOffset are not None, then - offsets are transformed by transOffset and applied after + *linestyles* [ 'solid' | 'dashed' | 'dashdot' | 'dotted' ] + a string or dash tuple. The dash tuple is:: + + (offset, onoffseq), + + where *onoffseq* is an even length tuple of on and off ink + in points. + + If *linewidths*, *colors*, or *antialiaseds* is None, they + default to their rcParams setting, in sequence form. + + If *offsets* and *transOffset* are not None, then + *offsets* are transformed by *transOffset* and applied after the segments have been transformed to display coordinates. - If offsets is not None but transOffset is None, then the - offsets are added to the segments before any transformation. - In this case, a single offset can be specified as offsets=(xo,yo), - and this value will be - added cumulatively to each successive segment, so as - to produce a set of successively offset curves. + If *offsets* is not None but *transOffset* is None, then the + *offsets* are added to the segments before any transformation. + In this case, a single offset can be specified as:: - norm = None, # optional for ScalarMappable - cmap = None, # ditto + offsets=(xo,yo) - pickradius is the tolerance for mouse clicks picking a line. The - default is 5 pt. + and this value will be added cumulatively to each successive + segment, so as to produce a set of successively offset curves. - The use of ScalarMappable is optional. If the ScalarMappable - matrix _A is not None (ie a call to set_array has been made), at + *norm* + None (optional for :class:`matplotlib.cm.ScalarMappable`) + *cmap* + None (optional for :class:`matplotlib.cm.ScalarMappable`) + + *pickradius* is the tolerance for mouse clicks picking a line. + The default is 5 pt. + + The use of :class:`~matplotlib.cm.ScalarMappable` is optional. + If the :class:`~matplotlib.cm.ScalarMappable` matrix + :attr:`~matplotlib.cm.ScalarMappable._A` is not None (ie a call to + :meth:`~matplotlib.cm.ScalarMappable.set_array` has been made), at draw time a call to scalar mappable will be made to set the colors. """ if colors is None: colors = mpl.rcParams['lines.color'] @@ -721,8 +750,8 @@ def set_color(self, c): """ - Set the color(s) of the line collection. c can be a - matplotlib color arg (all patches have same color), or a a + Set the color(s) of the line collection. *c* can be a + matplotlib color arg (all patches have same color), or a sequence or rgba tuples; if it is a sequence the patches will cycle through the sequence @@ -732,8 +761,8 @@ def color(self, c): """ - Set the color(s) of the line collection. c can be a - matplotlib color arg (all patches have same color), or a a + Set the color(s) of the line collection. *c* can be a + matplotlib color arg (all patches have same color), or a sequence or rgba tuples; if it is a sequence the patches will cycle through the sequence This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ds...@us...> - 2008-06-16 00:27:37
|
Revision: 5552 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5552&view=rev Author: dsdale Date: 2008-06-15 17:27:35 -0700 (Sun, 15 Jun 2008) Log Message: ----------- added colorbar api reference Modified Paths: -------------- trunk/matplotlib/doc/api/index.rst trunk/matplotlib/lib/matplotlib/colorbar.py Added Paths: ----------- trunk/matplotlib/doc/api/axis_api.rst trunk/matplotlib/doc/api/cbook_api.rst trunk/matplotlib/doc/api/cm_api.rst trunk/matplotlib/doc/api/collections_api.rst trunk/matplotlib/doc/api/colorbar_api.rst Added: trunk/matplotlib/doc/api/axis_api.rst =================================================================== --- trunk/matplotlib/doc/api/axis_api.rst (rev 0) +++ trunk/matplotlib/doc/api/axis_api.rst 2008-06-16 00:27:35 UTC (rev 5552) @@ -0,0 +1,11 @@ +*************** +matplotlib axis +*************** + + +:mod:`matplotlib.axis` +====================== + +.. automodule:: matplotlib.axis + :members: + :undoc-members: Added: trunk/matplotlib/doc/api/cbook_api.rst =================================================================== --- trunk/matplotlib/doc/api/cbook_api.rst (rev 0) +++ trunk/matplotlib/doc/api/cbook_api.rst 2008-06-16 00:27:35 UTC (rev 5552) @@ -0,0 +1,11 @@ +**************** +matplotlib cbook +**************** + + +:mod:`matplotlib.cbook` +======================= + +.. automodule:: matplotlib.cbook + :members: + :undoc-members: Added: trunk/matplotlib/doc/api/cm_api.rst =================================================================== --- trunk/matplotlib/doc/api/cm_api.rst (rev 0) +++ trunk/matplotlib/doc/api/cm_api.rst 2008-06-16 00:27:35 UTC (rev 5552) @@ -0,0 +1,11 @@ +************* +matplotlib cm +************* + + +:mod:`matplotlib.cm` +==================== + +.. automodule:: matplotlib.cm + :members: + :undoc-members: Added: trunk/matplotlib/doc/api/collections_api.rst =================================================================== --- trunk/matplotlib/doc/api/collections_api.rst (rev 0) +++ trunk/matplotlib/doc/api/collections_api.rst 2008-06-16 00:27:35 UTC (rev 5552) @@ -0,0 +1,11 @@ +********************** +matplotlib collections +********************** + + +:mod:`matplotlib.collections` +============================= + +.. automodule:: matplotlib.collections + :members: + :undoc-members: Added: trunk/matplotlib/doc/api/colorbar_api.rst =================================================================== --- trunk/matplotlib/doc/api/colorbar_api.rst (rev 0) +++ trunk/matplotlib/doc/api/colorbar_api.rst 2008-06-16 00:27:35 UTC (rev 5552) @@ -0,0 +1,11 @@ +******************* +matplotlib colorbar +******************* + + +:mod:`matplotlib.colorbar` +========================== + +.. automodule:: matplotlib.colorbar + :members: + :undoc-members: Modified: trunk/matplotlib/doc/api/index.rst =================================================================== --- trunk/matplotlib/doc/api/index.rst 2008-06-15 23:53:06 UTC (rev 5551) +++ trunk/matplotlib/doc/api/index.rst 2008-06-16 00:27:35 UTC (rev 5552) @@ -18,5 +18,6 @@ cbook_api.rst cm_api.rst collections_api.rst + colorbar_api.rst pyplot_api.rst index_backend_api.rst Modified: trunk/matplotlib/lib/matplotlib/colorbar.py =================================================================== --- trunk/matplotlib/lib/matplotlib/colorbar.py 2008-06-15 23:53:06 UTC (rev 5551) +++ trunk/matplotlib/lib/matplotlib/colorbar.py 2008-06-16 00:27:35 UTC (rev 5552) @@ -1,17 +1,21 @@ ''' Colorbar toolkit with two classes and a function: - ColorbarBase is the base class with full colorbar drawing functionality. + :class:`ColorbarBase` + the base class with full colorbar drawing functionality. It can be used as-is to make a colorbar for a given colormap; a mappable object (e.g., image) is not needed. - Colorbar is the derived class for use with images or contour plots. + :class:`Colorbar` + the derived class for use with images or contour plots. - make_axes is a function for resizing an axes and adding a second axes + :func:`make_axes` + a function for resizing an axes and adding a second axes suitable for a colorbar -The Figure.colorbar() method uses make_axes and Colorbar; the pylab.colorbar() -function is a thin wrapper over Figure.colorbar(). +The :meth:`matplotlib.Figure.colorbar` method uses :func:`make_axes` +and :class:`Colorbar`; the :func:`matplotlib.pyplot.colorbar` function +is a thin wrapper over :meth:`matplotlib.Figure.colorbar`. ''' @@ -28,60 +32,68 @@ make_axes_kw_doc = ''' - ======== ==================================================== - Property Description - ======== ==================================================== - fraction 0.15; fraction of original axes to use for colorbar - pad 0.05 if vertical, 0.15 if horizontal; fraction - of original axes between colorbar and new image axes - shrink 1.0; fraction by which to shrink the colorbar - aspect 20; ratio of long to short dimensions - ======== ==================================================== + ========== ==================================================== + Property Description + ========== ==================================================== + *fraction* 0.15; fraction of original axes to use for colorbar + *pad* 0.05 if vertical, 0.15 if horizontal; fraction + of original axes between colorbar and new image axes + *shrink* 1.0; fraction by which to shrink the colorbar + *aspect* 20; ratio of long to short dimensions + ========== ==================================================== ''' colormap_kw_doc = ''' - ========= =============================================================== - Property Description - ========= =============================================================== - extend [ 'neither' | 'both' | 'min' | 'max' ] - If not 'neither', make pointed end(s) for out-of-range - values. These are set for a given colormap using the - colormap set_under and set_over methods. - spacing [ 'uniform' | 'proportional' ] - Uniform spacing gives each discrete color the same space; - proportional makes the space proportional to the data interval. - ticks [ None | list of ticks | Locator object ] - If None, ticks are determined automatically from the input. - format [ None | format string | Formatter object ] - If none, the ScalarFormatter is used. - If a format string is given, e.g. '%.3f', that is used. - An alternative Formatter object may be given instead. - drawedges [ False | True ] If true, draw lines at color boundaries. - ========= =============================================================== + =========== ==================================================== + Property Description + =========== ==================================================== + *extend* [ 'neither' | 'both' | 'min' | 'max' ] + If not 'neither', make pointed end(s) for out-of- + range values. These are set for a given colormap + using the colormap set_under and set_over methods. + *spacing* [ 'uniform' | 'proportional' ] + Uniform spacing gives each discrete color the same + space; proportional makes the space proportional to + the data interval. + *ticks* [ None | list of ticks | Locator object ] + If None, ticks are determined automatically from the + input. + *format* [ None | format string | Formatter object ] + If None, the + :class:`~matplotlib.ticker.ScalarFormatter` is used. + If a format string is given, e.g. '%.3f', that is + used. An alternative + :class:`~matplotlib.ticker.Formatter` object may be + given instead. + *drawedges* [ False | True ] If true, draw lines at color + boundaries. + =========== ==================================================== The following will probably be useful only in the context of indexed colors (that is, when the mappable has norm=NoNorm()), or other unusual circumstances. - ========== =============================================================== - Property Description - ========== =============================================================== - boundaries None or a sequence - values None or a sequence which must be of length 1 less than the - sequence of boundaries. For each region delimited by adjacent - entries in boundaries, the color mapped to the corresponding - value in values will be used. - ========== =============================================================== + ============ =================================================== + Property Description + ============ =================================================== + *boundaries* None or a sequence + *values* None or a sequence which must be of length 1 less + than the sequence of *boundaries*. For each region + delimited by adjacent entries in *boundaries*, the + color mapped to the corresponding value in values + will be used. + ============ =================================================== ''' colorbar_doc = ''' Add a colorbar to a plot. -Function signatures for the pyplot interface; all but the first are -also method signatures for the Figure.colorbar method:: +Function signatures for the :mod:`~matplotlib.pyplot` interface; all +but the first are also method signatures for the +:meth:`matplotlib.Figure.colorbar` method:: colorbar(**kwargs) colorbar(mappable, **kwargs) @@ -89,16 +101,17 @@ colorbar(mappable, ax=ax, **kwargs) arguments: - mappable: - the image, ContourSet, etc. to which the colorbar applies; - this argument is mandatory for the Figure.colorbar - method but optional for the pyplot.colorbar function, - which sets the default to the current image. + *mappable* + the image, :class:`~matplotlib.contours.ContourSet`, etc. to + which the colorbar applies; this argument is mandatory for the + :meth:`matplotlib.Figure.colorbar` method but optional for the + :func:`matplotlib.pyplot.colorbar` function, which sets the + default to the current image. keyword arguments: - cax: + *cax* None | axes object into which the colorbar will be drawn - ax: + *ax* None | parent axes object from which space for a new colorbar axes will be stolen @@ -109,19 +122,18 @@ colorbar properties: %s -If mappable is a ContourSet, its extend kwarg is included automatically. +If mappable is a :class:`~matplotlib.contours.ContourSet`, its *extend* +kwarg is included automatically. -Note that the shrink kwarg provides a simple way to keep -a vertical colorbar, for example, from being taller than -the axes of the mappable to which the colorbar is attached; -but it is a manual method requiring some trial and error. -If the colorbar is too tall (or a horizontal colorbar is -too wide) use a smaller value of shrink. +Note that the *shrink* kwarg provides a simple way to keep a vertical +colorbar, for example, from being taller than the axes of the mappable +to which the colorbar is attached; but it is a manual method requiring +some trial and error. If the colorbar is too tall (or a horizontal +colorbar is too wide) use a smaller value of *shrink*. -For more precise control, you can manually specify the -positions of the axes objects in which the mappable and -the colorbar are drawn. In this case, do not use any of the -axes properties kwargs. +For more precise control, you can manually specify the positions of +the axes objects in which the mappable and the colorbar are drawn. In +this case, do not use any of the axes properties kwargs. ''' % (make_axes_kw_doc, colormap_kw_doc) @@ -130,16 +142,22 @@ ''' Draw a colorbar in an existing axes. - This is a base class for the Colorbar class, which is - the basis for the colorbar method and pylab function. + This is a base class for the :class:`Colorbar` class, which is the + basis for the :func:`~matplotlib.pyplot.colorbar` method and pylab + function. - It is also useful by itself for showing a colormap. If - the cmap kwarg is given but boundaries and values are left - as None, then the colormap will be displayed on a 0-1 scale. - To show the under- and over-value colors, specify the norm - as colors.Normalize(clip=False). + It is also useful by itself for showing a colormap. If the *cmap* + kwarg is given but *boundaries* and *values* are left as None, + then the colormap will be displayed on a 0-1 scale. To show the + under- and over-value colors, specify the *norm* as:: + + colors.Normalize(clip=False) + To show the colors versus index instead of on the 0-1 scale, - use norm=colors.NoNorm. + use:: + + norm=colors.NoNorm. + ''' _slice_dict = {'neither': slice(0,1000000), 'both': slice(1,-1), @@ -257,7 +275,7 @@ def _outline(self, X, Y): ''' - Return x, y arrays of colorbar bounding polygon, + Return *x*, *y* arrays of colorbar bounding polygon, taking orientation into account. ''' N = X.shape[0] @@ -284,7 +302,8 @@ def _add_solids(self, X, Y, C): ''' - Draw the colors using pcolor; optionally add separators. + Draw the colors using :meth:`~matplotlib.axes.Axes.pcolor`; + optionally add separators. ''' ## Change to pcolorfast after fixing bugs in some backends... if self.orientation == 'vertical': @@ -371,9 +390,9 @@ def _process_values(self, b=None): ''' - Set the _boundaries and _values attributes based on - the input boundaries and values. Input boundaries can - be self.boundaries or the argument b. + Set the :attr:`_boundaries` and :attr:`_values` attributes + based on the input boundaries and values. Input boundaries + can be *self.boundaries* or the argument *b*. ''' if b is None: b = self.boundaries @@ -441,15 +460,15 @@ def _find_range(self): ''' - Set vmin and vmax attributes to the first and last - boundary excluding extended end boundaries. + Set :attr:`vmin` and :attr:`vmax` attributes to the first and + last boundary excluding extended end boundaries. ''' b = self._boundaries[self._inside] self.vmin = b[0] self.vmax = b[-1] def _central_N(self): - '''number of boundaries *before* extension of ends''' + '''number of boundaries **before** extension of ends''' nb = len(self._boundaries) if self.extend == 'both': nb -= 2 @@ -471,7 +490,7 @@ def _uniform_y(self, N): ''' - Return colorbar data coordinates for N uniformly + Return colorbar data coordinates for *N* uniformly spaced boundaries, plus ends if required. ''' if self.extend == 'neither': @@ -595,7 +614,8 @@ def add_lines(self, CS): ''' - Add the lines from a non-filled ContourSet to the colorbar. + Add the lines from a non-filled + :class:`~matplotlib.contour.ContourSet` to the colorbar. ''' if not isinstance(CS, contour.ContourSet) or CS.filled: raise ValueError('add_lines is only for a ContourSet of lines') @@ -612,7 +632,8 @@ ColorbarBase.add_lines(self, CS.levels, tcolors, tlinewidths) def update_bruteforce(self, mappable): - '''Manually change any contour line colors. This is called + ''' + Manually change any contour line colors. This is called when the image or contour plot to which this colorbar belongs is changed. ''' @@ -666,12 +687,15 @@ return cax, kw make_axes.__doc__ =''' Resize and reposition a parent axes, and return a child - axes suitable for a colorbar. + axes suitable for a colorbar:: - cax, kw = make_axes(parent, **kw) + cax, kw = make_axes(parent, **kw) Keyword arguments may include the following (with defaults): - orientation = 'vertical' or 'horizontal' + + *orientation* + 'vertical' or 'horizontal' + %s All but the first of these are stripped from the input kw set. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2008-06-16 13:04:36
|
Revision: 5556 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5556&view=rev Author: mdboom Date: 2008-06-16 06:04:07 -0700 (Mon, 16 Jun 2008) Log Message: ----------- Fix title placement in polar plots. Remove broken auto layout code. Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/axes.py trunk/matplotlib/lib/matplotlib/config/mplconfig.py trunk/matplotlib/lib/matplotlib/config/rcsetup.py trunk/matplotlib/lib/matplotlib/figure.py trunk/matplotlib/lib/matplotlib/projections/geo.py trunk/matplotlib/lib/matplotlib/projections/polar.py trunk/matplotlib/lib/matplotlib/rcsetup.py trunk/matplotlib/matplotlibrc.template Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2008-06-16 12:51:33 UTC (rev 5555) +++ trunk/matplotlib/lib/matplotlib/axes.py 2008-06-16 13:04:07 UTC (rev 5556) @@ -1403,32 +1403,6 @@ YL = self.yaxis.get_major_locator().autoscale() self.set_ybound(YL) - def update_layout(self, renderer): - pad_pixels = rcParams['xtick.major.pad'] * self.figure.dpi / 72.0 - inverse_transFigure = self.figure.transFigure.inverted() - t_text, b_text = self.xaxis.get_text_heights(renderer) - l_text, r_text = self.yaxis.get_text_widths(renderer) - title_height = self.title.get_window_extent(renderer).height - title_height += pad_pixels * 2.0 - original_t_text = t_text - - ((l_text, t_text), - (r_text, b_text), - (dummy, title_height)) = inverse_transFigure.transform( - ((l_text, t_text), - (r_text, b_text), - (0.0, title_height))) - x0, y0, x1, y1 = self.get_position(True).extents - # Adjust the title - self.titleOffsetTrans.clear().translate( - 0, original_t_text + pad_pixels * 2.0) - - new_position = mtransforms.Bbox.from_extents( - x0 + l_text, y0 + b_text, - x1 - r_text, y1 - t_text - title_height) - - self.set_position(new_position, 'active') - #### Drawing def draw(self, renderer=None, inframe=False): @@ -5654,7 +5628,7 @@ ax2.xaxis.set_label_position('top') self.xaxis.tick_bottom() return ax2 - + def get_shared_x_axes(self): 'Return a copy of the shared axes Grouper object for x axes' return self._shared_x_axes Modified: trunk/matplotlib/lib/matplotlib/config/mplconfig.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2008-06-16 12:51:33 UTC (rev 5555) +++ trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2008-06-16 13:04:07 UTC (rev 5556) @@ -238,7 +238,6 @@ dpi = T.Float(80) facecolor = T.Trait('0.75', mplT.ColorHandler()) edgecolor = T.Trait('white', mplT.ColorHandler()) - autolayout = T.false class subplot(TConfig): """The figure subplot parameters. All dimensions are fraction @@ -408,7 +407,6 @@ 'figure.dpi' : (self.tconfig.figure, 'dpi'), 'figure.facecolor' : (self.tconfig.figure, 'facecolor'), 'figure.edgecolor' : (self.tconfig.figure, 'edgecolor'), - 'figure.autolayout' : (self.tconfig.figure, 'autolayout'), 'figure.subplot.left' : (self.tconfig.figure.subplot, 'left'), 'figure.subplot.right' : (self.tconfig.figure.subplot, 'right'), Modified: trunk/matplotlib/lib/matplotlib/config/rcsetup.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/rcsetup.py 2008-06-16 12:51:33 UTC (rev 5555) +++ trunk/matplotlib/lib/matplotlib/config/rcsetup.py 2008-06-16 13:04:07 UTC (rev 5556) @@ -439,7 +439,6 @@ 'figure.dpi' : [80, validate_float], # DPI 'figure.facecolor' : ['0.75', validate_color], # facecolor; scalar gray 'figure.edgecolor' : ['w', validate_color], # edgecolor; white - 'figure.autolayout' : [False, validate_bool], 'figure.subplot.left' : [0.125, ValidateInterval(0, 1, closedmin=False, closedmax=False)], 'figure.subplot.right' : [0.9, ValidateInterval(0, 1, closedmin=False, closedmax=False)], Modified: trunk/matplotlib/lib/matplotlib/figure.py =================================================================== --- trunk/matplotlib/lib/matplotlib/figure.py 2008-06-16 12:51:33 UTC (rev 5555) +++ trunk/matplotlib/lib/matplotlib/figure.py 2008-06-16 13:04:07 UTC (rev 5556) @@ -240,7 +240,6 @@ self.clf() self._cachedRenderer = None - self._autoLayout = rcParams['figure.autolayout'] def _get_dpi(self): return self._dpi @@ -250,9 +249,6 @@ self.callbacks.process('dpi_changed', self) dpi = property(_get_dpi, _set_dpi) - def enable_auto_layout(self, setting=True): - self._autoLayout = setting - def autofmt_xdate(self, bottom=0.2, rotation=30, ha='right'): """ Date ticklabels often overlap, so it is useful to rotate them @@ -284,7 +280,7 @@ label.set_visible(False) ax.set_xlabel('') - if allsubplots and not self._autoLayout: + if allsubplots: self.subplots_adjust(bottom=bottom) def get_children(self): @@ -765,62 +761,6 @@ renderer.draw_image(l, b, im, self.bbox, *self.get_transformed_clip_path_and_affine()) - # update the positions of the axes - # This gives each of the axes the opportunity to resize itself - # based on the tick and axis labels etc., and then makes sure - # that any axes that began life aligned to another axes remains - # aligned after these adjustments - if self._autoLayout and len(self.axes) > 1: - aligned_positions = [{}, {}, {}, {}] - sizes = [{}, {}] - for a in self.axes: - a.update_layout(renderer) - orig_pos = a.get_position(True) - curr_pos = a.get_position() - for pos, orig, curr in zip(aligned_positions, - orig_pos.get_points().flatten(), - curr_pos.get_points().flatten()): - if orig in pos: - pos[orig][0].append(a) - pos[orig][1].add(curr) - else: - pos[orig] = [[a], set([curr])] - for size, orig, curr in zip(sizes, - orig_pos.size, - curr_pos.size): - orig = round(orig * 1000.0) / 1000.0 - if orig in size: - size[orig][0].append(a) - size[orig][1].add(curr) - else: - size[orig] = [[a], set([curr])] - - for i, pos in enumerate(aligned_positions): - for axes, places in pos.values(): - if len(places) > 1: - if i < 2: - curr = max(places) - else: - curr = min(places) - for a in axes: - curr_pos = a.get_position().frozen() - curr_pos.get_points()[i/2, i%2] = curr - a.set_position(curr_pos, 'active') - - for i, size in enumerate(sizes): - for axes, dims in size.values(): - new = min(dims) - for a in axes: - curr_pos = a.get_position().frozen() - curr = curr_pos.size[i] - if curr > new: - extra = (curr - new) * 0.5 - curr_pos.get_points()[0, i] += extra - curr_pos.get_points()[1, i] -= extra - a.set_position(curr_pos, 'active') - elif self._autoLayout: - for a in self.axes: a.update_layout(renderer) - # render the axes for a in self.axes: a.draw(renderer) Modified: trunk/matplotlib/lib/matplotlib/projections/geo.py =================================================================== --- trunk/matplotlib/lib/matplotlib/projections/geo.py 2008-06-16 12:51:33 UTC (rev 5555) +++ trunk/matplotlib/lib/matplotlib/projections/geo.py 2008-06-16 13:04:07 UTC (rev 5556) @@ -109,14 +109,6 @@ .scale(0.5 / xscale, 0.5 / yscale) \ .translate(0.5, 0.5) - def update_layout(self, renderer): - t_text, b_text = self.xaxis.get_text_heights(renderer) - l_text, r_text = self.yaxis.get_text_widths(renderer) - originalPosition = self.get_position(True) - title_offset = (b_text - originalPosition.transformed( - self.figure.transFigure).height) / 2.0 - self.titleOffsetTrans.clear().translate(0, title_offset) - def get_xaxis_transform(self): return self._xaxis_transform Modified: trunk/matplotlib/lib/matplotlib/projections/polar.py =================================================================== --- trunk/matplotlib/lib/matplotlib/projections/polar.py 2008-06-16 12:51:33 UTC (rev 5555) +++ trunk/matplotlib/lib/matplotlib/projections/polar.py 2008-06-16 13:04:07 UTC (rev 5556) @@ -176,6 +176,8 @@ def cla(self): Axes.cla(self) + self.title.set_y(1.05) + self.xaxis.set_major_formatter(self.ThetaFormatter()) angles = npy.arange(0.0, 360.0, 45.0) self.set_thetagrids(angles) @@ -241,14 +243,6 @@ self._yaxis_transform ) - def update_layout(self, renderer): - t_text, b_text = self.xaxis.get_text_heights(renderer) - l_text, r_text = self.yaxis.get_text_widths(renderer) - originalPosition = self.get_position(True) - title_offset = (b_text - originalPosition.transformed( - self.figure.transFigure).height) / 2.0 - self.titleOffsetTrans.clear().translate(0, title_offset) - def get_xaxis_transform(self): return self._xaxis_transform Modified: trunk/matplotlib/lib/matplotlib/rcsetup.py =================================================================== --- trunk/matplotlib/lib/matplotlib/rcsetup.py 2008-06-16 12:51:33 UTC (rev 5555) +++ trunk/matplotlib/lib/matplotlib/rcsetup.py 2008-06-16 13:04:07 UTC (rev 5556) @@ -457,8 +457,6 @@ 'figure.subplot.wspace' : [0.2, ValidateInterval(0, 1, closedmin=True, closedmax=False)], 'figure.subplot.hspace' : [0.2, ValidateInterval(0, 1, closedmin=True, closedmax=False)], - 'figure.autolayout' : [False, validate_bool], - 'savefig.dpi' : [100, validate_float], # DPI 'savefig.facecolor' : ['w', validate_color], # facecolor; white 'savefig.edgecolor' : ['w', validate_color], # edgecolor; white Modified: trunk/matplotlib/matplotlibrc.template =================================================================== --- trunk/matplotlib/matplotlibrc.template 2008-06-16 12:51:33 UTC (rev 5555) +++ trunk/matplotlib/matplotlibrc.template 2008-06-16 13:04:07 UTC (rev 5556) @@ -249,8 +249,6 @@ #figure.subplot.wspace : 0.2 # the amount of width reserved for blank space between subplots #figure.subplot.hspace : 0.2 # the amount of height reserved for white space between subplots -#figure.autolayout : False # when True, adjust the axes so that text doesn't overlap - ### IMAGES #image.aspect : equal # equal | auto | a number #image.interpolation : bilinear # see help(imshow) for options This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2008-06-17 14:41:11
|
Revision: 5570 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5570&view=rev Author: mdboom Date: 2008-06-17 07:40:10 -0700 (Tue, 17 Jun 2008) Log Message: ----------- Support getting the vertices of curved paths. Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/patches.py trunk/matplotlib/lib/matplotlib/path.py trunk/matplotlib/src/_path.cpp Modified: trunk/matplotlib/lib/matplotlib/patches.py =================================================================== --- trunk/matplotlib/lib/matplotlib/patches.py 2008-06-17 14:04:19 UTC (rev 5569) +++ trunk/matplotlib/lib/matplotlib/patches.py 2008-06-17 14:40:10 UTC (rev 5570) @@ -83,11 +83,17 @@ def get_verts(self): """ return a copy of the vertices used in this patch + + If the patch contains Bezier curves, the curves will be + interpolated by line segments. To access the curves as + curves, use :meth:`get_path`. """ trans = self.get_transform() path = self.get_path() - tverts = trans.transform(path.vertices) - return tverts + polygons = path.to_polygons(trans) + if len(polygons): + return polygons[0] + return [] def contains(self, mouseevent): """Test whether the mouse event occurred in the patch. Modified: trunk/matplotlib/lib/matplotlib/path.py =================================================================== --- trunk/matplotlib/lib/matplotlib/path.py 2008-06-17 14:04:19 UTC (rev 5569) +++ trunk/matplotlib/lib/matplotlib/path.py 2008-06-17 14:40:10 UTC (rev 5570) @@ -290,14 +290,21 @@ ``MOVETO`` instructions or curves. This is useful for displaying in backends that do not support compound paths or Bezier curves, such as GDK. + + If width and height are both non-zero then the lines will be + simplified so that vertices outside of (0, 0), (width, height) + will be clipped. """ + if len(self.vertices) == 0: + return [] + if transform is not None: transform = transform.frozen() - # Deal with the common and simple case - if self.codes is None and len(self.vertices) < 100: - if len(self.vertices): + if self.codes is None: return [transform.transform(self.vertices)] - return [] + else: + if self.codes is None: + return [self.vertices] # Deal with the case where there are curves and/or multiple # subpaths (using extension code) return convert_path_to_polygons(self, transform, width, height) Modified: trunk/matplotlib/src/_path.cpp =================================================================== --- trunk/matplotlib/src/_path.cpp 2008-06-17 14:04:19 UTC (rev 5569) +++ trunk/matplotlib/src/_path.cpp 2008-06-17 14:40:10 UTC (rev 5570) @@ -52,7 +52,7 @@ add_varargs_method("path_intersects_path", &_path_module::path_intersects_path, "path_intersects_path(p1, p2)"); add_varargs_method("convert_path_to_polygons", &_path_module::convert_path_to_polygons, - "convert_path_to_polygons(path, trans)"); + "convert_path_to_polygons(path, trans, width, height)"); initialize("Helper functions for paths"); } @@ -1115,7 +1115,7 @@ double width = Py::Float(args[2]); double height = Py::Float(args[3]); - bool simplify = !path.has_curves(); + bool simplify = !path.has_curves() && width != 0.0 && height != 0.0; transformed_path_t tpath(path, trans); simplify_t simplified(tpath, false, simplify, width, height); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2008-06-17 15:44:21
|
Revision: 5577 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5577&view=rev Author: mdboom Date: 2008-06-17 08:42:12 -0700 (Tue, 17 Jun 2008) Log Message: ----------- Align inline mathtext correctly in HTML docs (by adjusting for the baseline) Modified Paths: -------------- trunk/matplotlib/doc/sphinxext/mathpng.py trunk/matplotlib/examples/user_interfaces/mathtext_wx.py trunk/matplotlib/lib/matplotlib/mathtext.py Modified: trunk/matplotlib/doc/sphinxext/mathpng.py =================================================================== --- trunk/matplotlib/doc/sphinxext/mathpng.py 2008-06-17 15:09:09 UTC (rev 5576) +++ trunk/matplotlib/doc/sphinxext/mathpng.py 2008-06-17 15:42:12 UTC (rev 5577) @@ -113,16 +113,19 @@ # This uses mathtext to render the expression def latex2png(latex, filename, fontset='cm'): + latex = "$%s$" % latex if os.path.exists(filename): - return + return mathtext_parser.get_depth(latex, dpi=120) orig_fontset = rcParams['mathtext.fontset'] rcParams['mathtext.fontset'] = fontset try: - mathtext_parser.to_png(filename, "$%s$" % latex, dpi=120) + depth = mathtext_parser.to_png(filename, latex, dpi=120) except: - warnings.warn("Could not render math expression $%s$" % latex, - warnings.Warning) + warnings.warn("Could not render math expression %s" % latex, + Warning) + depth = 0 rcParams['mathtext.fontset'] = orig_fontset + return depth # LaTeX to HTML translation stuff: def latex2html(node, source): @@ -131,8 +134,7 @@ print latex.encode("ascii", "backslashreplace") name = 'math-%s' % md5(latex).hexdigest()[-10:] dest = '_static/%s.png' % name - if not isfile(dest): - latex2png(latex, dest, node['fontset']) + depth = latex2png(latex, dest, node['fontset']) path = '_static' count = source.split('/doc/')[-1].count('/') @@ -148,5 +150,10 @@ cls = '' else: cls = 'class="center" ' - return '<img src="%s/%s.png" %s%s/>' % (path, name, align, cls) + if inline and depth != 0: + style = 'style="position: relative; bottom: -%dpx"' % (depth + 1) + else: + style = '' + return '<img src="%s/%s.png" %s%s%s/>' % (path, name, align, cls, style) + Modified: trunk/matplotlib/examples/user_interfaces/mathtext_wx.py =================================================================== --- trunk/matplotlib/examples/user_interfaces/mathtext_wx.py 2008-06-17 15:09:09 UTC (rev 5576) +++ trunk/matplotlib/examples/user_interfaces/mathtext_wx.py 2008-06-17 15:42:12 UTC (rev 5577) @@ -21,7 +21,7 @@ from matplotlib.mathtext import MathTextParser mathtext_parser = MathTextParser("Bitmap") def mathtext_to_wxbitmap(s): - ftimage = mathtext_parser.parse(s, 150) + ftimage, depth = mathtext_parser.parse(s, 150) return wx.BitmapFromBufferRGBA( ftimage.get_width(), ftimage.get_height(), ftimage.as_rgba_str()) Modified: trunk/matplotlib/lib/matplotlib/mathtext.py =================================================================== --- trunk/matplotlib/lib/matplotlib/mathtext.py 2008-06-17 15:09:09 UTC (rev 5576) +++ trunk/matplotlib/lib/matplotlib/mathtext.py 2008-06-17 15:42:12 UTC (rev 5577) @@ -341,7 +341,7 @@ class MathtextBackendBitmapRender(MathtextBackendAggRender): def get_results(self, box): - return self.image + return self.image, self.depth def MathtextBackendBitmap(): return MathtextBackendBbox(MathtextBackendBitmapRender()) @@ -2726,8 +2726,14 @@ def to_mask(self, texstr, dpi=120, fontsize=14): """ - return an NxM uint8 alpha ubyte mask array of rasterized tex + Returns a tuple (*array*, *depth*) + - *array* is an NxM uint8 alpha ubyte mask array of + rasterized tex. + + - depth is the offset of the baseline from the bottom of the + image in pixels. + ''texstr'' A valid mathtext string, eg r'IQ: $\sigma_i=15$' @@ -2739,15 +2745,23 @@ """ assert(self._output=="bitmap") prop = FontProperties(size=fontsize) - ftimage = self.parse(texstr, dpi=dpi, prop=prop) + ftimage, depth = self.parse(texstr, dpi=dpi, prop=prop) x = ftimage.as_array() - return x + return x, depth def to_rgba(self, texstr, color='black', dpi=120, fontsize=14): """ - return an NxMx4 RGBA array of ubyte rasterized tex + Returns a tuple (*array*, *depth*) + - *array* is an NxMx4 RGBA array of ubyte rasterized tex. + + - depth is the offset of the baseline from the bottom of the + image in pixels. + + Returns a tuple (array, depth), where depth is the offset of + the baseline from the bottom of the image. + ''texstr'' A valid mathtext string, eg r'IQ: $\sigma_i=15$' @@ -2760,7 +2774,7 @@ ''fontsize'' The font size in points """ - x = self.to_mask(texstr, dpi=dpi, fontsize=fontsize) + x, depth = self.to_mask(texstr, dpi=dpi, fontsize=fontsize) r, g, b = mcolors.colorConverter.to_rgb(color) RGBA = np.zeros((x.shape[0], x.shape[1], 4), dtype=np.uint8) @@ -2768,11 +2782,15 @@ RGBA[:,:,1] = int(255*g) RGBA[:,:,2] = int(255*b) RGBA[:,:,3] = x - return RGBA + return RGBA, depth def to_png(self, filename, texstr, color='black', dpi=120, fontsize=14): """ + Writes a tex expression to a PNG file. + Returns the offset of the baseline from the bottom of the + image in pixels. + ''filename'' A writable filename or fileobject @@ -2790,7 +2808,27 @@ """ - rgba = self.to_rgba(texstr, color=color, dpi=dpi, fontsize=fontsize) + rgba, depth = self.to_rgba(texstr, color=color, dpi=dpi, fontsize=fontsize) numrows, numcols, tmp = rgba.shape - return _png.write_png(rgba.tostring(), numcols, numrows, filename) + _png.write_png(rgba.tostring(), numcols, numrows, filename) + return depth + def get_depth(self, texstr, dpi=120, fontsize=14): + """ + Returns the offset of the baseline from the bottom of the + image in pixels. + + ''texstr'' + A valid mathtext string, eg r'IQ: $\sigma_i=15$' + + ''dpi'' + The dots-per-inch to render the text + + ''fontsize'' + The font size in points + + """ + assert(self._output=="bitmap") + prop = FontProperties(size=fontsize) + ftimage, depth = self.parse(texstr, dpi=dpi, prop=prop) + return depth This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2008-06-17 18:03:02
|
Revision: 5583 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5583&view=rev Author: mdboom Date: 2008-06-17 11:02:08 -0700 (Tue, 17 Jun 2008) Log Message: ----------- Add a generic PatchCollection class. Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/collections.py Added Paths: ----------- trunk/matplotlib/examples/api/patch_collection.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2008-06-17 17:23:30 UTC (rev 5582) +++ trunk/matplotlib/CHANGELOG 2008-06-17 18:02:08 UTC (rev 5583) @@ -1,3 +1,6 @@ +2008-06-17 Add a generic PatchCollection class that can contain any + kind of patch. - MGD + 2008-06-13 Change pie chart label alignment to avoid having labels overwrite the pie - MGD Added: trunk/matplotlib/examples/api/patch_collection.py =================================================================== --- trunk/matplotlib/examples/api/patch_collection.py (rev 0) +++ trunk/matplotlib/examples/api/patch_collection.py 2008-06-17 18:02:08 UTC (rev 5583) @@ -0,0 +1,38 @@ +import matplotlib +from matplotlib.patches import Circle, Wedge, Polygon +from matplotlib.collections import PatchCollection +import pylab + +fig=pylab.figure() +ax=fig.add_subplot(111) + +resolution = 50 # the number of vertices +N = 3 +x = pylab.rand(N) +y = pylab.rand(N) +radii = 0.1*pylab.rand(N) +patches = [] +for x1,y1,r in zip(x, y, radii): + circle = Circle((x1,y1), r) + patches.append(circle) + +x = pylab.rand(N) +y = pylab.rand(N) +radii = 0.1*pylab.rand(N) +theta1 = 360.0*pylab.rand(N) +theta2 = 360.0*pylab.rand(N) +for x1,y1,r,t1,t2 in zip(x, y, radii, theta1, theta2): + wedge = Wedge((x1,y1), r, t1, t2) + patches.append(wedge) + +for i in range(N): + polygon = Polygon(pylab.rand(N,2), True) + patches.append(polygon) + +colors = 100*pylab.rand(len(patches)) +p = PatchCollection(patches, cmap=matplotlib.cm.jet) +p.set_array(pylab.array(colors)) +ax.add_collection(p) +pylab.colorbar(p) + +pylab.show() Modified: trunk/matplotlib/lib/matplotlib/collections.py =================================================================== --- trunk/matplotlib/lib/matplotlib/collections.py 2008-06-17 17:23:30 UTC (rev 5582) +++ trunk/matplotlib/lib/matplotlib/collections.py 2008-06-17 18:02:08 UTC (rev 5583) @@ -775,7 +775,68 @@ return self._edgecolors get_colors = get_color # for compatibility with old versions +class PatchCollection(Collection): + """ + A generic collection of patches. + This makes it easier to assign a color map to a heterogeneous + collection of patches. + + This also may improve plotting speed, since PatchCollection will + draw faster than a large number of patches. + """ + + def __init__(self, patches, match_original=False, **kwargs): + """ + *patches* + a sequence of Patch objects. This list may include + a heterogeneous assortment of different patch types. + + *match_original* If True, use the colors and linewidths of the + original patches. If False, new colors may be assigned by + providing the standard collection arguments, facecolor, + edgecolor, linewidths, norm or cmap. + + If any of *edgecolors*, *facecolors*, *linewidths*, + *antialiaseds* are None, they default to their + :data:`matplotlib.rcParams` patch setting, in sequence form. + + The use of :class:`~matplotlib.cm.ScalarMappable` is optional. + If the :class:`~matplotlib.cm.ScalarMappable` matrix _A is not + None (ie a call to set_array has been made), at draw time a + call to scalar mappable will be made to set the face colors. + """ + + if match_original: + def determine_facecolor(patch): + if patch.fill(): + return patch.get_facecolor() + return [0, 0, 0, 0] + + facecolors = [determine_facecolor(p) for p in patches] + edgecolors = [p.get_edgecolor() for p in patches] + linewidths = [p.get_linewidths() for p in patches] + antialiaseds = [p.get_antialiased() for p in patches] + + Collection.__init__( + self, + edgecolors=edgecolors, + facecolors=facecolors, + linewidths=linewidths, + linestyles='solid', + antialiaseds = antialiaseds) + else: + Collection.__init__(self, **kwargs) + + paths = [p.get_transform().transform_path(p.get_path()) + for p in patches] + + self._paths = paths + + def get_paths(self): + return self._paths + + artist.kwdocd['Collection'] = patchstr = artist.kwdoc(Collection) for k in ('QuadMesh', 'PolyCollection', 'BrokenBarHCollection', 'RegularPolyCollection', 'StarPolygonCollection'): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2008-06-18 20:27:19
|
Revision: 5589 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5589&view=rev Author: jdh2358 Date: 2008-06-18 13:26:35 -0700 (Wed, 18 Jun 2008) Log Message: ----------- added figure api doc Modified Paths: -------------- trunk/matplotlib/doc/api/index.rst trunk/matplotlib/lib/matplotlib/colorbar.py trunk/matplotlib/lib/matplotlib/figure.py Added Paths: ----------- trunk/matplotlib/doc/api/figure_api.rst Added: trunk/matplotlib/doc/api/figure_api.rst =================================================================== --- trunk/matplotlib/doc/api/figure_api.rst (rev 0) +++ trunk/matplotlib/doc/api/figure_api.rst 2008-06-18 20:26:35 UTC (rev 5589) @@ -0,0 +1,12 @@ +***************** +matplotlib figure +***************** + + +:mod:`matplotlib.figure` +======================== + +.. automodule:: matplotlib.figure + :members: + :undoc-members: + :show-inheritance: Modified: trunk/matplotlib/doc/api/index.rst =================================================================== --- trunk/matplotlib/doc/api/index.rst 2008-06-18 19:38:57 UTC (rev 5588) +++ trunk/matplotlib/doc/api/index.rst 2008-06-18 20:26:35 UTC (rev 5589) @@ -13,6 +13,7 @@ matplotlib_configuration_api.rst artist_api.rst + figure_api.rst axes_api.rst axis_api.rst cbook_api.rst Modified: trunk/matplotlib/lib/matplotlib/colorbar.py =================================================================== --- trunk/matplotlib/lib/matplotlib/colorbar.py 2008-06-18 19:38:57 UTC (rev 5588) +++ trunk/matplotlib/lib/matplotlib/colorbar.py 2008-06-18 20:26:35 UTC (rev 5589) @@ -101,6 +101,7 @@ colorbar(mappable, ax=ax, **kwargs) arguments: + *mappable* the image, :class:`~matplotlib.contours.ContourSet`, etc. to which the colorbar applies; this argument is mandatory for the @@ -109,6 +110,7 @@ default to the current image. keyword arguments: + *cax* None | axes object into which the colorbar will be drawn *ax* @@ -117,6 +119,7 @@ Additional keyword arguments are of two kinds: + axes properties: %s colorbar properties: Modified: trunk/matplotlib/lib/matplotlib/figure.py =================================================================== --- trunk/matplotlib/lib/matplotlib/figure.py 2008-06-18 19:38:57 UTC (rev 5588) +++ trunk/matplotlib/lib/matplotlib/figure.py 2008-06-18 20:26:35 UTC (rev 5589) @@ -1,5 +1,18 @@ """ -Figure class -- add docstring here! +The figure module provides the top-level +:class:`~matplotlib.artist.Artist`, the :class:`Figure`, which +contains all the plot elements. The following classes are defined + +:class:`SubplotParams` + control the default spacing of the subplots + +:class:`BlockingMouseInput` + creates a callable object to retrieve mouse clicks in a blocking way for interactive sessions + +:class:`Figure` + top level container for all plot elements + + """ import numpy as np import time @@ -32,18 +45,24 @@ All dimensions are fraction of the figure width or height. All values default to their rc params - The following attributes are available: + The following attributes are available - left : the left side of the subplots of the figure - right : the right side of the subplots of the figure - bottom : the bottom of the subplots of the figure - top : the top of the subplots of the figure - wspace : the amount of width reserved for blank space between subplots - hspace : the amount of height reserved for white space between subplots + *left* = 0.125 + the left side of the subplots of the figure + *right* = 0.9 + the right side of the subplots of the figure + *bottom* = 0.1 + the bottom of the subplots of the figure + *top* = 0.9 + the top of the subplots of the figure + *wspace* = 0.2 + the amount of width reserved for blank space between subplots + *hspace* = 0.2 + the amount of height reserved for white space between subplots + *validate* + make sure the params are in a legal state (*left*<*right*, etc) + """ - validate : make sure the params are in a legal state - (left<right, etc) - """ self.validate = True self.update(left, bottom, right, top, wspace, hspace) @@ -100,17 +119,19 @@ class BlockingMouseInput(object): - """ Class that creates a callable object to retrieve mouse clicks in a - blocking way. """ + Class that creates a callable object to retrieve mouse clicks in a + blocking way. + """ def __init__(self, fig): self.fig = fig def on_click(self, event): - """ Event handler that will be passed to the current figure to - retrieve clicks. """ + Event handler that will be passed to the current figure to + retrieve clicks. + """ if event.button == 3: # If it's a right click, pop the last coordinates. if len(self.clicks) > 0: @@ -137,9 +158,10 @@ def __call__(self, n=1, timeout=30, verbose=False, show_clicks=True): - """ Blocking call to retrieve n coordinate pairs through mouse - clicks. """ + Blocking call to retrieve n coordinate pairs through mouse + clicks. + """ self.verbose = verbose self.done = False self.clicks = [] @@ -179,10 +201,17 @@ class Figure(Artist): """ - The Figure instance supports callbacks through a callbacks - attribute which is a cbook.CallbackRegistry instance. The events - you can connect to are 'dpi_changed', and the callback will be - called with func(fig) where fig is the Figure instance + The Figure instance supports callbacks through a *callbacks* + attribute which is a :class:`matplotlib.cbook.CallbackRegistry` + instance. The events you can connect to are 'dpi_changed', and + the callback will be called with ``func(fig)`` where fig is the + :class:`Figure` instance. + + The figure patch is drawn by a the attribute + + *figurePatch* + a :class:`matplotlib.patches.Rectangle` instance + """ def __str__(self): @@ -198,9 +227,20 @@ subplotpars = None, # default to rc ): """ - figsize is a w,h tuple in inches - dpi is dots per inch - subplotpars is a SubplotParams instance, defaults to rc + *figsize* + w,h tuple in inches + *dpi* + dots per inch + *facecolor* + the figure patch facecolor; defaults to rc ``figure.facecolor`` + *edgecolor* + the figure patch edge color; defaults to rc ``figure.edgecolor`` + *linewidth* + the figure patch edge linewidth; the default linewidth of the frame + *frameon* + if False, suppress drawing the figure frame + *subplotpars* + a :class:`SubplotParams` instance, defaults to rc """ Artist.__init__(self) @@ -258,10 +298,12 @@ bottom subplot and turn them off on other subplots, as well as turn off xlabels. - - bottom : the bottom of the subplots for subplots_adjust - rotation: the rotation of the xtick labels - ha : the horizontal alignment of the xticklabels + *bottom* + the bottom of the subplots for :meth:`subplots_adjust` + *rotation* + the rotation of the xtick labels + *ha* + the horizontal alignment of the xticklabels """ allsubplots = np.alltrue([hasattr(ax, 'is_last_row') for ax in self.axes]) if len(self.axes)==1: @@ -295,7 +337,8 @@ return children def contains(self, mouseevent): - """Test whether the mouse event occurred on the figure. + """ + Test whether the mouse event occurred on the figure. Returns True,{} """ @@ -313,17 +356,21 @@ """ add a centered title to the figure - kwargs are matplotlib.text.Text properties. Using figure + kwargs are :class:`matplotlib.text.Text` properties. Using figure coordinates, the defaults are - x = 0.5 - y = 0.98 - horizontalalignment = 'center' - verticalalignment = 'top' + *x* = 0.5 + the x location of text in figure coords + *y* = 0.98 + the y location of the text in figure coords + *horizontalalignment* = 'center' + the horizontal alignment of the text + *verticalalignment* = 'top' + the vertical alignment of the text - The matplotlib.text.Text instance is returned + The :class:`matplotlib.text.Text` instance is returned - Example: + Example:: fig.subtitle('this is the figure title', fontsize=12) """ @@ -351,10 +398,11 @@ 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 + Eg:: + + hold() # toggle hold + hold(True) # hold is on + hold(False) # hold is off """ if b is None: self._hold = not self._hold else: self._hold = b @@ -411,7 +459,7 @@ resampled to fit the current axes. If you want a resampled image to fill the entire figure, you can define an Axes with size [0,1,0,1]. - An image.FigureImage instance is returned. + An :class:`matplotlib.image.FigureImage` instance is returned. """ if not self._hold: self.clf() @@ -435,10 +483,12 @@ Set the figure size in inches - Usage: set_size_inches(self, w,h) OR - set_size_inches(self, (w,h) ) + Usage:: - optional kwarg forward=True will cause the canvas size to be + fig.set_size_inches(w,h) # OR + fig.set_size_inches((w,h) ) + + optional kwarg *forward=True* will cause the canvas size to be automatically updated; eg you can resize the figure window from the shell @@ -578,31 +628,30 @@ Add an a axes with axes rect [left, bottom, width, height] where all quantities are in fractions of figure width and height. kwargs are legal Axes kwargs plus "projection" which sets the projection type - of the axes. (For backward compatibility, polar=True may also be - provided, which is equivalent to projection='polar'). + of the axes. (For backward compatibility, *polar=True* may also be + provided, which is equivalent to *projection='polar'*). Valid values for "projection" are: %s. Some of these projections - support additional kwargs, which may be provided to add_axes. + support additional kwargs, which may be provided to add_axes:: rect = l,b,w,h - add_axes(rect) - add_axes(rect, frameon=False, axisbg='g') - add_axes(rect, polar=True) - add_axes(rect, projection='polar') - add_axes(ax) # add an Axes instance + fig.add_axes(rect) + fig.add_axes(rect, frameon=False, axisbg='g') + fig.add_axes(rect, polar=True) + fig.add_axes(rect, projection='polar') + fig.add_axes(ax) # add an Axes instance - If the figure already has an axes with key *args, *kwargs then it will simply make that axes current and return it. If you do not want this behavior, eg you want to force the creation of a new axes, you must use a unique set of args and kwargs. The artist "label" attribute has been exposed for this purpose. Eg, if you want two axes that are otherwise identical to be added to the figure, make sure you give them - unique labels: + unique labels:: - add_axes(rect, label='axes1') - add_axes(rect, label='axes2') + fig.add_axes(rect, label='axes1') + fig.add_axes(rect, label='axes2') - The Axes instance will be returned + The :class:`~matplotlib.axes.Axes` instance will be returned. The following kwargs are supported: %s @@ -643,24 +692,24 @@ def add_subplot(self, *args, **kwargs): """ - Add a subplot. Examples + Add a subplot. Examples: - add_subplot(111) - add_subplot(1,1,1) # equivalent but more general - add_subplot(212, axisbg='r') # add subplot with red background - add_subplot(111, polar=True) # add a polar subplot - add_subplot(sub) # add Subplot instance sub + fig.add_subplot(111) + fig.add_subplot(1,1,1) # equivalent but more general + fig.add_subplot(212, axisbg='r') # add subplot with red background + fig.add_subplot(111, polar=True) # add a polar subplot + fig.add_subplot(sub) # add Subplot instance sub - kwargs are legal Axes kwargs plus "projection", which chooses + *kwargs* are legal :class:`!matplotlib.axes.Axes` kwargs plus *projection*, which chooses a projection type for the axes. (For backward compatibility, - polar=True may also be provided, which is equivalent to - projection='polar'). Valid values for "projection" are: %s. - Some of these projections support additional kwargs, which may - be provided to add_axes. + *polar=True* may also be provided, which is equivalent to + *projection='polar'*). Valid values for *projection* are: %s. + Some of these projections support additional *kwargs*, which may + be provided to :meth:`add_axes`. - The Axes instance will be returned. + The :class:`~matplotlib.axes.Axes` instance will be returned. - If the figure already has a subplot with key *args, *kwargs then it will + If the figure already has a subplot with key *args*, *kwargs* then it will simply make that subplot current and return it The following kwargs are supported: @@ -731,7 +780,7 @@ def draw(self, renderer): """ - Render the figure using Renderer instance renderer + Render the figure using :class:`matplotlib.backend_bases.RendererBase` instance renderer """ # draw the figure bounding box, perhaps none for white figure #print 'figure draw' @@ -777,7 +826,10 @@ self.canvas.draw_event(renderer) def draw_artist(self, a): - 'draw artist only -- this is available only after the figure is drawn' + """ + draw :class:`matplotlib.artist.Artist` instance *a* only -- + this is available only after the figure is drawn + """ assert self._cachedRenderer is not None a.draw(self._cachedRenderer) @@ -787,16 +839,18 @@ def legend(self, handles, labels, *args, **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 or an integer specifying the legend - location + strings, handles is a sequence of + :class:`~matplotlib.lines.Line2D` or + :class:`~matplotlib.patches.Patch` instances, and loc can be a + string or an integer specifying the legend location - USAGE: + USAGE:: + legend( (line1, line2, line3), ('label1', 'label2', 'label3'), 'upper right') - The LOC location codes are + The *loc* location codes are:: 'best' : 0, (currently not supported for figure legends) 'upper right' : 1, @@ -810,27 +864,35 @@ 'upper center' : 9, 'center' : 10, - loc can also be an (x,y) tuple in figure coords, which + *loc* can also be an (x,y) tuple in figure coords, which specifies the lower left of the legend box. figure coords are (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: + The legend instance is returned. The following kwargs are supported - loc = "upper right" # - numpoints = 4 # the number of points in the legend line - prop = FontProperties(size='smaller') # the font property - pad = 0.2 # the fractional whitespace inside the legend border - markerscale = 0.6 # the relative size of legend markers vs. original - shadow # if True, draw a shadow behind legend - labelsep = 0.005 # the vertical space between the legend entries - handlelen = 0.05 # the length of the legend lines - handletextsep = 0.02 # the space between the legend line and legend text - axespad = 0.02 # the border between the axes and legend edge + *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 """ - - handles = flatten(handles) l = Legend(self, handles, labels, *args, **kwargs) self.legends.append(l) @@ -841,7 +903,7 @@ Add text to figure at location x,y (relative 0-1 coords) See the help for Axis text for the meaning of the other arguments - kwargs control the Text properties: + kwargs control the :class:`~matplotlib.text.Text` properties: %(Text)s """ @@ -951,11 +1013,11 @@ def subplots_adjust(self, *args, **kwargs): """ - subplots_adjust(self, left=None, bottom=None, right=None, top=None, - wspace=None, hspace=None) - fig.subplots_adjust(left=None, bottom=None, right=None, wspace=None, hspace=None): - Update the SubplotParams with kwargs (defaulting to rc where + fig.subplots_adjust(left=None, bottom=None, right=None, wspace=None, hspace=None) + + Update the :class:`SubplotParams` with *kwargs* (defaulting to rc where None) and update the subplot locations + """ self.subplotpars.update(*args, **kwargs) import matplotlib.axes @@ -994,14 +1056,14 @@ def figaspect(arg): """ - Create a figure with specified aspect ratio. If arg is a number, - use that aspect ratio. If arg is an array, figaspect will + Create a figure with specified aspect ratio. If *arg* is a number, + use that aspect ratio. If *arg* is an array, figaspect will determine the width and height for a figure that would fit array preserving aspect ratio. The figure width, height in inches are returned. Be sure to create an axes with equal with and height, eg - Example usage: + Example usage:: # make a figure twice as tall as it is wide w, h = figaspect(2.) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2008-06-19 12:15:34
|
Revision: 5591 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5591&view=rev Author: jdh2358 Date: 2008-06-19 05:15:20 -0700 (Thu, 19 Jun 2008) Log Message: ----------- added installing section to users guide Modified Paths: -------------- trunk/matplotlib/doc/users/index.rst trunk/matplotlib/doc/users/mathtext.rst trunk/matplotlib/lib/matplotlib/lines.py Modified: trunk/matplotlib/doc/users/index.rst =================================================================== --- trunk/matplotlib/doc/users/index.rst 2008-06-18 22:06:03 UTC (rev 5590) +++ trunk/matplotlib/doc/users/index.rst 2008-06-19 12:15:20 UTC (rev 5591) @@ -13,6 +13,7 @@ :maxdepth: 2 intro.rst + installing.rst pyplot_tutorial.rst navigation_toolbar.rst customizing.rst Modified: trunk/matplotlib/doc/users/mathtext.rst =================================================================== --- trunk/matplotlib/doc/users/mathtext.rst 2008-06-18 22:06:03 UTC (rev 5590) +++ trunk/matplotlib/doc/users/mathtext.rst 2008-06-19 12:15:20 UTC (rev 5591) @@ -4,7 +4,7 @@ ================================ You can use TeX markup in any matplotlib text string. Note that you -do not need to have TeX installed, since matplotlib ships its own TeX +do not need to have TeX installed, since matplotlib ships its own` TeX expression parser, layout engine and fonts. The layout engine is a fairly direct adaptation of the layout algorithms in Donald Knuth's TeX, so the quality is quite good (matplotlib also provides a Modified: trunk/matplotlib/lib/matplotlib/lines.py =================================================================== --- trunk/matplotlib/lib/matplotlib/lines.py 2008-06-18 22:06:03 UTC (rev 5590) +++ trunk/matplotlib/lib/matplotlib/lines.py 2008-06-19 12:15:20 UTC (rev 5591) @@ -837,7 +837,7 @@ def _draw_thin_diamond(self, renderer, gc, path, path_trans): offset = renderer.points_to_pixels(self._markersize) transform = Affine2D().translate(-0.5, -0.5) \ - .rotate_deg(45).scale(offset * 0.6, offset) + .rot<ate_deg(45).scale(offset * 0.6, offset) rgbFace = self._get_rgb_face() renderer.draw_markers(gc, Path.unit_rectangle(), transform, path, path_trans, rgbFace) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2008-06-19 13:16:39
|
Revision: 5593 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5593&view=rev Author: mdboom Date: 2008-06-19 06:16:16 -0700 (Thu, 19 Jun 2008) Log Message: ----------- Lots of docstring formatting fixes. Modified Paths: -------------- trunk/matplotlib/doc/faq/installing_faq.rst trunk/matplotlib/lib/matplotlib/__init__.py trunk/matplotlib/lib/matplotlib/artist.py trunk/matplotlib/lib/matplotlib/axes.py trunk/matplotlib/lib/matplotlib/backend_bases.py trunk/matplotlib/lib/matplotlib/contour.py trunk/matplotlib/lib/matplotlib/figure.py trunk/matplotlib/lib/matplotlib/image.py trunk/matplotlib/lib/matplotlib/lines.py trunk/matplotlib/lib/matplotlib/pyplot.py trunk/matplotlib/lib/matplotlib/quiver.py trunk/matplotlib/lib/matplotlib/text.py Modified: trunk/matplotlib/doc/faq/installing_faq.rst =================================================================== --- trunk/matplotlib/doc/faq/installing_faq.rst 2008-06-19 12:16:50 UTC (rev 5592) +++ trunk/matplotlib/doc/faq/installing_faq.rst 2008-06-19 13:16:16 UTC (rev 5593) @@ -55,8 +55,8 @@ easy_install -m PackageName -3. Delete any .egg files or directories from your `installation directory - <locating-matplotlib-install>`. +3. Delete any .egg files or directories from your :ref:`installation + directory <locating-matplotlib-install>`. Windows installer Modified: trunk/matplotlib/lib/matplotlib/__init__.py =================================================================== --- trunk/matplotlib/lib/matplotlib/__init__.py 2008-06-19 12:16:50 UTC (rev 5592) +++ trunk/matplotlib/lib/matplotlib/__init__.py 2008-06-19 13:16:16 UTC (rev 5593) @@ -684,11 +684,11 @@ def rc(group, **kwargs): """ - Set the current rc params. Group is the grouping for the rc, eg - for lines.linewidth the group is 'lines', for axes.facecolor, the - group is 'axes', and so on. Group may also be a list or tuple - of group names, eg ('xtick','ytick'). kwargs is a list of - attribute name/value pairs, eg:: + Set the current rc params. Group is the grouping for the rc, eg. + for ``lines.linewidth`` the group is ``lines``, for + ``axes.facecolor``, the group is ``axes``, and so on. Group may + also be a list or tuple of group names, eg. (*xtick*, *ytick*). + *kwargs* is a dictionary attribute name/value pairs, eg:: rc('lines', linewidth=2, color='r') @@ -728,7 +728,8 @@ rc('font', **font) # pass in the font dict as kwargs This enables you to easily switch between several configurations. - Use rcdefaults to restore the default rc params after changes. + Use :func:`~matplotlib.pyplot.rcdefaults` to restore the default + rc params after changes. """ aliases = { @@ -756,7 +757,7 @@ def rcdefaults(): """ Restore the default rc params - the ones that were created at - matplotlib load time + matplotlib load time. """ rcParams.update(rcParamsDefault) Modified: trunk/matplotlib/lib/matplotlib/artist.py =================================================================== --- trunk/matplotlib/lib/matplotlib/artist.py 2008-06-19 12:16:50 UTC (rev 5592) +++ trunk/matplotlib/lib/matplotlib/artist.py 2008-06-19 13:16:16 UTC (rev 5593) @@ -707,31 +707,32 @@ def setp(h, *args, **kwargs): """ - matplotlib supports the use of setp ("set property") and getp to set - and get object properties, as well as to do introspection on the - object For example, to set the linestyle of a line to be dashed, you - can do + matplotlib supports the use of :func:`setp` ("set property") and + :func:`getp` to set and get object properties, as well as to do + introspection on the object. For example, to set the linestyle of a + line to be dashed, you can do:: >>> line, = plot([1,2,3]) >>> setp(line, linestyle='--') If you want to know the valid types of arguments, you can provide the - name of the property you want to set without a value + name of the property you want to set without a value:: >>> setp(line, 'linestyle') linestyle: [ '-' | '--' | '-.' | ':' | 'steps' | 'None' ] If you want to see all the properties that can be set, and their - possible values, you can do + possible values, you can do:: >>> setp(line) ... long output listing omitted - setp operates on a single instance or a list of instances. If you - are in query mode introspecting the possible values, only the first - instance in the sequence is used. When actually setting values, - all the instances will be set. Eg, suppose you have a list of two - lines, the following will make both lines thicker and red + :func:`setp` operates on a single instance or a list of instances. + If you are in query mode introspecting the possible values, only + the first instance in the sequence is used. When actually setting + values, all the instances will be set. Eg., suppose you have a + list of two lines, the following will make both lines thicker and + red:: >>> x = arange(0,1.0,0.01) >>> y1 = sin(2*pi*x) @@ -739,8 +740,8 @@ >>> lines = plot(x, y1, x, y2) >>> setp(lines, linewidth=2, color='r') - setp works with the matlab(TM) style string/value pairs or with - python kwargs. For example, the following are equivalent + :func:`setp` works with the matlab(TM) style string/value pairs or + with python kwargs. For example, the following are equivalent >>> setp(lines, 'linewidth', 2, 'color', r') # matlab style >>> setp(lines, linewidth=2, color='r') # python style Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2008-06-19 12:16:50 UTC (rev 5592) +++ trunk/matplotlib/lib/matplotlib/axes.py 2008-06-19 13:16:16 UTC (rev 5593) @@ -1546,17 +1546,18 @@ grid(self, b=None, **kwargs) - Set the axes grids on or off; b is a boolean + Set the axes grids on or off; *b* is a boolean - if b is None and len(kwargs)==0, toggle the grid state. if - kwargs are supplied, it is assumed that you want a grid and b - is thus set to True + If *b* is *None* and len(kwargs)==0, toggle the grid state. If + kwargs are supplied, it is assumed that you want a grid and *b* + is thus set to *True* kawrgs are used to set the grid line properties, eg:: ax.grid(color='r', linestyle='-', linewidth=2) - Valid Line2D kwargs are + Valid :class:`~matplotlib.lines.Line2D` kwargs are + %(Line2D)s """ if len(kwargs): b = True @@ -2457,40 +2458,44 @@ text(x, y, s, fontdict=None, **kwargs) - Add text in string s to axis at location x,y (data coords) + Add text in string *s* to axis at location *x*, *y*, data + coordinates. Keyword arguments: - fontdict: - a dictionary to override the default text properties. - If fontdict is None, the defaults are determined by your rc + *fontdict*: + A dictionary to override the default text properties. + If *fontdict* is *None*, the defaults are determined by your rc parameters. - withdash: [ False | True ] - creates a TextWithDash instance instead of a Text instance. + *withdash*: [ False | True ] + Creates a :class:`~matplotlib.text.TextWithDash` instance + instead of a :class:`~matplotlib.text.Text` instance. + Individual keyword arguments can be used to override any given parameter:: text(x, y, s, fontsize=12) The default transform specifies that text is in data coords, - alternatively, you can specify text in axis coords (0,0 lower left and - 1,1 upper right). The example below places text in the center of the - axes:: + alternatively, you can specify text in axis coords (0,0 is + lower-left and 1,1 is upper-right). The example below places + text in the center of the axes:: text(0.5, 0.5,'matplotlib', horizontalalignment='center', verticalalignment='center', transform = ax.transAxes) - You can put a rectangular box around the text instance (eg to - set a background color) by using the keyword bbox. bbox is a - dictionary of patches.Rectangle properties (see help - for Rectangle for a list of these). For example:: + You can put a rectangular box around the text instance (eg. to + set a background color) by using the keyword *bbox*. *bbox* is + a dictionary of :class:`matplotlib.patches.Rectangle` + properties. For example:: text(x, y, s, bbox=dict(facecolor='red', alpha=0.5)) - Valid kwargs are Text properties + Valid kwargs are :class:`matplotlib.text.Text` properties: + %(Text)s """ default = { @@ -2536,6 +2541,7 @@ textcoords='data', arrowprops=None, **kwargs) Keyword arguments: + %(Annotation)s """ a = mtext.Annotation(*args, **kwargs) @@ -2556,30 +2562,33 @@ Axis Horizontal Line - Draw a horizontal line at y from xmin to xmax. With the default - values of xmin=0 and xmax=1, this line will always span the horizontal - extent of the axes, regardless of the xlim settings, even if you - change them, eg with the xlim command. That is, the horizontal extent - is in axes coords: 0=left, 0.5=middle, 1.0=right but the y location is - in data coordinates. + Draw a horizontal line at *y* from *xmin* to *xmax*. With the + default values of *xmin* = 0 and *xmax* = 1, this line will + always span the horizontal extent of the axes, regardless of + the xlim settings, even if you change them, eg. with the + :meth:`set_xlim` command. That is, the horizontal extent is + in axes coords: 0=left, 0.5=middle, 1.0=right but the *y* + location is in data coordinates. - Return value is the Line2D instance. kwargs are the same as kwargs to - plot, and can be used to control the line properties. Eg + Return value is the :class:`~matplotlib.lines.Line2D` + instance. kwargs are the same as kwargs to plot, and can be + used to control the line properties. Eg., - * draw a thick red hline at y=0 that spans the xrange + * draw a thick red hline at *y* = 0 that spans the xrange >>> axhline(linewidth=4, color='r') - * draw a default hline at y=1 that spans the xrange + * draw a default hline at *y* = 1 that spans the xrange >>> axhline(y=1) - * draw a default hline at y=.5 that spans the the middle half of + * draw a default hline at *y* = .5 that spans the the middle half of the xrange >>> axhline(y=.5, xmin=0.25, xmax=0.75) - Valid kwargs are Line2D properties + Valid kwargs are :class:`~matplotlib.lines.Line2D` properties: + %(Line2D)s """ @@ -2603,30 +2612,33 @@ Axis Vertical Line - Draw a vertical line at x from ymin to ymax. With the default values - of ymin=0 and ymax=1, this line will always span the vertical extent - of the axes, regardless of the xlim settings, even if you change them, - eg with the xlim command. That is, the vertical extent is in axes - coords: 0=bottom, 0.5=middle, 1.0=top but the x location is in data - coordinates. + Draw a vertical line at *x* from *ymin* to *ymax*. With the + default values of *ymin* = 0 and *ymax* = 1, this line will + always span the vertical extent of the axes, regardless of the + xlim settings, even if you change them, eg. with the + :meth:`set_xlim` command. That is, the vertical extent is in + axes coords: 0=bottom, 0.5=middle, 1.0=top but the *x* location + is in data coordinates. - Return value is the Line2D instance. kwargs are the same as - kwargs to plot, and can be used to control the line properties. Eg + Return value is the :class:`~matplotlib.lines.Line2D` + instance. kwargs are the same as kwargs to plot, and can be + used to control the line properties. Eg., - * draw a thick red vline at x=0 that spans the yrange + * draw a thick red vline at *x* = 0 that spans the yrange >>> axvline(linewidth=4, color='r') - * draw a default vline at x=1 that spans the yrange + * draw a default vline at *x* = 1 that spans the yrange >>> axvline(x=1) - * draw a default vline at x=.5 that spans the the middle half of + * draw a default vline at *x* = .5 that spans the the middle half of the yrange >>> axvline(x=.5, ymin=0.25, ymax=0.75) - Valid kwargs are Line2D properties + Valid kwargs are :class:`~matplotlib.lines.Line2D` properties: + %(Line2D)s """ @@ -2648,26 +2660,31 @@ axhspan(ymin, ymax, xmin=0, xmax=1, **kwargs) - Axis Horizontal Span. ycoords are in data units and x - coords are in axes (relative 0-1) units + Axis Horizontal Span. - Draw a horizontal span (regtangle) from ymin to ymax. With the - default values of xmin=0 and xmax=1, this always span the xrange, - regardless of the xlim settings, even if you change them, eg with the - xlim command. That is, the horizontal extent is in axes coords: - 0=left, 0.5=middle, 1.0=right but the y location is in data + *y* coords are in data units and *x* coords are in axes (relative + 0-1) units. + + Draw a horizontal span (rectangle) from *ymin* to *ymax*. + With the default values of *xmin* = 0 and *xmax* = 1, this + always span the xrange, regardless of the xlim settings, even + if you change them, eg. with the :meth:`set_xlim` command. + That is, the horizontal extent is in axes coords: 0=left, + 0.5=middle, 1.0=right but the *y* location is in data coordinates. - Return value is the patches.Polygon instance. + Return value is a :class:`matplotlib.patches.Polygon` + instance. Examples: - * draw a gray rectangle from y=0.25-0.75 that spans the horizontal - extent of the axes + * draw a gray rectangle from *y* = 0.25-0.75 that spans the + horizontal extent of the axes >>> axhspan(0.25, 0.75, facecolor='0.5', alpha=0.5) - Valid kwargs are Polygon properties + Valid kwargs are :class:`~matplotlib.patches.Polygon` properties: + %(Polygon)s """ # convert y axis units @@ -2686,17 +2703,21 @@ axvspan(xmin, xmax, ymin=0, ymax=1, **kwargs) - Axis Vertical Span. xcoords are in data units and y coords - are in axes (relative 0-1) units + Axis Vertical Span. - Draw a vertical span (regtangle) from xmin to xmax. With the default - values of ymin=0 and ymax=1, this always span the yrange, regardless - of the ylim settings, even if you change them, eg with the ylim - command. That is, the vertical extent is in axes coords: 0=bottom, - 0.5=middle, 1.0=top but the y location is in data coordinates. + *x* coords are in data units and *y* coords are in axes (relative + 0-1) units. - return value is the patches.Polygon instance. + Draw a vertical span (rectangle) from *xmin* to *xmax*. With + the default values of *ymin* = 0 and *ymax* = 1, this always + span the yrange, regardless of the ylim settings, even if you + change them, eg. with the :meth:`set_ylim` command. That is, + the vertical extent is in axes coords: 0=bottom, 0.5=middle, + 1.0=top but the *y* location is in data coordinates. + Return value is the :class:`matplotlib.patches.Polygon` + instance. + Examples: * draw a vertical green translucent rectangle from x=1.25 to 1.55 that @@ -2704,7 +2725,9 @@ >>> axvspan(1.25, 1.55, facecolor='g', alpha=0.5) - Valid kwargs are Polygon properties: + Valid kwargs are :class:`~matplotlib.patches.Polygon` + properties: + %(Polygon)s """ # convert x axis units @@ -2725,27 +2748,28 @@ hlines(y, xmin, xmax, colors='k', linestyle='solid', **kwargs) - plot horizontal lines at each y from xmin to xmax. + Plot horizontal lines at each *y* from *xmin* to *xmax*. - Returns the LineCollection that was added + Returns the :class:`~matplotlib.collections.LineCollection` + that was added. Required arguments: - y: + *y*: a 1-D numpy array or iterable. - xmin and xmax: - can be scalars or len(x) numpy arrays. If they are scalars, then - the respective values are constant, else the widths of the lines - are determined by xmin and xmax + *xmin* and *xmax*: + can be scalars or ``len(x)`` numpy arrays. If they are + scalars, then the respective values are constant, else the + widths of the lines are determined by *xmin* and *xmax*. Optional keyword arguments: - colors: + *colors*: a line collections color argument, either a single color - or a len(y) list of colors + or a ``len(y)`` list of colors - linestyle: + *linestyle*: [ 'solid' | 'dashed' | 'dashdot' | 'dotted' ] """ @@ -2800,20 +2824,21 @@ vlines(x, ymin, ymax, color='k') - Plot vertical lines at each x from ymin to ymax. ymin or ymax can be - scalars or len(x) numpy arrays. If they are scalars, then the - respective values are constant, else the heights of the lines are - determined by ymin and ymax + Plot vertical lines at each *x* from *ymin* to *ymax*. *ymin* + or *ymax* can be scalars or len(*x*) numpy arrays. If they are + scalars, then the respective values are constant, else the + heights of the lines are determined by *ymin* and *ymax*. + *colors* is a line collections color args, either a single color + or a len(*x*) list of colors - colors is a line collections color args, either a single color - or a len(x) list of colors + *linestyle* is one of [ 'solid' | 'dashed' | 'dashdot' | 'dotted' ] - linestyle is one of [ 'solid' | 'dashed' | 'dashdot' | 'dotted' ] + Returns the :class:`matplotlib.collections.LineCollection` + that was added. - Returns the collections.LineCollection that was added + kwargs are :class:`~matplotlib.collections.LineCollection` properties: - kwargs are collections.LineCollection properties: %(LineCollection)s """ @@ -2870,19 +2895,22 @@ #### Basic plotting def plot(self, *args, **kwargs): """ - Plot lines and/or markers to the Axes. ``*args`` is a variable length - argument, allowing for multiple *x*, *y* pairs with an optional format - string. For example, each of the following is legal:: + Plot lines and/or markers to the + :class:`~matplotlib.axes.Axes`. *args* is a variable length + argument, allowing for multiple *x*, *y* pairs with an + optional format string. For example, each of the following is + legal:: plot(x, y) # plot x and y using the default line style and color plot(x, y, 'bo') # plot x and y using blue circle markers plot(y) # plot y using x as index array 0..N-1 plot(y, 'r+') # ditto, but with red plusses - If ``x`` and/or ``y`` is 2-dimensional, then the corresponding columns + If *x* and/or *y* is 2-dimensional, then the corresponding columns will be plotted. - An arbitrary number of ``x``, ``y``, ``fmt`` groups can be specified, as in:: + An arbitrary number of *x*, *y*, *fmt* groups can be + specified, as in:: a.plot(x1, y1, 'g^', x2, y2, 'g-') @@ -2929,16 +2957,16 @@ w # white In addition, you can specify colors in many weird and - wonderful ways, including full names (``'green'``), hex strings - (``'#008000'``), RGB or RGBA tuples (``(0,1,0,1)``) or grayscale - intensities as a string (``'0.8'``). Of these, the string - specifications can be used in place of a ``fmt`` group, but the - tuple forms can be used only as ``kwargs``. + wonderful ways, including full names (``'green'``), hex + strings (``'#008000'``), RGB or RGBA tuples (``(0,1,0,1)``) or + grayscale intensities as a string (``'0.8'``). Of these, the + string specifications can be used in place of a ``fmt`` group, + but the tuple forms can be used only as ``kwargs``. Line styles and colors are combined in a single format string, as in ``'bo'`` for blue circles. - The ``**kwargs`` can be used to set line properties (any property that has + The *kwargs* can be used to set line properties (any property that has a ``set_*`` method). You can use this to set a line label (for auto legends), linewidth, anitialising, marker face color, etc. Here is an example:: @@ -2948,19 +2976,21 @@ axis([0, 4, 0, 10]) legend() - If you make multiple lines with one plot command, the ``kwargs`` apply - to all those lines, e.g.:: + If you make multiple lines with one plot command, the kwargs + apply to all those lines, e.g.:: plot(x1, y1, x2, y2, antialised=False) Neither line will be antialiased. - The kwargs are Line2D properties: + The kwargs are :class:`~matplotlib.lines.Line2D` properties: + %(Line2D)s - kwargs ``scalex`` and ``scaley``, if defined, are passed on to - :meth:`autoscale_view` to determine whether the *x* and *y* axes - are autoscaled; the default is ``True``. + kwargs *scalex* and *scaley*, if defined, are passed on to + :meth:`~matplotlib.axes.Axes.autoscale_view` to determine + whether the *x* and *y* axes are autoscaled; the default is + *True*. """ scalex = kwargs.pop( 'scalex', True) scaley = kwargs.pop( 'scaley', True) @@ -2985,36 +3015,48 @@ plot_date(x, y, fmt='bo', tz=None, xdate=True, ydate=False, **kwargs) - Similar to the plot() command, except the x or y (or both) data - is considered to be dates, and the axis is labeled accordingly. + Similar to the :func:`~matplotlib.pyplot.plot` command, except + the *x* or *y* (or both) data is considered to be dates, and the + axis is labeled accordingly. - x and/or y can be a sequence of dates represented as float days since + *x* and/or *y* can be a sequence of dates represented as float days since 0001-01-01 UTC. - See dates for helper functions date2num, num2date - and drange for help on creating the required floating point dates + See :mod:`~matplotlib.dates` for helper functions + :func:`~matplotlib.dates.date2num`, + :func:`~matplotlib.dates.num2date` and + :func:`~matplotlib.dates.drange` for help on creating the + required floating point dates. Keyword arguments: - fmt: string + *fmt*: string The plot format string. - tz: [ None | timezone string ] - The time zone to use in labeling dates. If None, defaults to rc + + *tz*: [ None | timezone string ] + The time zone to use in labeling dates. If *None*, defaults to rc value. - xdate: [ True | False ] - If True, the x-axis will be labeled with dates. - ydate: [ False | True ] - If True, the y-axis will be labeled with dates. + *xdate*: [ True | False ] + If *True*, the *x*-axis will be labeled with dates. + + *ydate*: [ False | True ] + If *True*, the *y*-axis will be labeled with dates. + Note if you are using custom date tickers and formatters, it may be necessary to set the formatters/locators after the call - to plot_date since plot_date will set the default tick locator - to ticker.AutoDateLocator (if the tick locator is not already set to - a ticker.DateLocator instance) and the default tick formatter to - AutoDateFormatter (if the tick formatter is not already set to - a DateFormatter instance). + to :meth:`plot_date` since :meth:`plot_date` will set the + default tick locator to + :class:`matplotlib.ticker.AutoDateLocator` (if the tick + locator is not already set to a + :class:`matplotlib.ticker.DateLocator` instance) and the + default tick formatter to + :class:`matplotlib.ticker.AutoDateFormatter` (if the tick + formatter is not already set to a + :class:`matplotlib.ticker.DateFormatter` instance). - Valid kwargs are Line2D properties: + Valid kwargs are :class:`~matplotlib.lines.Line2D` properties: + %(Line2D)s """ @@ -3040,22 +3082,27 @@ loglog(*args, **kwargs) - Make a plot with log scaling on the x and y axis. The args to loglog - are the same as the args to plot. See plot for more info. + Make a plot with log scaling on the *x* and *y* axis. - loglog supports all the keyword arguments of plot and - Axes.set_xscale/Axes.set_yscale. + :func:`~matplotlib.pyplot.loglog` supports all the keyword + arguments of :func:`~matplotlib.pyplot.plot` and + :meth:`matplotlib.axes.Axes.set_xscale`/:meth:`matplotlib.axes.Axes.set_yscale`. Notable keyword arguments: - basex/basey: scalar > 1 - base of the x/y logarithm - subsx/subsy: [ None | sequence ] - the location of the minor x/yticks; None defaults to - autosubs, which depend on the number of decades in the - plot; see set_xscale/set_yscale for details + *basex*/*basey*: scalar > 1 + base of the *x*/*y* logarithm - The remaining valid kwargs are Line2D properties: + *subsx*/*subsy*: [ None | sequence ] + the location of the minor *x*/*y* ticks; *None* defaults + to autosubs, which depend on the number of decades in the + plot; see + :meth:`matplotlib.axes.Axes.set_xscale`/:meth:`matplotlib.axes.Axes.set_yscale` + for details + + The remaining valid kwargs are + :class:`~matplotlib.lines.Line2D` properties: + %(Line2D)s """ if not self._hold: self.cla() @@ -3084,23 +3131,26 @@ semilogx(*args, **kwargs) - Make a plot with log scaling on the x axis. The args to - semilogx are the same as the args to plot. See plot for - more info. + Make a plot with log scaling on the *x* axis. - semilogx supports all the keyword arguments of plot and - Axes.set_xscale. + :func:`semilogx` supports all the keyword arguments of + :func:`~matplotlib.pyplot.plot` and + :meth:`matplotlib.axes.Axes.set_xscale`. Notable keyword arguments: - basex: scalar > 1 - base of the x logarithm - subsx: [ None | sequence ] - the location of the minor xticks; None defaults to + *basex*: scalar > 1 + base of the *x* logarithm + + *subsx*: [ None | sequence ] + The location of the minor xticks; *None* defaults to autosubs, which depend on the number of decades in the - plot; see set_xscale for details + plot; see :meth:`~matplotlib.axes.Axes.set_xscale` for + details. - The remaining valid kwargs are Line2D properties: + The remaining valid kwargs are + :class:`~matplotlib.lines.Line2D` properties: + %(Line2D)s """ if not self._hold: self.cla() @@ -3122,23 +3172,26 @@ semilogy(*args, **kwargs) - Make a plot with log scaling on the y axis. The args to - semilogy are the same as the args to plot. See plot for - more info. + Make a plot with log scaling on the *y* axis. - semilogy supports all the keyword arguments of plot and - Axes.set_yscale. + :func:`semilogy` supports all the keyword arguments of + :func:`~matplotlib.pylab.plot` and + :meth:`matplotlib.axes.Axes.set_yscale`. Notable keyword arguments: - basey: scalar > 1 - base of the y logarithm - subsy: [ None | sequence ] - the location of the minor yticks; None defaults to + *basey*: scalar > 1 + Base of the *y* logarithm + + *subsy*: [ None | sequence ] + The location of the minor yticks; *None* defaults to autosubs, which depend on the number of decades in the - plot; see set_yscale for details + plot; see :meth:`~matplotlib.axes.Axes.set_yscale` for + details. - The remaining valid kwargs are Line2D properties: + The remaining valid kwargs are + :class:`~matplotlib.lines.Line2D` properties: + %(Line2D)s """ if not self._hold: self.cla() @@ -3161,33 +3214,47 @@ acorr(x, normed=False, detrend=mlab.detrend_none, usevlines=False, maxlags=None, **kwargs) - Plot the autocorrelation of x. If normed=True, normalize the - data but the autocorrelation at 0-th lag. x is detrended by - the detrend callable (default no normalization. + Plot the autocorrelation of *x*. If *normed* = *True*, + normalize the data but the autocorrelation at 0-th lag. *x* is + detrended by the *detrend* callable (default no normalization). - data are plotted as ``plot(lags, c, **kwargs)`` + Data are plotted as ``plot(lags, c, **kwargs)`` - return value is lags, c, line where lags are a length - 2*maxlags+1 lag vector, c is the 2*maxlags+1 auto correlation - vector, and line is a Line2D instance returned by plot. The - default linestyle is None and the default marker is 'o', - though these can be overridden with keyword args. The cross - correlation is performed with numpy correlate with - mode=2. + Return value is a tuple (*lags*, *c*, *line*) where: - If usevlines is True, Axes.vlines rather than Axes.plot is used - to draw vertical lines from the origin to the acorr. - Otherwise the plotstyle is determined by the kwargs, which are - Line2D properties. If usevlines, the return value is lags, c, - linecol, b where linecol is the collections.LineCollection and b is the x-axis + - *lags* are a length 2*maxlags+1 lag vector - if usevlines=True, kwargs are passed onto Axes.vlines - if usevlines=False, kwargs are passed onto Axes.plot + - *c* is the 2*maxlags+1 auto correlation vector - maxlags is a positive integer detailing the number of lags to show. - The default value of None will return all (2*len(x)-1) lags. + - *line* is a :class:`~matplotlib.lines.Line2D` instance + returned by :meth:`plot` - See the respective function for documentation on valid kwargs + The default *linestyle* is None and the default *marker* is + ``'o'``, though these can be overridden with keyword args. + The cross correlation is performed with :func:`numpy.correlate` with + *mode* = 2. + + If *usevlines* is *True*: + + :meth:`~matplotlib.axes.Axes.vlines` rather than + :meth:`~matplotlib.axes.Axes.plot` is used to draw + vertical lines from the origin to the acorr. Otherwise, + the plot style is determined by the kwargs, which are + :class:`~matplotlib.lines.Line2D` properties. The return + value is a tuple (*lags*, *c*, *linecol*, *b*) where + + - *linecol* is the + :class:`~matplotlib.collections.LineCollection` + + - *b* is the *x*-axis. + + *maxlags* is a positive integer detailing the number of lags + to show. The default value of *None* will return all + ``(2*len(x)-1)`` lags. + + See the respective :meth:`~matplotlib.axes.Axes.plot` or + :meth:`~matplotlib.axes.Axes.vlines` functions for + documentation on valid kwargs. """ return self.xcorr(x, x, **kwargs) acorr.__doc__ = cbook.dedent(acorr.__doc__) % martist.kwdocd @@ -3200,35 +3267,42 @@ xcorr(x, y, normed=False, detrend=mlab.detrend_none, usevlines=False, **kwargs): - Plot the cross correlation between x and y. If normed=True, - normalize the data but the cross correlation at 0-th lag. x - and y are detrended by the detrend callable (default no - normalization. x and y must be equal length + Plot the cross correlation between *x* and *y*. If *normed* = + *True*, normalize the data but the cross correlation at 0-th + lag. *x* and y are detrended by the *detrend* callable + (default no normalization). *x* and *y* must be equal length. - data are plotted as ``plot(lags, c, **kwargs)`` + Data are plotted as ``plot(lags, c, **kwargs)`` - return value is lags, c, line where lags are a length - ``2*maxlags+1`` lag vector, c is the ``2*maxlags+1`` auto correlation - vector, and line is a Line2D instance returned by plot. The - default linestyle is None and the default marker is 'o', - though these can be overridden with keyword args. The cross - correlation is performed with numpy correlate with - mode=2. + Return value is a tuple (*lags*, *c*, *line*) where: - If usevlines is True, Axes.vlines rather than Axes.plot is used - to draw vertical lines from the origin to the acorr. - Otherwise the plotstyle is determined by the kwargs, which are - Line2D properties. If usevlines, the return value is lags, c, - linecol, b where linecol is the collections.LineCollection and b is the - x-axis + - *lags* are a length ``2*maxlags+1`` lag vector - if ``usevlines=True``, kwargs are passed onto Axes.vlines - if ``usevlines=False``, kwargs are passed onto Axes.plot + - *c* is the ``2*maxlags+1`` auto correlation vector - maxlags is a positive integer detailing the number of lags to show. - The default value of None will return all ``(2*len(x)-1)`` lags. + - *line* is a :class:`~matplotlib.lines.Line2D` instance + returned by :func:`~matplotlib.pyplot.plot`. - See the respective function for documentation on valid kwargs + The default *linestyle* is *None* and the default *marker* is + 'o', though these can be overridden with keyword args. The + cross correlation is performed with :func:`numpy.correlate` + with *mode* = 2. + + If *usevlines* is *True*: + + :func:`~matplotlib.pyplot.vlines` + rather than :func:`~matplotlib.pyplot.plot` is used to draw + vertical lines from the origin to the xcorr. Otherwise the + plotstyle is determined by the kwargs, which are + :class:`~matplotlib.lines.Line2D` properties. + + The return value is a tuple (*lags*, *c*, *linecol*, *b*) + where *linecol* is the + :class:`matplotlib.collections.LineCollection` instance and + *b* is the *x*-axis. + + *maxlags* is a positive integer detailing the number of lags to show. + The default value of *None* will return all ``(2*len(x)-1)`` lags. """ Nx = len(x) @@ -3269,20 +3343,27 @@ legend(*args, **kwargs) - Place a legend on the current axes at location loc. Labels are a - sequence of strings and loc can be a string or an integer specifying - the legend location + Place a legend on the current axes at location *loc*. Labels are a + sequence of strings and *loc* can be a string or an integer specifying + the legend location. To make a legend with existing lines:: legend() - legend by itself will try and build a legend using the label + :meth:`legend` by itself will try and build a legend using the label property of the lines/patches/collections. You can set the label of - a line by doing plot(x, y, label='my data') or line.set_label('my - data'). If label is set to '_nolegend_', the item will not be shown - in legend. + a line by doing:: + plot(x, y, label='my data') + + or:: + + line.set_label('my data'). + + If label is set to '_nolegend_', the item will not be shown in + legend. + To automatically generate the legend from labels:: legend( ('label1', 'label2', 'label3') ) @@ -3325,32 +3406,41 @@ Keyword arguments: - isaxes: [ True | False ] + *isaxes*: [ True | False ] Indicates that this is an axes legend - numpoints: integer + + *numpoints*: integer The number of points in the legend line, default is 4 - prop: [ None | FontProperties ] - A FontProperties instance, or None to use rc settings. - see :class:`~matplotlib.font_manager.FontProperties` - pad: [ None | scalar ] + + *prop*: [ None | FontProperties ] + A :class:`matplotlib.font_manager.FontProperties` + instance, or *None* to use rc settings. + + *pad*: [ None | scalar ] The fractional whitespace inside the legend border, between 0 and 1. - If None, use rc settings - markerscale: [ None | scalar ] - The relative size of legend markers vs. original. If None, use rc - settings - shadow: [ None | False | True ] - If True, draw a shadow behind legend. If None, use rc settings. - labelsep: [ None | scalar ] - The vertical space between the legend entries. If None, use rc - settings - handlelen: [ None | scalar ] - The length of the legend lines. If None, use rc settings. - handletextsep: [ None | scalar ] - The space between the legend line and legend text. If None, use rc + If *None*, use rc settings. + + *markerscale*: [ None | scalar ] + The relative size of legend markers vs. original. If *None*, use rc settings. - axespad: [ None | scalar ] - The border between the axes and legend edge. If None, use rc + + *shadow*: [ None | False | True ] + If *True*, draw a shadow behind legend. If *None*, use rc settings. + + *labelsep*: [ None | scalar ] + The vertical space between the legend entries. If *None*, use rc settings. + + *handlelen*: [ None | scalar ] + The length of the legend lines. If *None*, use rc settings. + + *handletextsep*: [ None | scalar ] + The space between the legend line and legend text. If *None*, use rc + settings. + + *axespad*: [ None | scalar ] + The border between the axes and legend edge. If *None*, use rc + settings. """ def get_handles(): @@ -3409,21 +3499,21 @@ step(x, y, *args, **kwargs) - x and y must be 1-D sequences, and it is assumed, but not checked, - that x is uniformly increasing. + Make a step plot. Additional keyword args to :func:`step` are the same + as those for :func:`~matplotlib.pyplot.plot`. + *x* and *y* must be 1-D sequences, and it is assumed, but not checked, + that *x* is uniformly increasing. + Keyword arguments: - where: [ 'pre' | 'post' | 'mid' ] - if 'pre', the interval from x[i] to x[i+1] has level y[i] + *where*: [ 'pre' | 'post' | 'mid' ] + If 'pre', the interval from x[i] to x[i+1] has level y[i] - if 'post', that interval has level y[i+1] + If 'post', that interval has level y[i+1] - if 'mid', the jumps in y occur half-way between the x-values. - - Make a step plot. Additional keyword args to step are the same - as those for plot. See plot for more info. - + If 'mid', the jumps in *y* occur half-way between the + *x*-values. ''' where = kwargs.pop('where', 'pre') @@ -3450,12 +3540,14 @@ Make a bar plot with rectangles bounded by: - left, left+width, bottom, bottom+height + *left*, *left* + *width*, *bottom*, *bottom* + *height* (left, right, bottom and top edges) - left, height, width, and bottom can be either scalars or sequences + *left*, *height*, *width*, and *bottom* can be either scalars + or sequences - Return value is a list of Rectangle patch instances + Return value is a list of + :class:`matplotlib.patches.Rectangle` instances. Required arguments: @@ -3488,18 +3580,20 @@ axis as-is; True sets it to log scale ============= =================================================== - For vertical bars, align='edge' aligns bars by their left edges in - left, while 'center' interprets these values as the x coordinates of - the bar centers. For horizontal bars, 'edge' aligns bars by their - bottom edges in bottom, while 'center' interprets these values as the - y coordinates of the bar centers. + For vertical bars, *align* = 'edge' aligns bars by their left + edges in left, while *align* = 'center' interprets these + values as the *x* coordinates of the bar centers. For + horizontal bars, *align* = 'edge' aligns bars by their bottom + edges in bottom, while *align* = 'center' interprets these + values as the *y* coordinates of the bar centers. - The optional arguments color, edgecolor, linewidth, xerr, and yerr can - be either scalars or sequences of length equal to the number of bars. - This enables you to use bar as the basis for stacked bar charts, or - candlestick plots. + The optional arguments *color*, *edgecolor*, *linewidth*, + *xerr*, and *yerr* can be either scalars or sequences of + length equal to the number of bars. This enables you to use + bar as the basis for stacked bar charts, or candlestick plots. Other optional kwargs: + %(Rectangle)s """ if not self._hold: self.cla() @@ -3698,12 +3792,14 @@ Make a horizontal bar plot with rectangles bounded by: - left, left+width, bottom, bottom+height + *left*, *left* + *width*, *bottom*, *bottom* + *height* (left, right, bottom and top edges) - bottom, width, height, and left can be either scalars or sequences + *bottom*, *width*, *height*, and *left* can be either scalars + or sequences - Return value is a list of Rectangle patch instances + Return value is a list of + :class:`matplotlib.patches.Rectangle` instances. Required arguments: @@ -3735,16 +3831,18 @@ axis as-is; True sets it to log scale ============= =================================================== - Setting align='edge' aligns bars by their bottom edges in bottom, - while 'center' interprets these values as the y coordinates of the bar - centers. + Setting *align* = 'edge' aligns bars by their bottom edges in + bottom, while *align* = 'center' interprets these values as + the *y* coordinates of the bar centers. - The optional arguments color, edgecolor, linewidth, xerr, and yerr can - be either scalars or sequences of length equal to the number of bars. - This enables you to use barh as the basis for stacked bar charts, or - candlestick plots. + The optional arguments *color*, *edgecolor*, *linewidth*, + *xerr*, and *yerr* can be either scalars or sequences of + length equal to the number of bars. This enables you to use + barh as the basis for stacked bar charts, or candlestick + plots. other optional kwargs: + %(Rectangle)s """ @@ -3760,8 +3858,8 @@ broken_barh(self, xranges, yrange, **kwargs) - A collection of horizontal bars spanning yrange with a sequence of - xranges + A collection of horizontal bars spanning *yrange* with a sequence of + *xranges*. Required arguments: @@ -3772,7 +3870,10 @@ yrange sequence of (ymin, ywidth) ======== ========================== - kwargs are collections.BrokenBarHCollection properties: + kwargs are + :class:`matplotlib.collections.BrokenBarHCollection` + properties: + %(BrokenBarHCollection)s these can either be a single argument, ie:: @@ -3781,8 +3882,7 @@ or a sequence of arguments for the various bars, ie:: - facecolors = 'black', 'red', 'green' - + facecolors = ('black', 'red', 'green') """ col = mcoll.BrokenBarHCollection(xranges, yrange, **kwargs) self.add_collection(col, autolim=True) @@ -3798,15 +3898,17 @@ stem(x, y, linefmt='b-', markerfmt='bo', basefmt='r-') - A stem plot plots vertical lines (using linefmt) at each x location - from the baseline to y, and places a marker there using markerfmt. A - horizontal line at 0 is is plotted using basefmt + A stem plot plots vertical lines (using *linefmt*) at each *x* + location from the baseline to *y*, and places a marker there + using *markerfmt*. A horizontal line at 0 is is plotted using + *basefmt*. - Return value is (markerline, stemlines, baseline) . + Return value is a tuple (*markerline*, *stemlines*, + *baseline*). - See - http://www.mathworks.com/access/helpdesk/help/techdoc/ref/stem.html - for details and examples/stem_plot.py for a demo. + See `this document + <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/stem.html>`_ + for details and :file:`examples/pylab_examples/stem_plot.py` for a demo. """ remember_hold=self._hold if not self._hold: self.cla() @@ -3829,56 +3931,68 @@ def pie(self, x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1): - """ + r""" call signature:: pie(x, explode=None, labels=None, colors=('b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'), autopct=None, pctdistance=0.6, labeldistance=1.1, shadow=False) - Make a pie chart of array x. The fractional area of each wedge is - given by x/sum(x). If sum(x)<=1, then the values of x give the - fractional area directly and the array will not be normalized. + Make a pie chart of array *x*. The fractional area of each + wedge is given by x/sum(x). If sum(x) <= 1, then the values + of x give the fractional area directly and the array will not + be normalized. Keyword arguments: - explode: [ None | len(x) sequence ] - If not None, is a len(x) array which specifies the + *explode*: [ None | len(x) sequence ] + If not *None*, is a len(*x*) array which specifies the fraction of the radius with which to offset each wedge. - colors: [ None | color sequence ] + + *colors*: [ None | color sequence ] A sequence of matplotlib color args through which the pie chart will cycle. - labels: [ None | len(x) sequence of strings ] + + *labels*: [ None | len(x) sequence of strings ] A sequence of strings providing the labels for each wedge - autopct: [ None | format string | format function ] - If not None, is a string or function used to label the + + *autopct*: [ None | format string | format function ] + If not *None*, is a string or function used to label the wedges with their numeric value. The label will be placed inside - the wedge. If it is a format string, the label will be fmt%pct. - If it is a function, it will be called - pctdistance: scalar - The ratio between the center of each pie slice and the start of the - text generated by autopct. Ignored if autopct is None; default is - 0.6. - labeldistance: scalar + the wedge. If it is a format string, the label will be ``fmt%pct``. + If it is a function, it will be called. + + *pctdistance*: scalar + The ratio between the center of each pie slice and the + start of the text generated by *autopct*. Ignored if + *autopct* is *None*; default is 0.6. + + *labeldistance*: scalar The radial distance at which the pie labels are drawn - shadow: [ False | True ] + + *shadow*: [ False | True ] Draw a shadow beneath the pie. The pie chart will probably look best if the figure and axes are - square. Eg:: + square. Eg.:: figure(figsize=(8,8)) ax = axes([0.1, 0.1, 0.8, 0.8]) Return value: - If autopct is None, return a list of (patches, texts), where patches - is a sequence of mpatches.Wedge instances and texts is a - list of the label Text instnaces + If *autopct* is None, return the tuple (*patches*, *texts*): - If autopct is not None, return (patches, texts, autotexts), where - patches and texts are as above, and autotexts is a list of text - instances for the numeric labels + - *patches* is a sequence of + :class:`matplotlib.patches.Wedge` instances + - *texts* is a list of the label + :class:`matplotlib.text.Text` instances. + + If *autopct* is not *None*, return the tuple (*patches*, + *texts*, *autotexts*), where *patches* and *texts* are as + above, and *autotexts* is a list of + :class:`~matplotlib.text.Text` instances for the numeric + labels. """ self.set_frame_on(False) @@ -3975,40 +4089,47 @@ barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False) - Plot x versus y with error deltas in yerr and xerr. - Vertical errorbars are plotted if yerr is not None. - Horizontal errorbars are plotted if xerr is not None. + Plot *x* versus *y* with error deltas in *yerr* and *xerr*. + Vertical errorbars are plotted if *yerr* is not *None*. + Horizontal errorbars are plotted if *xerr* is not *None*. - x, y, xerr, and yerr can all be scalars, which plots a single error bar - at x, y. + *x*, *y*, *xerr*, and *yerr* can all be scalars, which plots a + single error bar at *x*, *y*. Optional keyword arguments: - xerr/yerr: [ scalar | N, Nx1, Nx2 array-like ] + *xerr*/*yerr*: [ scalar | N, Nx1, Nx2 array-like ] If a scalar number, len(N) array-like object, or an Nx1 array-like object, errorbars are drawn +/- value. If a rank-1, Nx2 Numpy array, errorbars are drawn at -column1 and +column2 - fmt: '-' - The plot format symbol for y. If fmt is None, just plot the + + *fmt*: '-' + The plot format symbol for *y*. If *fmt* is *None*, just plot the errorbars with no line symbols. This can be useful for creating a bar plot with errorbars. - ecolor: [ None | mpl color ] + + *ecolor*: [ None | mpl color ] a matplotlib color arg which gives the color the errorbar lines; if - None, use the marker color. - elinewidth: scalar - the linewidth of the errorbar lines. If None, use the linewidth. - capsize: scalar + *None*, use the marker color. + + *elinewidth*: scalar + the linewidth of the errorbar lines. If *None*, use the linewidth. + + *capsize*: scalar the size of the error bar caps in points - barsabove: [ True | False ] - if True, will plot the errorbars above the plot symbols. Default is - below. - lolims/uplims/xlolims/xuplims: [ False | True ] - These arguments can be used to indicate that a value gives only - upper/lower limits. In that case a caret symbol is used to indicate - this. lims-arguments may be of the same type as xerr and yerr. + *barsabove*: [ True | False ] + if *True*, will plot the errorbars above the plot + symbols. Default is below. + + *lolims*/*uplims*/*xlolims*/*xuplims*: [ False | True ] + These arguments can be used to indicate that a value gives + only upper/lower limits. In that case a caret symbol is + used to indicate this. lims-arguments may be of the same + type as *xerr* and *yerr*. + All other keyword arguments are passed on to the plot command for the markers, so you can add additional key=value pairs to control the errorbar markers. For example, this code makes big red squares with @@ -4018,16 +4139,20 @@ errorbar(x, y, yerr, marker='s', mfc='red', mec='green', ms=20, mew=4) - where mfc, mec, ms and mew are aliases for the longer property names, - markerfacecolor, markeredgecolor, markersize and markeredgewith. + where *mfc*, *mec*, *ms* and *mew* are aliases for the longer + property names, *markerfacecolor*, *markeredgecolor*, *markersize* + and *markeredgewith*. valid kwargs for the marker properties are + %(Line2D)s Return value is a length 3 tuple. The first element is the - Line2D instance for the y symbol lines. The second element is - a list of error bar cap lines, the third element is a list of - line collections for the horizontal and vertical error ranges + :class:`~matplotlib.lines.Line2D` instance for the *y* symbol + lines. The second element is a list of error bar cap lines, + the third element is a list of + :class:`~matplotlib.collections.LineCollection` instances for + the horizontal and vertical error ranges. """ self._process_unit_info(xdata=x, ydata=y, kwargs=kwargs) @@ -4196,38 +4321,38 @@ boxplot(x, notch=0, sym='+', vert=1, whis=1.5, positions=None, widths=None) - Make a box and whisker plot for each column of x or - each vector in sequence x. - The box extends from the lower to upper quartile values - of the data, with a line at the median. The whiskers - extend from the box to show the range of the data. Flier - points are those past the end of the whiskers. + Make a box and whisker plot for each column of *x* or each + vector in sequence *x*. The box extends from the lower to + upper quartile values of the data, with a line at the median. + The whiskers extend from the box to show the range of the + data. Flier points are those past the end of the whiskers. - ``notch = 0`` (default) produces a rectangular box plot. - ``notch = 1`` will produce a notched box plot + - *notch* = 0 (default) produces a rectangular box plot. + - *notch* = 1 will produce a notched box plot - sym (default 'b+') is the default symbol for flier points. + *sym* (default 'b+') is the default symbol for flier points. Enter an empty string ('') if you don't want to show fliers. - ``vert = 1`` (default) makes the boxes vertical. - ``vert = 0`` makes horizontal boxes. This seems goofy, but - that's how Matlab did it. + - *vert* = 1 (default) makes the boxes vertical. + - *vert* = 0 makes horizontal boxes. This seems goofy, but + that's how Matlab did it. - whis (default 1.5) defines the length of the whiskers as + *whis* (default 1.5) defines the length of the whiskers as a function of the inner quartile range. They extend to the most extreme data point within ( ``whis*(75%-25%)`` ) data range. - positions (default 1,2,...,n) sets the horizontal positions of + *positions* (default 1,2,...,n) sets the horizontal positions of the boxes. The ticks and limits are automatically set to match the positions. - widths is either a scalar or a vector and sets the width of + *widths* is either a scalar or a vector and sets the width of each box. The default is 0.5, or ``0.15*(distance between extreme positions)`` if that is smaller. - x is an array or a sequence of vectors. + *x* is an array or a sequence of vectors. - Returns a list of the lines added. + Returns a list of the :class:`matplotlib.lines.Line2D` + instances added. """ if not self._hold: self.cla() @@ -4382,24 +4507,26 @@ vmin=None, vmax=None, alpha=1.0, linewidths=None, verts=None, **kwargs) - Make a scatter plot of x versus y, where x, y are 1-D sequences - of the same length, N. + Make a scatter plot of *x* versus *y*, where *x*, *y* are 1-D + sequences of the same length, *N*. Keyword arguments: - s: + *s*: size in points^2. It is a scalar or an array of the same - length as x and y. - c: - a color. c can be a single color format string, or a - sequence of color specifications of length N, or a sequence - of N numbers to be mapped to colors using the cmap and norm - specified via kwargs (see below). Note that c should not be - a single numeric RGB or RGBA sequence because that is - indistinguishable from an array of values to be colormapped. - c can be a 2-D array in which the rows are RGB or RGBA, - however. - marker: + length as *x* and *y*. + + *c*: + a color. *c* can be a single color format string, or a + sequence of color specifications of length *N*, or a + sequence of *N* numbers to be mapped to colors using the + *cmap* and *norm* specified via kwargs (see below). Note + that *c* should not be a single numeric RGB or RGBA + sequence because that is indistinguishable from an array + of values to be colormapped. *c* can be a 2-D array in + which the rows are RGB or RGBA, however. + + *marker*: can be on... [truncated message content] |
From: <jd...@us...> - 2008-06-19 16:55:24
|
Revision: 5596 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5596&view=rev Author: jdh2358 Date: 2008-06-19 09:54:54 -0700 (Thu, 19 Jun 2008) Log Message: ----------- added auto subplots adj faq Modified Paths: -------------- trunk/matplotlib/Makefile trunk/matplotlib/doc/faq/howto_faq.rst trunk/matplotlib/doc/glossary/index.rst trunk/matplotlib/doc/make.py trunk/matplotlib/doc/users/installing.rst Added Paths: ----------- trunk/matplotlib/doc/pyplots/auto_subplots_adjust.py Modified: trunk/matplotlib/Makefile =================================================================== --- trunk/matplotlib/Makefile 2008-06-19 13:59:08 UTC (rev 5595) +++ trunk/matplotlib/Makefile 2008-06-19 16:54:54 UTC (rev 5596) @@ -39,7 +39,7 @@ rm -rf build;\ python make.py clean;\ svn up;\ - python make.py html latex sf; + python make.py html latex sf sfpdf; Modified: trunk/matplotlib/doc/faq/howto_faq.rst =================================================================== --- trunk/matplotlib/doc/faq/howto_faq.rst 2008-06-19 13:59:08 UTC (rev 5595) +++ trunk/matplotlib/doc/faq/howto_faq.rst 2008-06-19 16:54:54 UTC (rev 5596) @@ -54,6 +54,40 @@ `axes_demo.py <http://matplotlib.sf.net/examples/axes_demo.py>`_ for an example of placing axes manually. +.. _howto-auto-adjust: + +How do I automatically make room for my tick labels? +==================================================== + +In most use cases, it is enought to simpy change the subplots adjust +parameters as described in :ref:`howto-subplots-adjust`. But in some +cases, you don't know ahead of time what your tick labels will be, or +how large they will be (data and labels outside your control may be +being fed into your graphing application), and you may need to +automatically adjust your subplot parameters based on the size of the +tick labels. Any :class:`matplotlib.text.Text` instance can report +its extent in window coordinates (a negative x coordinate is outside +the window), but there is a rub. + +The :class:`matplotlib.backend_bases.RendererBase` instance, which is +used to calculate the text size, is not known until the figure is +drawn (:meth:`matplotlib.figure.Figure.draw`). After the window is +drawn and the text instance knows its renderer, you can call +:meth:`matplotlib.text.Text.get_window_extent``. One way to solve +this chicken and egg problem is to wait until the figure is draw by +connecting +(:meth:`matplotlib.backend_bases.FigureCanvasBase.mpl_connect`) to the +"on_draw" signal (:class:`~matplotlib.backend_bases.DrawEvent`) and +get the window extent there, and then do something with it, eg move +the left of the canvas over; see :ref:`event-handling-tutorial`. + +Here is a recursive, iterative solution that will gradually move the +left of the subplot over until the label fits w/o going outside the +figure border (requires matplotlib 0.98) + +.. plot:: auto_subplots_adjust.py + :include-source: + .. _howto-ticks: How do I configure the tick linewidths? Modified: trunk/matplotlib/doc/glossary/index.rst =================================================================== --- trunk/matplotlib/doc/glossary/index.rst 2008-06-19 13:59:08 UTC (rev 5595) +++ trunk/matplotlib/doc/glossary/index.rst 2008-06-19 16:54:54 UTC (rev 5596) @@ -8,73 +8,138 @@ .. glossary:: AGG - The Anti-Grain Geometry rendering engine, capable of rendering - high-quality images. + The Anti-Grain Geometry (`Agg <http://antigrain.com>`_) rendering engine, capable of rendering + high-quality images Cairo - The Cairo graphics engine + The `Cairo graphics <http://cairographics.org>`_ engine EPS - Encapsulated Postscript + Encapsulated Postscript (`EPS <http://en.wikipedia.org/wiki/Encapsulated_PostScript>`_) FLTK - FLTK (pronounced "fulltick") is a cross-platform C++ GUI toolkit for + `FLTK <http://www.fltk.org/>`_ (pronounced "fulltick") is a cross-platform C++ GUI toolkit for UNIX/Linux (X11), Microsoft Windows, and MacOS X + freetype + `freetype <http://www.freetype.org/>`_ is a font rasterization + library used by matplotlib which supports TrueType, Type 1, and + OpenType fonts. + + GDK The Gimp Drawing Kit for GTK+ GTK - The GTK graphical user interface library + The GIMP Toolkit (`GTK <http://www.gtk.org/>`_) graphical user interface library JPG - A compression method and file format for photographic images + The Joint Photographic Experts Group (`JPEG + <http://en.wikipedia.org/wiki/Jpeg>`_) compression method and + file format for photographic images + numpy + `numpy <http://numpy.scipy.org>`_ is the standard numerical + array library for python, the successor to Numeric and numarray. + numpy provides fast operations for homogeneous data sets and + common mathematical operations like correlations, standard + deviation, fourier transforms, and convolutions. + PDF - Adobe's Portable Document Format + Adobe's Portable Document Format (`PDF <http://en.wikipedia.org/wiki/Portable_Document_Format>`_) PNG - PNG stands for Portable Network Graphics, a raster graphics format that - employs lossless data compression which is more suitable for line art - than the lossy jpg format. Unlike the gif format, png is not encumbered - by requirements for a patent license. + Portable Network Graphics (`PNG + <http://en.wikipedia.org/wiki/Portable_Network_Graphics>`_), a raster graphics format + that employs lossless data compression which is more suitable + for line art than the lossy jpg format. Unlike the gif format, + png is not encumbered by requirements for a patent license. PS - Postscript + Postscript (`PS <http://en.wikipedia.org/wiki/PostScript>`_) is a + vector graphics ASCII text language widely used in printers and + publishing. Postscript was developerd by adobe systems and is + starting to show its age: for example is does not have an alpha + channel. PDF was designed in part as a next-generation document + format to replace postscript + pyfltk + `pyfltk <http://pyfltk.sourceforge.net/>`_ provides python + wrappers for the :term:`FLTK` widgets library for use with + FLTKAgg + + pygtk + `pygtk <http://www.pygtk.org/>`_ provides python wrappers for + the :term:`GTK` widgets library for use with the GTK or GTKAgg + backend. Widely used on linux, and is often packages as + 'python-gtk2' + + pyqt + `pyqt <http://wiki.python.org/moin/PyQt>`_ provides python + wrappers for the :term:`Qt` widgets library and is requied by + the matplotlib QtAgg and Qt4Agg backends. Widely used on linux + and windows; many linux distributions package this as + 'python-qt3' or 'python-qt4'. + + python + `python <http://python.org>`_ is an object oriented interpreted + language widely used for scripting, application development, web + application servers, scientific computing and more. + Qt - Qt is a cross-platform application framework for desktop and embedded - development. + `Qt <http://trolltech.com/products/qt/>`__ is a cross-platform + application framework for desktop and embedded development. Qt4 - Qt4 is the most recent version of Qt cross-platform application framework - for desktop and embedded development. + `Qt4 <http://trolltech.com/products/qt/>`__ is the most recent + version of Qt cross-platform application framework for desktop + and embedded development. raster graphics - Raster graphics, or bitmaps, represent an image as an array of pixels - which is resolution dependent. Raster graphics are generally most - practical for photo-realistic images, but do not scale easily without - loss of quality. See `raster graphics <http://en.wikipedia.org/wiki/Raster_graphics>`_ + `Raster graphics + <http://en.wikipedia.org/wiki/Raster_graphics>`_, or bitmaps, + represent an image as an array of pixels which is resolution + dependent. Raster graphics are generally most practical for + photo-realistic images, but do not scale easily without loss of + quality. SVG - The Scalable Vector Graphics format. + The Scalable Vector Graphics format (`SVG + <http://en.wikipedia.org/wiki/Svg>`_). An XML based vector + graphics format supported by many web browsers. TIFF - Tagged Image File Format + Tagged Image File Format (`TIFF + <http://en.wikipedia.org/wiki/Tagged_Image_File_Format>`_) is a + file format for storing images, including photographs and line + art. Tk - Tk is a graphical user interface for Tcl and many other dynamic - languages. It can produce rich, native applications that run unchanged - across Windows, Mac OS X, Linux and more. + `Tk <http://www.tcl.tk/>`_ is a graphical user interface for Tcl + and many other dynamic languages. It can produce rich, native + applications that run unchanged across Windows, Mac OS X, Linux + and more. + vector graphics + `vector graphics + <http://en.wikipedia.org/wiki/Vector_graphics>`_ use geometrical + primitives based upon mathematical equations to represent images + in computer graphics. Primitives can include points, lines, + curves, and shapes or polygons. Vector graphics are scalable, + which means that they can be resized without suffering from + issues related to inherent resolution like are seen in raster + graphics. Vector graphics are generally most practical for + typesetting and graphic design applications. + + wxpython + `wxpython <http://www.wxpython.org/>`_ provides python wrappers + for the :term:`wxWidgets` library for use with the WX and WXAgg + backends. Widely used on linux, OS-X and windows, it is often + packaged by linux distributions as 'python-wxgtk' + wxWidgets - A cross-platform GUI and tools library for GTK, MS Windows, and MacOS. + `WX <http://www.wxwidgets.org/>`_ is cross-platform GUI and + tools library for GTK, MS Windows, and MacOS. It uses native + widgets for each operating system, so applications will have the + look-and-feel that users on that operating system expect. - vector graphics - The use of geometrical primitives based upon mathematical equations to - represent images in computer graphics. Primitives can include points, - lines, curves, and shapes or polygons. Vector graphics are scalable, - which means that they can be resized without suffering from issues - related to inherent resolution like are seen in raster graphics. Vector - graphics are generally most practical for typesetting and graphic design - applications. See `vector graphics <http://en.wikipedia.org/wiki/Vector_graphics>`_ Modified: trunk/matplotlib/doc/make.py =================================================================== --- trunk/matplotlib/doc/make.py 2008-06-19 13:59:08 UTC (rev 5595) +++ trunk/matplotlib/doc/make.py 2008-06-19 16:54:54 UTC (rev 5596) @@ -17,8 +17,12 @@ def sf(): 'push a copy to the sf site' os.system('cd build; rsync -avz html jd...@ma...:/home/groups/m/ma/matplotlib/htdocs/doc/ -essh') - os.system('cd build/latex; scp Matplotlib.pdf jd...@ma...:/home/groups/m/ma/matplotlib/htdocs/doc/') +def sfpdf(): + 'push a copy to the sf site' + + #os.system('cd build/latex; scp Matplotlib.pdf jd...@ma...:/home/groups/m/ma/matplotlib/htdocs/doc/') + def figs(): os.system('cd users/figures/ && python make.py') @@ -73,6 +77,7 @@ 'latex':latex, 'clean':clean, 'sf':sf, + 'sfpdf':sfpdf, 'all':all, } Added: trunk/matplotlib/doc/pyplots/auto_subplots_adjust.py =================================================================== --- trunk/matplotlib/doc/pyplots/auto_subplots_adjust.py (rev 0) +++ trunk/matplotlib/doc/pyplots/auto_subplots_adjust.py 2008-06-19 16:54:54 UTC (rev 5596) @@ -0,0 +1,19 @@ +import matplotlib.pyplot as plt + +fig = plt.figure() +ax = fig.add_subplot(111) +ax.plot(range(10)) +ax.set_yticks((2,5,7)) +labels = ax.set_yticklabels(('really, really, really', 'long', 'labels')) + +def on_draw(event): + for label in labels: + bbox = label.get_window_extent() + if bbox.xmin<0: + fig.subplots_adjust(left=1.1*fig.subplotpars.left) + fig.canvas.draw() + break + +fig.canvas.mpl_connect('draw_event', on_draw) + +plt.show() Modified: trunk/matplotlib/doc/users/installing.rst =================================================================== --- trunk/matplotlib/doc/users/installing.rst 2008-06-19 13:59:08 UTC (rev 5595) +++ trunk/matplotlib/doc/users/installing.rst 2008-06-19 16:54:54 UTC (rev 5596) @@ -14,18 +14,18 @@ and numpy) since the others are built into the matplotlib windows installers available for download at the sourceforge site. -python 2.4 (or later but not python3) - matplotlib requires python 2.4 or later +:term:`python` 2.4 (or later but not python3) + matplotlib requires python 2.4 or later (`download <http://www.python.org/download/>`__) -numpy 1.1 (or later) - array support for python +:term:`numpy` 1.1 (or later) + array support for python (`download <http://sourceforge.net/project/showfiles.php?group_id=1369&package_id=175103>`__) libpng 1.1 (or later) - library for loading and saving PNG files. libpng requires zlib. If + library for loading and saving :term:`PNG` files (`download <http://www.libpng.org/pub/png/libpng.html>`__). libpng requires zlib. If you are a windows user, you can ignore this since we build support - into the matplotlib single click installer. + into the matplotlib single click installer -freetype 1.4 (or later) +:term:`freetype` 1.4 (or later) library for reading true type font files. If you are a windows user, you can ignore this since we build support into the matplotlib single click installer. @@ -37,25 +37,25 @@ :ref:`what-is-a-backend` for more details on the optional matplotlib backends and the capabilities they provide -tk 8.3 or later +:term:`tk` 8.3 or later The TCL/Tk widgets library used by the TkAgg backend -pyqt 3.1 or later +:term:`pyqt` 3.1 or later The Qt3 widgets library python wrappers for the QtAgg backend -pyqt 4.0 or later +:term:`pyqt` 4.0 or later The Qt4 widgets library python wrappersfor the Qt4Agg backend -pygtk 2.2 or later +:term:`pygtk` 2.2 or later The python wrappers for the GTK widgets library for use with the GTK or GTKAgg backend -wxpython 2.6 or later +:term:`wxpython` 2.6 or later The python wrappers for the wx widgets library for use with the WXAgg backend -wxpython 2.8 or later +:term:`wxpython` 2.8 or later The python wrappers for the wx widgets library for use with the WX backend -pyfltk 1.0 or later +:term:`pyfltk` 1.0 or later The python wrappers of the FLTK widgets library for use with FLTKAgg **Required libraries that ship with matplotlib** @@ -65,7 +65,7 @@ developers and packagers who may want to disable the matplotlib version and ship a packaged version. -agg2.4 +:term:`agg` 2.4 The antigrain C++ rendering engine pytz 2007g or later This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2008-06-19 17:24:25
|
Revision: 5597 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5597&view=rev Author: jdh2358 Date: 2008-06-19 10:23:34 -0700 (Thu, 19 Jun 2008) Log Message: ----------- added support for custom positioning of axis labels Modified Paths: -------------- trunk/matplotlib/doc/faq/howto_faq.rst trunk/matplotlib/lib/matplotlib/axis.py Added Paths: ----------- trunk/matplotlib/doc/pyplots/align_ylabels.py Modified: trunk/matplotlib/doc/faq/howto_faq.rst =================================================================== --- trunk/matplotlib/doc/faq/howto_faq.rst 2008-06-19 16:54:54 UTC (rev 5596) +++ trunk/matplotlib/doc/faq/howto_faq.rst 2008-06-19 17:23:34 UTC (rev 5597) @@ -113,6 +113,24 @@ ``markersize``. For more information on configuring ticks, see :ref:`axis-container` and :ref:`tick-container`. + +.. _howto-align-label: + +How do I align my ylabels across multiple subplots? +=================================================== + +If you have multiple subplots over one another, and the y data have +different scales, you can often get ylabels that do not align +vertically across the multiple subplots, which can be unattractive. +By default, matplotlib positions the x location of the ylabel so that +it does not overlap any of the y ticks. You can override this default +behavior by specifying the coordinates of the label. The example +below shows the default behavior in the left subplots, and the manual +setting in the right subplots. + +.. plot:: align_ylabels.py + :include-source: + .. _howto-webapp: How do I use matplotlib in a web application server? Added: trunk/matplotlib/doc/pyplots/align_ylabels.py =================================================================== --- trunk/matplotlib/doc/pyplots/align_ylabels.py (rev 0) +++ trunk/matplotlib/doc/pyplots/align_ylabels.py 2008-06-19 17:23:34 UTC (rev 5597) @@ -0,0 +1,35 @@ +import numpy as np +import matplotlib.pyplot as plt + +box = dict(facecolor='yellow', pad=5, alpha=0.2) + +fig = plt.figure() +fig.subplots_adjust(left=0.2, wspace=0.6) + + +ax1 = fig.add_subplot(221) +ax1.plot(2000*np.random.rand(10)) +ax1.set_title('ylabels not aligned') +ax1.set_ylabel('misaligned 1', bbox=box) +ax1.set_ylim(0, 2000) +ax3 = fig.add_subplot(223) +ax3.set_ylabel('misaligned 2',bbox=box) +ax3.plot(np.random.rand(10)) + + +labelx = -0.3 # axes coords + +ax2 = fig.add_subplot(222) +ax2.set_title('ylabels aligned') +ax2.plot(2000*np.random.rand(10)) +ax2.set_ylabel('aligned 1', bbox=box) +ax2.yaxis.set_label_coords(labelx, 0.5) +ax2.set_ylim(0, 2000) + +ax4 = fig.add_subplot(224) +ax4.plot(np.random.rand(10)) +ax4.set_ylabel('aligned 2', bbox=box) +ax4.yaxis.set_label_coords(labelx, 0.5) + + +plt.show() Modified: trunk/matplotlib/lib/matplotlib/axis.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axis.py 2008-06-19 16:54:54 UTC (rev 5596) +++ trunk/matplotlib/lib/matplotlib/axis.py 2008-06-19 17:23:34 UTC (rev 5597) @@ -503,9 +503,9 @@ """ Public attributes - transData - transform data coords to display coords - transAxis - transform axis coords to display coords + * transData - transform data coords to display coords + * transAxis - transform axis coords to display coords """ LABELPAD = 5 @@ -533,6 +533,7 @@ #self.major = dummy() #self.minor = dummy() + self._autolabelpos = True self.label = self._get_label() self.offsetText = self._get_offset_text() self.majorTicks = [] @@ -542,6 +543,29 @@ self.cla() self.set_scale('linear') + + def set_label_coords(self, x, y, transform=None): + """ + Set the coordinates of the label. By default, the x + coordinate of the y label is determined by the tick label + bounding boxes, but this can lead to poor alignment of + multiple ylabels if there are multiple axes. Ditto for the y + coodinate of the x label. + + You can also specify the coordinate system of the label with + the transform. If None, the default coordinate system will be + the axes coordinate system (0,0) is (left,bottom), (0.5, 0.5) + is middle, etc + + """ + + self._autolabelpos = False + if transform is None: + transform = self.axes.transAxes + + self.label.set_transform(transform) + self.label.set_position((x, y)) + def get_transform(self): return self._scale.get_transform() @@ -703,7 +727,9 @@ # just the tick labels that actually overlap note we need a # *copy* of the axis label box because we don't wan't to scale # the actual bbox + self._update_label_position(ticklabelBoxes, ticklabelBoxes2) + self.label.draw(renderer) self._update_offset_text_position(ticklabelBoxes, ticklabelBoxes2) @@ -1139,8 +1165,9 @@ verticalalignment='top', horizontalalignment='center', ) + label.set_transform( mtransforms.blended_transform_factory( - self.axes.transAxes, mtransforms.IdentityTransform() )) + self.axes.transAxes, mtransforms.IdentityTransform() )) self._set_artist_props(label) self.label_position='bottom' @@ -1184,7 +1211,7 @@ Update the label position based on the sequence of bounding boxes of all the ticklabels """ - + if not self._autolabelpos: return x,y = self.label.get_position() if self.label_position == 'bottom': if not len(bboxes): @@ -1374,7 +1401,7 @@ rotation='vertical', ) label.set_transform( mtransforms.blended_transform_factory( - mtransforms.IdentityTransform(), self.axes.transAxes) ) + mtransforms.IdentityTransform(), self.axes.transAxes) ) self._set_artist_props(label) self.label_position='left' @@ -1418,7 +1445,7 @@ Update the label position based on the sequence of bounding boxes of all the ticklabels """ - + if not self._autolabelpos: return x,y = self.label.get_position() if self.label_position == 'left': if not len(bboxes): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ef...@us...> - 2008-06-20 05:23:26
|
Revision: 5605 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5605&view=rev Author: efiring Date: 2008-06-19 22:23:08 -0700 (Thu, 19 Jun 2008) Log Message: ----------- Merged revisions 5603 via svnmerge from https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/v0_91_maint ........ r5603 | efiring | 2008-06-19 18:51:47 -1000 (Thu, 19 Jun 2008) | 2 lines Make set_default_size set the variable actually being used elsewhere ........ Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/font_manager.py Property Changed: ---------------- trunk/matplotlib/ Property changes on: trunk/matplotlib ___________________________________________________________________ Name: svnmerge-integrated - /branches/v0_91_maint:1-5573 + /branches/v0_91_maint:1-5573,5603 Modified: trunk/matplotlib/lib/matplotlib/font_manager.py =================================================================== --- trunk/matplotlib/lib/matplotlib/font_manager.py 2008-06-20 04:53:28 UTC (rev 5604) +++ trunk/matplotlib/lib/matplotlib/font_manager.py 2008-06-20 05:23:08 UTC (rev 5605) @@ -925,7 +925,7 @@ def set_default_size(self, size): "Set the default font size in points. The initial value is set by font.size in rc." - self.__default_size = size + self.default_size = size def update_fonts(self, filenames): """ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ef...@us...> - 2008-06-20 07:03:26
|
Revision: 5606 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5606&view=rev Author: efiring Date: 2008-06-20 00:03:22 -0700 (Fri, 20 Jun 2008) Log Message: ----------- Use relative font sizes by default so they will scale with font.size Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/rcsetup.py trunk/matplotlib/matplotlibrc.template Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2008-06-20 05:23:08 UTC (rev 5605) +++ trunk/matplotlib/CHANGELOG 2008-06-20 07:03:22 UTC (rev 5606) @@ -1,3 +1,8 @@ +2008-06-19 Use relative font sizes (e.g. 'medium' and 'large') in + rcsetup.py and matplotlibrc.template so that text will + be scaled by default when changing rcParams['font.size'] - + EF + 2008-06-17 Add a generic PatchCollection class that can contain any kind of patch. - MGD @@ -24,7 +29,7 @@ sets '_nolegend_' for the other patch labels. This lets autolegend work as expected for hist and bar - see https://sourceforge.net/tracker/index.php?func=detail&aid=1986597&group_id=80706&atid=560720 - JDH + JDH 2008-06-10 Fix text baseline alignment bug. [ 1985420 ] Repair of baseline alignment in Text._get_layout. Thanks Stan West - Modified: trunk/matplotlib/lib/matplotlib/rcsetup.py =================================================================== --- trunk/matplotlib/lib/matplotlib/rcsetup.py 2008-06-20 05:23:08 UTC (rev 5605) +++ trunk/matplotlib/lib/matplotlib/rcsetup.py 2008-06-20 07:03:22 UTC (rev 5606) @@ -394,9 +394,9 @@ 'axes.facecolor' : ['w', validate_color], # background color; white 'axes.edgecolor' : ['k', validate_color], # edge color; black 'axes.linewidth' : [1.0, validate_float], # edge linewidth - 'axes.titlesize' : [14, validate_fontsize], # fontsize of the axes title + 'axes.titlesize' : ['large', validate_fontsize], # fontsize of the axes title 'axes.grid' : [False, validate_bool], # display grid or not - 'axes.labelsize' : [12, validate_fontsize], # fontsize of the x any y labels + 'axes.labelsize' : ['medium', validate_fontsize], # fontsize of the x any y labels 'axes.labelcolor' : ['k', validate_color], # color of axis label 'axes.formatter.limits' : [[-7, 7], validate_nseq_int(2)], # use scientific notation if log10 @@ -409,7 +409,7 @@ 'legend.loc' : ['upper right',validate_legend_loc], # at some point, this should be changed to 'best' 'legend.isaxes' : [True,validate_bool], # this option is internally ignored - it never served any useful purpose 'legend.numpoints' : [2, validate_int], # the number of points in the legend line - 'legend.fontsize' : [14, validate_fontsize], + 'legend.fontsize' : ['large', validate_fontsize], 'legend.pad' : [0.2, validate_float], # the fractional whitespace inside the legend border 'legend.markerscale' : [1.0, validate_float], # the relative size of legend markers vs. original @@ -427,7 +427,7 @@ 'xtick.major.pad' : [4, validate_float], # distance to label in points 'xtick.minor.pad' : [4, validate_float], # distance to label in points 'xtick.color' : ['k', validate_color], # color of the xtick labels - 'xtick.labelsize' : [12, validate_fontsize], # fontsize of the xtick labels + 'xtick.labelsize' : ['medium', validate_fontsize], # fontsize of the xtick labels 'xtick.direction' : ['in', str], # direction of xticks 'ytick.major.size' : [4, validate_float], # major ytick size in points @@ -435,7 +435,7 @@ 'ytick.major.pad' : [4, validate_float], # distance to label in points 'ytick.minor.pad' : [4, validate_float], # distance to label in points 'ytick.color' : ['k', validate_color], # color of the ytick labels - 'ytick.labelsize' : [12, validate_fontsize], # fontsize of the ytick labels + 'ytick.labelsize' : ['medium', validate_fontsize], # fontsize of the ytick labels 'ytick.direction' : ['in', str], # direction of yticks 'grid.color' : ['k', validate_color], # grid color Modified: trunk/matplotlib/matplotlibrc.template =================================================================== --- trunk/matplotlib/matplotlibrc.template 2008-06-20 05:23:08 UTC (rev 5605) +++ trunk/matplotlib/matplotlibrc.template 2008-06-20 07:03:22 UTC (rev 5606) @@ -185,8 +185,8 @@ #axes.edgecolor : black # axes edge color #axes.linewidth : 1.0 # edge linewidth #axes.grid : False # display grid or not -#axes.titlesize : 14 # fontsize of the axes title -#axes.labelsize : 12 # fontsize of the x any y labels +#axes.titlesize : large # fontsize of the axes title +#axes.labelsize : medium # fontsize of the x any y labels #axes.labelcolor : black #axes.axisbelow : False # whether axis gridlines and ticks are below # the axes elements (lines, text, etc) @@ -203,7 +203,7 @@ #xtick.major.pad : 4 # distance to major tick label in points #xtick.minor.pad : 4 # distance to the minor tick label in points #xtick.color : k # color of the tick labels -#xtick.labelsize : 12 # fontsize of the tick labels +#xtick.labelsize : medium # fontsize of the tick labels #xtick.direction : in # direction: in or out #ytick.major.size : 4 # major tick size in points @@ -211,7 +211,7 @@ #ytick.major.pad : 4 # distance to major tick label in points #ytick.minor.pad : 4 # distance to the minor tick label in points #ytick.color : k # color of the tick labels -#ytick.labelsize : 12 # fontsize of the tick labels +#ytick.labelsize : medium # fontsize of the tick labels #ytick.direction : in # direction: in or out @@ -223,7 +223,7 @@ ### Legend #legend.isaxes : True #legend.numpoints : 2 # the number of points in the legend line -#legend.fontsize : 14 +#legend.fontsize : large #legend.pad : 0.2 # the fractional whitespace inside the legend border #legend.markerscale : 1.0 # the relative size of legend markers vs. original # the following dimensions are in axes coords This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <mme...@us...> - 2008-06-20 11:55:01
|
Revision: 5608 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5608&view=rev Author: mmetz_bn Date: 2008-06-20 04:54:55 -0700 (Fri, 20 Jun 2008) Log Message: ----------- Added get/set_closed to Polygon Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/patches.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2008-06-20 10:46:12 UTC (rev 5607) +++ trunk/matplotlib/CHANGELOG 2008-06-20 11:54:55 UTC (rev 5608) @@ -1,3 +1,6 @@ +2008-06-20 Added set/get_closed method to Polygon; fixes error + in hist - MM + 2008-06-19 Use relative font sizes (e.g. 'medium' and 'large') in rcsetup.py and matplotlibrc.template so that text will be scaled by default when changing rcParams['font.size'] - Modified: trunk/matplotlib/lib/matplotlib/patches.py =================================================================== --- trunk/matplotlib/lib/matplotlib/patches.py 2008-06-20 10:46:12 UTC (rev 5607) +++ trunk/matplotlib/lib/matplotlib/patches.py 2008-06-20 11:54:55 UTC (rev 5608) @@ -558,14 +558,28 @@ """ Patch.__init__(self, **kwargs) xy = np.asarray(xy, np.float_) - if closed and len(xy) and (xy[0] != xy[-1]).any(): - xy = np.concatenate([xy, [xy[0]]]) self._path = Path(xy) + self.set_closed(closed) + __init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd def get_path(self): return self._path + def get_closed(self): + return self._closed + + def set_closed(self, closed): + self._closed = closed + xy = self._get_xy() + if closed: + if len(xy) and (xy[0] != xy[-1]).any(): + xy = np.concatenate([xy, [xy[0]]]) + else: + if len(xy)>2 and (xy[0]==xy[-1]).all(): + xy = xy[0:-2] + self._set_xy(xy) + def _get_xy(self): return self._path.vertices def _set_xy(self, vertices): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2008-06-20 14:06:33
|
Revision: 5611 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5611&view=rev Author: jdh2358 Date: 2008-06-20 07:05:42 -0700 (Fri, 20 Jun 2008) Log Message: ----------- fixed pixel border bug for composite images (eg layer_image.py) Modified Paths: -------------- trunk/matplotlib/MANIFEST.in trunk/matplotlib/examples/api/mathtext_asarray.py trunk/matplotlib/lib/matplotlib/axes.py trunk/matplotlib/lib/matplotlib/figure.py Added Paths: ----------- trunk/matplotlib/examples/widgets/README.txt Removed Paths: ------------- trunk/matplotlib/examples/widgets/README Modified: trunk/matplotlib/MANIFEST.in =================================================================== --- trunk/matplotlib/MANIFEST.in 2008-06-20 13:30:18 UTC (rev 5610) +++ trunk/matplotlib/MANIFEST.in 2008-06-20 14:05:42 UTC (rev 5611) @@ -14,8 +14,8 @@ include lib/matplotlib/mpl-data/fonts/pdfcorefonts/* include lib/matplotlib/mpl-data/fonts/afm/* recursive-include license LICENSE* -recursive-include examples README *.py -prune examples/_tmp_* +recursive-include examples * +recursive-include doc * recursive-include src *.cpp *.c *.h recursive-include CXX *.cxx *.hxx *.c *.h recursive-include agg24 * Modified: trunk/matplotlib/examples/api/mathtext_asarray.py =================================================================== --- trunk/matplotlib/examples/api/mathtext_asarray.py 2008-06-20 13:30:18 UTC (rev 5610) +++ trunk/matplotlib/examples/api/mathtext_asarray.py 2008-06-20 14:05:42 UTC (rev 5611) @@ -5,15 +5,20 @@ import numpy as np import matplotlib.mathtext as mathtext import matplotlib.pyplot as plt +import matplotlib +matplotlib.rc('image', origin='upper') parser = mathtext.MathTextParser("Bitmap") parser.to_png('test2.png', r'$\left[\left\lfloor\frac{5}{\frac{\left(3\right)}{4}} y\right)\right]$', color='green', fontsize=14, dpi=100) -rgba = parser.to_rgba(r'IQ: $\sigma_i=15$', color='blue', fontsize=20, dpi=200) +rgba1, depth1 = parser.to_rgba(r'IQ: $\sigma_i=15$', color='blue', fontsize=20, dpi=200) +rgba2, depth2 = parser.to_rgba(r'some other string', color='red', fontsize=20, dpi=200) fig = plt.figure() -fig.figimage(rgba.astype(float)/255., 100, 100) +fig.figimage(rgba1.astype(float)/255., 100, 100) +fig.figimage(rgba2.astype(float)/255., 100, 300) + plt.show() Deleted: trunk/matplotlib/examples/widgets/README =================================================================== --- trunk/matplotlib/examples/widgets/README 2008-06-20 13:30:18 UTC (rev 5610) +++ trunk/matplotlib/examples/widgets/README 2008-06-20 14:05:42 UTC (rev 5611) @@ -1,2 +0,0 @@ -Examples of how to write primitive, but GUI agnoistic, widgets in -matplotlib Copied: trunk/matplotlib/examples/widgets/README.txt (from rev 5596, trunk/matplotlib/examples/widgets/README) =================================================================== --- trunk/matplotlib/examples/widgets/README.txt (rev 0) +++ trunk/matplotlib/examples/widgets/README.txt 2008-06-20 14:05:42 UTC (rev 5611) @@ -0,0 +1,2 @@ +Examples of how to write primitive, but GUI agnoistic, widgets in +matplotlib Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2008-06-20 13:30:18 UTC (rev 5610) +++ trunk/matplotlib/lib/matplotlib/axes.py 2008-06-20 14:05:42 UTC (rev 5611) @@ -1436,15 +1436,18 @@ for im in self.images if im.get_visible()] - im = mimage.from_images(self.bbox.height*mag, - self.bbox.width*mag, + l, b, r, t = self.bbox.extents + width = mag*((round(r) + 0.5) - (round(l) - 0.5)) + height = mag*((round(t) + 0.5) - (round(b) - 0.5)) + im = mimage.from_images(height, + width, ims) im.is_grayscale = False l, b, w, h = self.bbox.bounds # composite images need special args so they will not # respect z-order for now renderer.draw_image( - l, b, im, self.bbox, + round(l), round(b), im, self.bbox, self.axesPatch.get_path(), self.axesPatch.get_transform()) Modified: trunk/matplotlib/lib/matplotlib/figure.py =================================================================== --- trunk/matplotlib/lib/matplotlib/figure.py 2008-06-20 13:30:18 UTC (rev 5610) +++ trunk/matplotlib/lib/matplotlib/figure.py 2008-06-20 14:05:42 UTC (rev 5611) @@ -796,6 +796,7 @@ if len(self.images)<=1 or renderer.option_image_nocomposite() or not allequal([im.origin for im in self.images]): for im in self.images: + print 'drawing', im im.draw(renderer) else: # make a composite image blending alpha @@ -809,8 +810,12 @@ ims) im.is_grayscale = False l, b, w, h = self.bbox.bounds + clippath, affine = self.get_transformed_clip_path_and_affine() + print 'compodite' + print 'clippath', affine + print 'affine', affine renderer.draw_image(l, b, im, self.bbox, - *self.get_transformed_clip_path_and_affine()) + clippath, affine) # render the axes for a in self.axes: a.draw(renderer) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |