Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 389243d

Browse files
committed
Add plot directive to include inline plots and their source.
svn path=/trunk/matplotlib/; revision=5503
1 parent 05c8058 commit 389243d

11 files changed

Lines changed: 220 additions & 56 deletions

File tree

doc/conf.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@
2727

2828
# Add any Sphinx extension module names here, as strings. They can be extensions
2929
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
30-
extensions = ['mathpng', 'math_symbol_table', 'sphinx.ext.autodoc']
30+
extensions = ['mathpng', 'math_symbol_table', 'sphinx.ext.autodoc',
31+
'only_directives', 'plot_directive']
3132

3233
# Add any paths that contain templates here, relative to this directory.
3334
templates_path = ['_templates']

doc/make.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,24 +24,32 @@ def figs():
2424
def html():
2525
check_build()
2626
figs()
27-
os.system('sphinx-build -b html -d build/doctrees . build/html')
27+
if os.system('sphinx-build -b html -d build/doctrees . build/html'):
28+
raise SystemExit("Building HTML failed.")
29+
30+
figures_dest_path = 'build/html/users/figures'
31+
if os.path.exists(figures_dest_path):
32+
shutil.rmtree(figures_dest_path)
33+
shutil.copytree('users/figures', figures_dest_path)
2834

2935
def latex():
3036
check_build()
3137
figs()
3238
if sys.platform != 'win32':
3339
# LaTeX format.
34-
os.system('sphinx-build -b latex -d build/doctrees . build/latex')
40+
if os.system('sphinx-build -b latex -d build/doctrees . build/latex'):
41+
raise SystemExit("Building LaTeX failed.")
3542

3643
# Produce pdf.
3744
os.chdir('build/latex')
3845

3946
# Copying the makefile produced by sphinx...
40-
os.system('pdflatex Matplotlib.tex')
41-
os.system('pdflatex Matplotlib.tex')
42-
os.system('makeindex -s python.ist Matplotlib.idx')
43-
os.system('makeindex -s python.ist modMatplotlib.idx')
44-
os.system('pdflatex Matplotlib.tex')
47+
if (os.system('pdflatex Matplotlib.tex') or
48+
os.system('pdflatex Matplotlib.tex') or
49+
os.system('makeindex -s python.ist Matplotlib.idx') or
50+
os.system('makeindex -s python.ist modMatplotlib.idx') or
51+
os.system('pdflatex Matplotlib.tex')):
52+
raise SystemExit("Rendering LaTeX failed.")
4553

4654
os.chdir('../..')
4755
else:

doc/sphinxext/only_directives.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
#
2+
# A pair of directives for inserting content that will only appear in
3+
# either html or latex.
4+
#
5+
6+
from docutils.nodes import Body, Element
7+
from docutils.writers.html4css1 import HTMLTranslator
8+
from sphinx.latexwriter import LaTeXTranslator
9+
from docutils.parsers.rst import directives
10+
11+
class html_only(Body, Element):
12+
pass
13+
14+
class latex_only(Body, Element):
15+
pass
16+
17+
def run(content, node_class, state, content_offset):
18+
text = '\n'.join(content)
19+
node = node_class(text)
20+
state.nested_parse(content, content_offset, node)
21+
return [node]
22+
23+
try:
24+
from docutils.parsers.rst import Directive
25+
except ImportError:
26+
from docutils.parsers.rst.directives import _directives
27+
28+
def html_only_directive(name, arguments, options, content, lineno,
29+
content_offset, block_text, state, state_machine):
30+
return run(content, html_only, state, content_offset)
31+
32+
def latex_only_directive(name, arguments, options, content, lineno,
33+
content_offset, block_text, state, state_machine):
34+
return run(content, latex_only, state, content_offset)
35+
36+
for func in (html_only_directive, latex_only_directive):
37+
func.content = 1
38+
func.options = {}
39+
func.arguments = None
40+
41+
_directives['htmlonly'] = html_only_directive
42+
_directives['latexonly'] = latex_only_directive
43+
else:
44+
class OnlyDirective(Directive):
45+
has_content = True
46+
required_arguments = 0
47+
optional_arguments = 0
48+
final_argument_whitespace = True
49+
option_spec = {}
50+
51+
def run(self):
52+
self.assert_has_content()
53+
return run(self.content, self.node_class,
54+
self.state, self.content_offset)
55+
56+
class HtmlOnlyDirective(OnlyDirective):
57+
node_class = html_only
58+
59+
class LatexOnlyDirective(OnlyDirective):
60+
node_class = latex_only
61+
62+
directives.register_directive('htmlonly', HtmlOnlyDirective)
63+
directives.register_directive('latexonly', LatexOnlyDirective)
64+
65+
def setup(app):
66+
app.add_node(html_only)
67+
app.add_node(latex_only)
68+
69+
# Add visit/depart methods to HTML-Translator:
70+
def visit_perform(self, node):
71+
pass
72+
def depart_perform(self, node):
73+
pass
74+
def visit_ignore(self, node):
75+
node.children = []
76+
def depart_ignore(self, node):
77+
node.children = []
78+
79+
HTMLTranslator.visit_html_only = visit_perform
80+
HTMLTranslator.depart_html_only = depart_perform
81+
HTMLTranslator.visit_latex_only = visit_ignore
82+
HTMLTranslator.depart_latex_only = depart_ignore
83+
84+
LaTeXTranslator.visit_html_only = visit_ignore
85+
LaTeXTranslator.depart_html_only = depart_ignore
86+
LaTeXTranslator.visit_latex_only = visit_perform
87+
LaTeXTranslator.depart_latex_only = depart_perform

doc/sphinxext/plot_directive.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
"""A special directive for including a matplotlib plot.
2+
3+
Given a path to a .py file, it includes the source code inline, then:
4+
5+
- On HTML, will include a .png with a link to a high-res .png.
6+
Underneath that, a [source] link will go to a plain text .py of
7+
the source.
8+
9+
- On LaTeX, will include a .pdf
10+
"""
11+
12+
from docutils.parsers.rst import directives
13+
14+
try:
15+
# docutils 0.4
16+
from docutils.parsers.rst.directives.images import align
17+
except ImportError:
18+
# docutils 0.5
19+
from docutils.parsers.rst.directives.images import Image
20+
align = Image.align
21+
22+
options = {'alt': directives.unchanged,
23+
'height': directives.length_or_unitless,
24+
'width': directives.length_or_percentage_or_unitless,
25+
'scale': directives.nonnegative_int,
26+
'align': align,
27+
'class': directives.class_option}
28+
29+
template = """
30+
.. literalinclude:: %(reference)s.py
31+
32+
.. htmlonly::
33+
34+
.. image:: %(reference)s.png
35+
:target: %(reference)s.hires.png
36+
%(options)s
37+
38+
`[source] <%(reference)s.py>`_
39+
40+
.. latexonly::
41+
.. image:: %(reference)s.pdf
42+
%(options)s
43+
44+
"""
45+
46+
def run(arguments, options, state_machine, lineno):
47+
reference = directives.uri(arguments[0])
48+
if reference.endswith('.py'):
49+
reference = reference[:-3]
50+
options = [' :%s: %s' % (key, val) for key, val in
51+
options.items()]
52+
options = "\n".join(options)
53+
lines = template % locals()
54+
lines = lines.split('\n')
55+
56+
state_machine.insert_input(
57+
lines, state_machine.input_lines.source(0))
58+
return []
59+
60+
try:
61+
from docutils.parsers.rst import Directive
62+
except ImportError:
63+
from docutils.parsers.rst.directives import _directives
64+
65+
def plot_directive(name, arguments, options, content, lineno,
66+
content_offset, block_text, state, state_machine):
67+
return run(arguments, options, state_machine, lineno)
68+
plot_directive.__doc__ = __doc__
69+
plot_directive.arguments = (1, 0, 1)
70+
plot_directive.options = options
71+
72+
_directives['plot'] = plot_directive
73+
else:
74+
class plot_directive(Directive):
75+
required_arguments = 1
76+
optional_arguments = 0
77+
final_argument_whitespace = True
78+
option_spec = options
79+
def run(self):
80+
return run(self.arguments, self.options,
81+
self.state_machine, self.lineno)
82+
plot_directive.__doc__ = __doc__
83+
84+
directives.register_directive('plot', plot_directive)
85+

doc/users/annotations.rst

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,7 @@ consider: the location being annotated represented by the argument
1212
``xy`` and the location of the text ``xytext``. Both of these
1313
arguments are ``(x,y)`` tuples.
1414

15-
.. literalinclude:: figures/annotation_basic.py
16-
17-
.. image:: figures/annotation_basic.png
15+
.. plot:: figures/annotation_basic.py
1816
:scale: 75
1917

2018
In this example, both the ``xy`` (arrow tip) and ``xytext`` locations
@@ -73,9 +71,7 @@ keyword args like ``horizontalalignment``, ``verticalalignment`` and
7371
``fontsize are passed from the `~matplotlib.Axes.annotate` to the
7472
``Text`` instance
7573

76-
.. literalinclude:: figures/annotation_polar.py
77-
78-
.. image:: figures/annotation_polar.png
74+
.. plot:: figures/annotation_polar.py
7975
:scale: 75
8076

8177
See the `annotations demo

doc/users/artists.rst

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -604,9 +604,7 @@ grid Turn the grid on or off for the major or minor ticks
604604
Here is an example, not recommended for its beauty, which customizes
605605
the axes and tick properties
606606

607-
.. literalinclude:: figures/fig_axes_customize_simple.py
608-
609-
.. image:: figures/fig_axes_customize_simple.png
607+
.. plot:: figures/fig_axes_customize_simple.py
610608
:scale: 75
611609

612610

@@ -643,7 +641,5 @@ label2On boolean which determines whether to draw tick label
643641
Here is an example which sets the formatter for the upper ticks with
644642
dollar signs and colors them green on the right side of the yaxis
645643

646-
.. literalinclude:: figures/dollar_ticks.py
647-
648-
.. image:: figures/dollar_ticks.png
644+
.. plot:: figures/dollar_ticks.py
649645
:scale: 75

doc/users/figures/make.py

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,27 +7,37 @@
77

88
mplshell = IPython.Shell.MatplotlibShell('mpl')
99

10+
formats = [('png', 100),
11+
('hires.png', 200),
12+
('pdf', 72)]
13+
1014
def figs():
1115
print 'making figs'
1216
import matplotlib.pyplot as plt
1317
for fname in glob.glob('*.py'):
1418
if fname==__file__: continue
1519
basename, ext = os.path.splitext(fname)
16-
outfile = '%s.png'%basename
20+
outfiles = ['%s.%s' % (basename, format) for format, dpi in formats]
21+
all_exists = True
22+
for format, dpi in formats:
23+
if not os.path.exists('%s.%s' % (basename, format)):
24+
all_exists = False
25+
break
1726

18-
if os.path.exists(outfile):
19-
print ' already have %s'%outfile
20-
continue
27+
if all_exists:
28+
print ' already have %s'%fname
2129
else:
2230
print ' building %s'%fname
23-
plt.close('all') # we need to clear between runs
24-
mplshell.magic_run(basename)
25-
plt.savefig(outfile)
31+
plt.close('all') # we need to clear between runs
32+
mplshell.magic_run(basename)
33+
for format, dpi in formats:
34+
plt.savefig('%s.%s' % (basename, format), dpi=dpi)
2635
print 'all figures made'
2736

2837

2938
def clean():
30-
patterns = ['#*', '*~', '*.png', '*pyc']
39+
patterns = (['#*', '*~', '*pyc'] +
40+
['*.%s' % format for format, dpi in formats])
3141
for pattern in patterns:
3242
for fname in glob.glob(pattern):
3343
os.remove(fname)

doc/users/mathtext.rst

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -271,9 +271,7 @@ Example
271271

272272
Here is an example illustrating many of these features in context.
273273

274-
.. literalinclude:: figures/pyplot_mathtext.py
275-
276-
.. image:: figures/pyplot_mathtext.png
274+
.. plot:: figures/pyplot_mathtext.py
277275
:scale: 75
278276

279277

doc/users/pyplot_tutorial.rst

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,9 @@ with labels, etc.... :mod:`matplotlib.pyplot` is stateful, in that it
1212
keeps track of the current figure and plotting area, and the plotting
1313
functions are directed to the current axes
1414

15-
.. literalinclude:: figures/pyplot_simple.py
16-
17-
.. image:: figures/pyplot_simple.png
15+
.. plot:: figures/pyplot_simple
1816
:scale: 75
1917

20-
2118
You may be wondering why the x-axis ranges from 0-3 and the y-axis
2219
from 1-4. If you provide a single list or array to the
2320
:func:`~matplotlib.pyplot.plot` command, matplotlib assumes it a
@@ -39,9 +36,7 @@ matlab, and you concatenate a color string with a line style string.
3936
The default format string is 'b-', which is a solid blue line. For
4037
example, to plot the above with red circles, you would issue
4138

42-
.. literalinclude:: figures/pyplot_formatstr.py
43-
44-
.. image:: figures/pyplot_formatstr.png
39+
.. plot:: figures/pyplot_formatstr.py
4540
:scale: 75
4641

4742
See the :func:`~matplotlib.pyplot.plot` documentation for a complete
@@ -57,9 +52,7 @@ converted to numpy arrays internally. The example below illustrates a
5752
plotting several lines with different format styles in one command
5853
using arrays.
5954

60-
.. literalinclude:: figures/pyplot_three.py
61-
62-
.. image:: figures/pyplot_three.png
55+
.. plot:: figures/pyplot_three.py
6356
:scale: 75
6457

6558
.. _controlling-line-properties:
@@ -164,9 +157,7 @@ current axes (a :class:`matplotlib.axes.Axes` instance), and
164157
to worry about this, because it is all taken care of behind the
165158
scenes. Below is an script to create two subplots.
166159

167-
.. literalinclude:: figures/pyplot_two_subplots.py
168-
169-
.. image:: figures/pyplot_two_subplots.png
160+
.. plot:: figures/pyplot_two_subplots.py
170161
:scale: 75
171162

172163
The :func:`~matplotlib.pyplot.figure` command here is optional because
@@ -225,9 +216,7 @@ an arbitrary location, and the :func:`~matplotlib.pyplot.xlabel`,
225216
are used tox add text in the indicated locations (see :ref:`text-intro`
226217
for a more detailed example)
227218

228-
.. literalinclude:: figures/pyplot_text.py
229-
230-
.. image:: figures/pyplot_text.png
219+
.. plot:: figures/pyplot_text.py
231220
:scale: 75
232221

233222

@@ -273,9 +262,7 @@ two points to consider: the location being annotated represented by
273262
the argument ``xy`` and the location of the text ``xytext``. Both of
274263
these arguments are ``(x,y)`` tuples.
275264

276-
.. literalinclude:: figures/pyplot_annotate.py
277-
278-
.. image:: figures/pyplot_annotate.png
265+
.. plot:: figures/pyplot_annotate.py
279266
:scale: 75
280267

281268
In this basic example, both the ``xy`` (arrow tip) and ``xytext``

0 commit comments

Comments
 (0)