Write documentation#
Getting started#
General file structure#
All documentation is built from thedoc/
. Thedoc/
directory contains configuration files for Sphinx and reStructuredText(ReST;.rst
) files that are rendered to documentation pages.
Documentation is created in three ways. First, API documentation(doc/api
) is created bySphinx fromthe docstrings of the classes in the Matplotlib library. Except fordoc/api/api_changes/
,.rst
files indoc/api
are createdwhen the documentation is built. SeeWrite API documentation below.
Second, our example pages, tutorials, and some of the narrative documentationare created bySphinx Gallery. Sphinx Gallery converts example Python filesto*.rst
files with the result of Matplotlib plot calls as embedded images.SeeWrite examples and tutorials below.
Third, Matplotlib has narrative docs written inReST in subdirectories ofdoc/users/
. If you would like to add new documentation that is suitedto an.rst
file rather than a gallery or tutorial example, choose anappropriate subdirectory to put it in, and add the file to the table ofcontents ofindex.rst
of the subdirectory. SeeWrite ReST pages below.
Note
Don't directly edit the.rst
files indoc/plot_types
,doc/gallery
,doc/tutorials
, anddoc/api
(exceptingdoc/api/api_changes/
).Sphinx regeneratesfiles in these directories when building documentation.
Set up the build#
The documentation for Matplotlib is generated from reStructuredText (ReST)using theSphinx documentation generation tool.
To build the documentation you will need toset up Matplotlib for development. Note inparticular theadditional dependencies required tobuild the documentation.
Build the docs#
The documentation sources are found in thedoc/
directory.The configuration file for Sphinx isdoc/conf.py
. It controls whichdirectories Sphinx parses, how the docs are built, and how the extensions areused. To build the documentation in html format, cd intodoc/
and run:
makehtml
Note
Since the documentation is very large, the first build may take 10-20 minutes,depending on your machine. Subsequent builds will be faster.
Other useful invocations include
# Build the html documentation, but skip generation of the gallery images to# save time.makehtml-noplot# Build the html documentation, but skip specific subdirectories. If a gallery# directory is skipped, the gallery images are not generated. The first# time this is run, it creates ``.mpl_skip_subdirs.yaml`` which can be edited# to add or remove subdirectoriesmakehtml-skip-subdirs# Delete built files. May help if you get errors about missing paths or# broken links.makeclean# Build pdf docs.makelatexpdf
TheSPHINXOPTS
variable is set to-W--keep-going
by default to buildthe complete docs but exit with exit status 1 if there are warnings. To unsetit, use
makeSPHINXOPTS=html
You can use theO
variable to set additional options:
makeO=-j4html
runs a parallel build with 4 processes.makeO=-Dplot_formats=png:100html
saves figures in low resolution.
Multiple options can be combined, e.g.makeO='-j4-Dplot_formats=png:100'html
.
On Windows, set the options as environment variables, e.g.:
setSPHINXOPTS=&setO=-j4 -Dplot_formats=png:100& make html
Show locally built docs#
The built docs are available in the folderbuild/html
. A shortcutfor opening them in your default browser is:
makeshow
Write ReST pages#
Most documentation is either in the docstrings of individualclasses and methods, in explicit.rst
files, or in examples and tutorials.All of these use theReST syntax and are processed bySphinx.
TheSphinx reStructuredText Primer isa good introduction into using ReST. More complete information is available inthereStructuredText reference documentation.
This section contains additional information and conventions how ReST is usedin the Matplotlib documentation.
Formatting and style conventions#
It is useful to strive for consistency in the Matplotlib documentation. Hereare some formatting and style conventions that are used.
Section formatting#
Usesentence caseUpperlower
for section titles, e.g.,Possiblehangups
rather thanPossibleHangups
.
We aim to follow the recommendations from thePython documentationand theSphinx reStructuredText documentationfor section markup characters, i.e.:
#
with overline, for parts. This is reserved for the main title inindex.rst
. All other pages should start with "chapter" or lower.*
with overline, for chapters=
, for sections-
, for subsections^
, for subsubsections"
, for paragraphs
This may not yet be applied consistently in existing docs.
Table formatting#
Given the size of the table and length of each entry, use:
small table | large table | |
short entry | ||
long entry |
For more information, seerst tables.
Function arguments#
Function arguments and keywords within docstrings should be referred to usingthe*emphasis*
role. This will keep Matplotlib's documentation consistentwith Python's documentation:
Here is a description of*argument*
Do not use the`defaultrole`
:
Do not describe`argument` like this. As per the next section,this syntax will (unsuccessfully) attempt to resolve the argument as alink to a class or method in the library.
nor the``literal``
role:
Do not describe``argument`` like this.
Refer to other documents and sections#
Sphinx supports internalreferences:
Role | Links target | Representation in rendered HTML |
---|---|---|
document | link to a page | |
reference label | link to an anchor associated with a heading |
Examples:
See the:doc:`/install/index`See the tutorial:ref:`quick_start`See the example:doc:`/gallery/lines_bars_and_markers/simple_plot`
will render as:
Sections can also be given reference labels. For instance from theInstallation link:
.._clean-install:How to completely remove Matplotlib===================================Occasionally, problems with Matplotlib can be solved with a clean...
and refer to it using the standard reference syntax:
See:ref:`clean-install`
will give the following link:How to completely remove Matplotlib
To maximize internal consistency in section labeling and references,use hyphen separated, descriptive labels for section references.Keep in mind that contents may be reorganized later, soavoid top level names in references likeuser
ordevel
orfaq
unless necessary, because for example the FAQ "what is abackend?" could later become part of the users guide, so the label:
.._what-is-a-backend:
is better than:
.._faq-backend:
In addition, since underscores are widely used by Sphinx itself, usehyphens to separate words.
Refer to other code#
To link to other methods, classes, or modules in Matplotlib you can useback ticks, for example:
`matplotlib.collections.LineCollection`
generates a link like this:matplotlib.collections.LineCollection
.
Note: We use the sphinx settingdefault_role='obj'
so that you don'thave to use qualifiers like:class:
,:func:
,:meth:
and the likes.
Often, you don't want to show the full package and module name. As long as thetarget is unambiguous you can simply leave them out:
`.LineCollection`
and the link still works:LineCollection
. Note that you should typically includethe leading dot. It tells Sphinx to look for the given name in the whole project.See also the explanation atSphinx: Cross-referencing Python objects.
If there are multiple code elements with the same name (e.g.plot()
is amethod in multiple classes), you'll have to extend the definition:
`.pyplot.plot` or`.Axes.plot`
These will show up aspyplot.plot
orAxes.plot
. To still show only thelast segment you can add a tilde as prefix:
`~.pyplot.plot` or`~.Axes.plot`
Other packages can also be linked viaintersphinx:
`numpy.mean`
will return this link:numpy.mean
. This works for Python, Numpy, Scipy,and Pandas (full list is indoc/conf.py
). If external linking fails,you can check the full list of referenceable objects with the followingcommands:
python-msphinx.ext.intersphinx'https://docs.python.org/3/objects.inv'python-msphinx.ext.intersphinx'https://numpy.org/doc/stable/objects.inv'python-msphinx.ext.intersphinx'https://docs.scipy.org/doc/scipy/objects.inv'python-msphinx.ext.intersphinx'https://pandas.pydata.org/pandas-docs/stable/objects.inv'
Include figures and files#
Image files can directly included in pages with theimage::
directive.e.g.,tutorials/intermediate/constrainedlayout_guide.py
displaysa couple of static images:
# .. image:: /_static/constrained_layout_1b.png# :align: center
Files can be included verbatim. For instance theLICENSE
file is includedatLicense agreement using
..literalinclude::../../LICENSE/LICENSE
The examples directory is copied todoc/gallery
by sphinx-gallery,so plots from the examples directory can be included using
..plot:: gallery/lines_bars_and_markers/simple_plot.py
Note that the python script that generates the plot is referred to, rather thanany plot that is created. Sphinx-gallery will provide the correct referencewhen the documentation is built.
Tools for writing mathematical expressions#
In most cases, you will likely want to use one ofSphinx's builtin Mathextensions.In rare cases we want the rendering of the mathematical text in thedocumentation html to exactly match with the rendering of the mathematicalexpression in the Matplotlib figure. In these cases, you can use thematplotlib.sphinxext.mathmpl
Sphinx extension (See also theWriting mathematical expressions tutorial.)
Write API documentation#
The API reference documentation describes the library interfaces, e.g. inputs, outputs,and expected behavior. Most of the API documentation is written in docstrings. These arecomment blocks in source code that explain how the code works. All docstrings shouldconform to thenumpydoc docstring guide. Much of theReST syntax discussed above(Write ReST pages) can be used for links and references.
Note
Some parts of the documentation do not yet conform to the currentdocumentation style. If in doubt, follow the rules given here and not whatyou may see in the source code. Pull requests updating docstrings tothe current style are very welcome.
The pages indoc/api
are purely technical definitions oflayout; therefore new API reference documentation should be added to the moduledocstrings. This placement keeps all API reference documentation about a module in thesame file. These module docstrings eventually populate thedoc/api
directoryand form the reference documentation for the library.
Example docstring#
An example docstring looks like:
defhlines(self,y,xmin,xmax,colors=None,linestyles='solid',label='',**kwargs):""" Plot horizontal lines at each *y* from *xmin* to *xmax*. Parameters ---------- y : float or array-like y-indexes where to plot the lines. xmin, xmax : float or array-like Respective beginning and end of each line. If scalars are provided, all lines will have the same length. colors : list of colors, default: :rc:`lines.color` linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, optional label : str, default: '' Returns ------- `~matplotlib.collections.LineCollection` Other Parameters ---------------- data : indexable object, optional DATA_PARAMETER_PLACEHOLDER **kwargs : `~matplotlib.collections.LineCollection` properties. See Also -------- vlines : vertical lines axhline : horizontal line across the Axes """
See thehlines
documentation for how this renders.
TheSphinx website also contains plenty ofdocumentation concerning ReSTmarkup and working with Sphinx in general.
Formatting conventions#
The basic docstring conventions are covered in thenumpydoc docstring guideand theSphinx documentation. Some Matplotlib-specific formatting conventionsto keep in mind:
Quote positions#
The quotes for single line docstrings are on the same line (pydocstyle D200):
defget_linewidth(self):"""Return the line width in points."""
The quotes for multi-line docstrings are on separate lines (pydocstyle D213):
defset_linestyle(self,ls):"""Set the linestyle of the line.[...]"""
Function arguments#
Function arguments and keywords within docstrings should be referred tousing the*emphasis*
role. This will keep Matplotlib's documentationconsistent with Python's documentation:
If*linestyles* is*None*, the default is 'solid'.
Do not use the`defaultrole`
or the``literal``
role:
Neither`argument` nor``argument`` should be used.
Quotes for strings#
Matplotlib does not have a convention whether to use single-quotes ordouble-quotes. There is a mixture of both in the current code.
Use simple single or double quotes when giving string values, e.g.
If 'tight', try to figure out the tight bbox of the figure.No``'extra'`` literal quotes.
The use of extra literal quotes around the text is discouraged. While theyslightly improve the rendered docs, they are cumbersome to type and difficultto read in plain-text docs.
Parameter type descriptions#
The main goal for parameter type descriptions is to be readable andunderstandable by humans. If the possible types are too complex use asimplification for the type description and explain the type moreprecisely in the text.
Generally, thenumpydoc docstring guide conventions apply. The followingrules expand on them where the numpydoc conventions are not specific.
Usefloat
for a type that can be any number.
Use(float,float)
to describe a 2D position. The parentheses should beincluded to make the tuple-ness more obvious.
Usearray-like
for homogeneous numeric sequences, which couldtypically be a numpy.array. Dimensionality may be specified using2D
,3D
,n-dimensional
. If you need to have variables denoting thesizes of the dimensions, use capital letters in brackets((M,N)array-like
). When referring to them in the text they are easierread and no special formatting is needed. Usearray
instead ofarray-like
for return types if the returned object is indeed a numpy array.
float
is the implicit default dtype for array-likes. For other dtypesusearray-likeofint
.
Some possible uses:
2Darray-like(N,)array-like(M,N)array-like(M,N,3)array-likearray-likeofint
Non-numeric homogeneous sequences are described as lists, e.g.:
list of strlist of `.Artist`
Reference types#
Generally, the rules fromreferring-to-other-code apply. More specifically:
Use full references`~matplotlib.colors.Normalize`
with anabbreviation tilde in parameter types. While the full name helps thereader of plain text docstrings, the HTML does not need to show the fullname as it links to it. Hence, the~
-shortening keeps it more readable.
Use abbreviated links`.Normalize`
in the text.
norm :`~matplotlib.colors.Normalize`, optional A`.Normalize` instance is used to scale luminance data to 0, 1.
Default values#
As opposed to the numpydoc guide, parameters need not be marked asoptional if they have a simple default:
use
{name}:{type},default:{val}
when possible.use
{name}:{type},optional
and describe the default in the text ifit cannot be explained sufficiently in the recommended manner.
The default value should provide semantic information targeted at a humanreader. In simple cases, it restates the value in the function signature.If applicable, units should be added.
Prefer: interval : int, default: 1000msover: interval : int, default: 1000
IfNone is only used as a sentinel value for "parameter not specified", donot document it as the default. Depending on the context, give the actualdefault, or mark the parameter as optional if not specifying has no particulareffect.
Prefer: dpi : float, default::rc:`figure.dpi`over: dpi : float, default: NonePrefer: textprops : dict, optional Dictionary of keyword parameters to be passed to the`~matplotlib.text.Text` instance contained inside TextArea.over: textprops : dict, default: None Dictionary of keyword parameters to be passed to the`~matplotlib.text.Text` instance contained inside TextArea.
Seealso
sections#
Sphinx automatically links code elements in the definition blocks ofSeealso
sections. No need to use backticks there:
SeeAlso--------vlines:verticallinesaxhline:horizontallineacrosstheAxes
Wrap parameter lists#
Long parameter lists should be wrapped using a\
for continuation andstarting on the new line without any indent (no indent because pydoc willparse the docstring and strip the line continuation so that indent wouldresult in a lot of whitespace within the line):
defadd_axes(self,*args,**kwargs):""" ... Parameters ---------- projection : {'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', \'rectilinear'}, optional The projection type of the axes. ... """
Alternatively, you can describe the valid parameter values in a dedicatedsection of the docstring.
rcParams#
rcParams can be referenced with the custom:rc:
role::rc:`foo`
yieldsrcParams["foo"]='default'
, which is a linkto thematplotlibrc
file description.
Setters and getters#
Artist properties are implemented using setter and getter methods (becauseMatplotlib predates the Pythonproperty
decorator).By convention, these setters and getters are namedset_PROPERTYNAME
andget_PROPERTYNAME
; the list of properties thusly defined on an artist andtheir values can be listed by thesetp
andgetp
functions.
The Parameters block of property setter methods is parsed to document theaccepted values, e.g. the docstring ofLine2D.set_linestyle
starts with
defset_linestyle(self,ls):""" Set the linestyle of the line. Parameters ---------- ls : {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} etc. """
which results in the following line in the output ofplt.setp(line)
orplt.setp(line,"linestyle")
:
linestyleorls:{'-','--','-.',':','',(offset,on-off-seq),...}
In some rare cases (mostly, setters which accept both a single tuple and anunpacked tuple), the accepted values cannot be documented in such a fashion;in that case, they can be documented as an..ACCEPTS:
block, e.g. foraxes.Axes.set_xlim
:
defset_xlim(self,left=None,right=None):""" Set the x-axis view limits. Parameters ---------- left : float, optional The left xlim in data coordinates. Passing *None* leaves the limit unchanged. The left and right xlims may also be passed as the tuple (*left*, *right*) as the first positional argument (or as the *left* keyword argument). .. ACCEPTS: (bottom: float, top: float) right : float, optional etc. """
Note that the leading..
makes the..ACCEPTS:
block a reST comment,hiding it from the rendered docs.
Keyword arguments#
Note
The information in this section is being actively discussed by thedevelopment team, so use the docstring interpolation only if necessary.This section has been left in place for now because this interpolationis part of the existing documentation.
Since Matplotlib uses a lot of pass-throughkwargs
, e.g., in every functionthat creates a line (plot
,semilogx
,semilogy
,etc.), it can be difficult for the new user to know whichkwargs
aresupported. Matplotlib uses a docstring interpolation scheme to supportdocumentation of every function that takes a**kwargs
. The requirementsare:
single point of configuration so changes to the properties don'trequire multiple docstring edits.
as automated as possible so that as properties change, the docsare updated automatically.
The@_docstring.interpd
decorator implements this. Any function acceptingLine2D
pass-throughkwargs
, e.g.,matplotlib.axes.Axes.plot
, can lista summary of theLine2D
properties, as follows:
# in axes.py@_docstring.interpddefplot(self,*args,**kwargs):""" Some stuff omitted Other Parameters ---------------- scalex, scaley : bool, default: True These parameters determine if the view limits are adapted to the data limits. The values are passed on to `autoscale_view`. **kwargs : `.Line2D` properties, optional *kwargs* are used to specify properties like a line label (for auto legends), linewidth, antialiasing, marker face color. Example:: >>> plot([1, 2, 3], [1, 2, 3], 'go-', label='line 1', linewidth=2) >>> plot([1, 2, 3], [1, 4, 9], 'rs', label='line 2') If you specify multiple lines with one plot call, the kwargs apply to all those lines. In case the label object is iterable, each element is used as labels for each set of data. Here is a list of available `.Line2D` properties: %(Line2D:kwdoc)s """
The%(Line2D:kwdoc)
syntax makesinterpd
lookup anArtist
subclassnamedLine2D
, and callartist.kwdoc
on that class.artist.kwdoc
introspects the subclass and summarizes its properties as a substring, whichgets interpolated into the docstring.
Note that this scheme does not work for decorating an Artist's__init__
, asthe subclass and its properties are not defined yet at that point. Instead,@_docstring.interpd
can be used to decorate the class itself -- at thatpoint,kwdoc
can list the properties and interpolate them into__init__.__doc__
.
Inherit docstrings#
If a subclass overrides a method but does not change the semantics, we canreuse the parent docstring for the method of the child class. Python does thisautomatically, if the subclass method does not have a docstring.
Use a plain comment#docstringinherited
to denote the intention to reusethe parent docstring. That way we do not accidentally create a docstring inthe future:
classA:deffoo():"""The parent docstring."""passclassB(A):deffoo():# docstring inheritedpass
Add figures#
As above (seeInclude figures and files), figures in the examples gallerycan be referenced with a..plot::
directive pointing to the python scriptthat created the figure. For instance thelegend
docstring referencesthe fileexamples/text_labels_and_annotations/legend.py
:
"""...Examples--------.. plot:: gallery/text_labels_and_annotations/legend.py"""
Note thatexamples/text_labels_and_annotations/legend.py
has been mapped togallery/text_labels_and_annotations/legend.py
, a redirection that may befixed in future re-organization of the docs.
Plots can also be directly placed inside docstrings. Details are inmatplotlib.sphinxext.plot_directive. A short example is:
"""...Examples--------.. plot:: import matplotlib.image as mpimg img = mpimg.imread('_static/stinkbug.png') imgplot = plt.imshow(img)"""
An advantage of this style over referencing an example script is that thecode will also appear in interactive docstrings.
Generate inheritance diagrams#
Class inheritance diagrams can be generated with the Sphinxinheritance-diagram directive.
Example:
..inheritance-diagram:: matplotlib.patches matplotlib.lines matplotlib.text:parts: 2
Write examples and tutorials#
Examples and tutorials are Python scripts that are run bySphinx Gallery.Sphinx Gallery finds*.py
files in source directories and runs the files tocreate images and narrative that are embedded in*.rst
files in a buildlocation of thedoc/
directory. Files in the build location should notbe directly edited as they will be overwritten by Sphinx gallery. CurrentlyMatplotlib has four galleries as follows:
Source location | Build location |
---|---|
|
|
|
|
|
|
|
|
The first three are traditional galleries. The last,galleries/users_explain
, is a mixed gallery where some of the files areraw*.rst
files and some are*.py
files; Sphinx Gallery just copiesthese*.rst
files from the source location to the build location (seeRaw restructured text files in the gallery, below).
In the Python files, to exclude an example from having a plot generated, insert"sgskip" somewhere in the filename.
The format of these files is relatively straightforward. Properlyformatted comment blocks are treated asReST text, the code isdisplayed, and figures are put into the built page. Matplotlib uses the#%%
section separator so that IDEs will identify "code cells" to makeit easy to re-run sub-sections of the example.
For instance the exampleLine plotexample is generated from/galleries/examples/lines_bars_and_markers/simple_plot.py
, which lookslike:
"""===========Simple Plot===========Create a simple plot."""importmatplotlib.pyplotaspltimportnumpyasnp# Data for plottingt=np.arange(0.0,2.0,0.01)s=1+np.sin(2*np.pi*t)# Note that using plt.subplots below is equivalent to using# fig = plt.figure and then ax = fig.add_subplot(111)fig,ax=plt.subplots()ax.plot(t,s)ax.set(xlabel='time (s)',ylabel='voltage (mV)',title='About as simple as it gets, folks')ax.grid()plt.show()
The first comment block is treated asReST text. The other comment blocksrender as comments inLine plot.
Tutorials are made with the exact same mechanism, except they are longer andtypically have more than one comment block (i.e.Quick start guide). Thefirst comment block can be the same as the example above. Subsequent blocks ofReST text are delimited by the line#%%
:
"""===========Simple Plot===========Create a simple plot."""...ax.grid()plt.show()# %%# Second plot# ===========## This is a second plot that is very nicefig,ax=plt.subplots()ax.plot(np.sin(range(50)))
In this way text, code, and figures are output in a "notebook" style.
Sample data#
When sample data comes from a public dataset, please cite the source of thedata. Sample data should be written out in the code. When this is notfeasible, the data can be loaded usingcbook.get_sample_data
.
importmatplotlib.cbookascbookfh=cbook.get_sample_data('mydata.dat')
If the data is too large to be included in the code, it should be added tolib/matplotlib/mpl-data/sample_data/
Create mini-gallery#
The showcased Matplotlib functions should be listed in an admonition at thebottom as follows
# %%## .. admonition:: References## The use of the following functions, methods, classes and modules is shown# in this example:## - `matplotlib.axes.Axes.fill` / `matplotlib.pyplot.fill`# - `matplotlib.axes.Axes.axis` / `matplotlib.pyplot.axis`
This allows sphinx-gallery to place an entry to the example in themini-gallery of the mentioned functions. Whether or not a function is mentionedhere should be decided depending on if a mini-gallery link prominently helpsto illustrate that function; e.g. mentionmatplotlib.pyplot.subplots
onlyin examples that are about laying out subplots, not in every example that usesit.
Functions that exist inpyplot
as well as in Axes or Figure should mentionboth references no matter which one is used in the example code. Thepyplot
reference should always be the second to mention; see the example above.
Order examples#
The order of the sections of theTutorials and theExamples, aswell as the order of the examples within each section are determined in atwo step process from within the/doc/sphinxext/gallery_order.py
:
Explicit order: This file contains a list of folders for the section orderand a list of examples for the subsection order. The order of the itemsshown in the doc pages is the order those items appear in those lists.
Implicit order: If a folder or example is not in those lists, it will beappended after the explicitly ordered items and all of those additionalitems will be ordered by pathname (for the sections) or by filename(for the subsections).
As a consequence, if you want to let your example appear in a certainposition in the gallery, extend those lists with your example.In case no explicit order is desired or necessary, still make sureto name your example consistently, i.e. use the main function or subjectof the example as first word in the filename; e.g. an image exampleshould ideally be named similar toimshow_mynewexample.py
.
Raw restructured text files in the gallery#
Sphinx Gallery folders usually consist of aREADME.txt
and a series ofPython source files that are then translated to anindex.rst
file and aseries ofexample_name.rst
files in thedoc/
subdirectories.However, Sphinx Gallery also allows raw*.rst
files to be passed through agallery (seeManually passing files in the Sphinx Gallery documentation). Weuse this feature ingalleries/users_explain
, where, for instance,galleries/users_explain/colors
is a regular Sphinx Gallerysubdirectory, butgalleries/users_explain/artists
has a mix of*.rst
and*py
files. For mixed subdirectories like this, we must addany*.rst
files to a:toctree:
, either in theREADME.txt
or in amanualindex.rst
.
Examples guidelines#
The gallery of examples contains visual demonstrations of matplotlib features. Galleryexamples exist so that users can scan through visual examples. Unlike tutorials or userguides, gallery examples teach by demonstration, rather than by explanation orinstruction.
Gallery examples should contain a very brief description ofwhat is being demonstratedand, when relevant,how it is achieved. Explanations should be brief, providing onlythe minimal context necessary for understanding the example. Cross-link relateddocumentation (e.g. tutorials, user guides and API entries) and tag the example withrelated concepts.
Format#
AllExamples should aim to follow these guidelines:
- Title:
Describe content in a short sentence (approx. 1-6 words). Do not usedemo asthis is implied by being an example. Avoid implied verbs such ascreate,make, etc, e.g.annotated heatmaps is preferred tocreate annotatedheatmaps. Use the simple present tense when a verb is necessary, e.g.Fill thearea between two curves
- Description:
In a short paragraph (approx 1-3 sentences) describe what visualizationtechnique is being demonstrated and how library features are used toexecute the technique, e.g.Set bar color and bar label entries using thecolor and label parameters of ~Axes.bar
- Plot:
Clearly demonstrate the subject and, when possible, show edge cases and differentapplications. While the plot should be visually appealing, prioritize keeping theplot uncluttered.
- Code:
Write the minimum necessary to showcase the feature that is the focus of theexample. Avoid custom styling and annotation (titles, legends, colors, etc.)when it will not improve the clarity of the example.
Use short comments sparingly to describe what hard to follow parts of code aredoing. When more context or explanation is required, add a text paragraph beforethe code example.
Identify whether artists intersect demonstrates the point of visual examples.This example is "messy" in that it's hard to categorize, but the gallery is the rightspot for it because it makes sense to find it by visual search
Interactive adjustment of colormap range is anexample of a good descriptive title that briefly summarizes how the showcasedlibrary features are used to implement the demonstrated visualization technique.
Lines with a ticked patheffect is an example of having aminimal amount of code necessary to showcase the feature. The lack of extraneous codemakes it easier for the reader to map which parts of code correspond to which parts ofthe plot.
Figure size#
When customizing figure sizes, we aim to avoid downscaling in rendered HTML docs.The current width limit (induced bypydata-sphinx-theme) is 720px, i.e.figsize=(7.2,...)
, or 896px if the page does not have subsections andthus does not have the "On this page" navigation on the right-hand side.
Plot types guidelines#
ThePlot types gallery provides an overview of the types of visualizations thatMatplotlib provides out of the box, meaning that there is a high-level API forgenerating each type of chart. Additions to this gallery are generally discouragedbecause this gallery is heavily curated and tightly scoped to methods onmatplotlib.axes.Axes
.
Format#
- title:
Method signature with required arguments, e.g.
plot(x,y)
- description:
In one sentence, describe the visualization that the method produces andlink to the API documentation, e.g.Draws a bar chart. See ~Axes.bar.When necessary, add an additional sentence explaining the use case forthis function vs a very similar one, e.g. stairs vs step.
- plot:
Use data with a self explanatory structure to illustrate the type of data thisplotting method is typically used for.
- code:
The code should be about 5-10 lines with minimal customization. Plots inthis gallery use the
_mpl-gallery
stylesheet for a uniform aesthetic.
Miscellaneous#
Move documentation#
Sometimes it is desirable to move or consolidate documentation. With noaction this will lead to links either going dead (404) or pointing to oldversions of the documentation. Preferable is to replace the old pagewith an html refresh that immediately redirects the viewer to the newpage. So, for example we move/doc/topic/old_info.rst
to/doc/topic/new_info.rst
. We remove/doc/topic/old_info.rst
andin/doc/topic/new_info.rst
we insert aredirect-from
directive thattells sphinx to still make the old file with the html refresh/redirect in it(probably near the top of the file to make it noticeable)
..redirect-from:: /topic/old_info
In the built docs this will yield an html file/build/html/topic/old_info.html
that has a refresh tonew_info.html
.If the two files are in different subdirectories:
..redirect-from:: /old_topic/old_info2
will yield an html file/build/html/old_topic/old_info2.html
that has a(relative) refresh to../topic/new_info.html
.
Use the full path for this directive, relative to the doc root athttps://matplotlib.org/stable/
. So/old_topic/old_info2
would befound by users athttp://matplotlib.org/stable/old_topic/old_info2
.For clarity, do not use relative links.
Navbar and style#
Matplotlib has a few subprojects that share the same navbar and style, so theseare centralized as a sphinx theme atmpl_sphinx_theme. Changes to thestyle or topbar should be made there to propagate across all subprojects.
Analytics#
Documentation page analytics are available athttps://views.scientific-python.org/matplotlib.org.