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

Skip to content

Commit ced790c

Browse files
committed
DOC: explain figures [skip actions] [skip appveyor] [skip azp]
1 parent 651a874 commit ced790c

File tree

3 files changed

+175
-0
lines changed

3 files changed

+175
-0
lines changed

doc/users/explain/figures.rst

Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
2+
.. _figure_explanation:
3+
4+
================================================
5+
Creating, viewing, and saving Matplotlib Figures
6+
================================================
7+
8+
.. plot::
9+
:include-source:
10+
11+
fig = plt.figure(figsize=(2, 2), facecolor='0.8', layout='constrained')
12+
ax = fig.add_subplot()
13+
14+
When looking at Matplotlib visualization, you are almost always looking at
15+
Artists placed on a `~.Figure`. In the example above, the figure is the
16+
gray region and `~.Figure.add_subplot` has added an `~.axes.Axes` artist to the
17+
`~.Figure`. A more complicated visualization can add multiple Axes to
18+
the Figure, colorbars, legends, annotations, and the Axes theselves can have
19+
multiple Artists added to them (e.g. ``ax.plot`` or ``ax.imshow``).
20+
21+
.. _viewing_figures:
22+
23+
Viewing Figures
24+
================
25+
26+
We will discuss how to create Figures in more detail below, but first it is
27+
helpful to understand how to view a Figure. This varies based on how you are
28+
using Matplotlib, and what :ref:`Backend <what-is-a-backend>` you are using.
29+
30+
Notebooks and IDEs
31+
------------------
32+
33+
If you are using a Notebook (e.g. `Jupyter <https://jupyter.org>`_) or an IDE
34+
that renders Notebooks (PyCharm, VSCode, etc), then they have a backend that
35+
will render the Matplotlib Figure when a code cell is executed. One thing to
36+
be aware of is that the default Jupyter backend (``%matplotlib inline``) will
37+
by default trim or expand the figure size to have a tight box around Artists
38+
added to the Figure (see :ref:`saving_figures`, below).
39+
40+
Standalone scripts and interctive use
41+
-------------------------------------
42+
43+
If the user is on a client with a windowing system, there are a number of
44+
:ref:`Backends <what-is-a-backend>` that can be used to render the Figure to
45+
the screen, usually using a Python Qt, Tk, or Wx toolkit, though there is a native
46+
MacOS backend as well. These are typically chosen either in the user's
47+
:ref:`matplotlibrc <customizing-with-matplotlibrc-files>`, or by calling
48+
``matplotlib.use('Qt5Agg')`` at the beginning of a session or script.
49+
50+
When run from a script, or interactively (e.g. from an
51+
`iPython shell <https://https://ipython.readthedocs.io/en/stable/>`_) the Figure
52+
will not be shown until we call ``plt.show()``. The Figure will appear in
53+
a new GUI window, and usually will have a toolbar with Zoom, Pan, and other tools
54+
for interacting with the Figure. By default, ``plt.show()`` blocks
55+
further interaction from the script or shell until the Figure window is closed,
56+
though that can be toggled off for some pusposes.
57+
58+
Note that if you are on a client that does not have access to a windowing
59+
system, the Figure will fallback to being drawn using the "Agg" backend, and
60+
cannot be viewed, though it can be :ref:`saved <saving_figures>`.
61+
62+
.. _creating_figures:
63+
64+
Creating Figures
65+
================
66+
67+
By far the most common way to create a figure is using the
68+
`pyplot </tutorials/introductory/pyplot>` interface. As noted in
69+
`api_interfaces`, the pyplot interface serves two purposes. One is to spin
70+
up the Backend and keep track of GUI windows. The other is a global state for
71+
Axes and Artists that allow a short form API to plotting methods. In the
72+
example above, we only use pyplot for the first purpose, to create the Figure
73+
object, ``fig``.
74+
75+
In addition to `~.pyplot.Figure`, there are convenience methods to create Axes
76+
at the same time that the figure is created since these two actions are so commonly
77+
done at the same time. A simple grid can be achieved with `~.pyplot.subplots` (which
78+
simply wraps `~.Figure.subplots`):
79+
80+
.. plot::
81+
:include-source:
82+
83+
fig, axs = plt.subplots(2, 2, figsize=(4, 3), layout='constrained')
84+
85+
More complex grids can be achieved with `~.pyplot.subplot_mosaic` (which wraps
86+
`~.Figure.subplot_mosaic`):
87+
88+
.. plot::
89+
:include-source:
90+
91+
fig, axs = plt.subplot_mosaic([['A', 'right'], ['B', 'right']],
92+
figsize=(4, 3), layout='constrained')
93+
for ax_name in axs:
94+
axs[ax_name].text(0.5, 0.5, ax_name, ha='center', va='center')
95+
96+
We can also have subfigures inside figures (or other subfigures;
97+
:doc:`/examples/subplots_axes_and_figures/subfigures` for more details).
98+
99+
It is possible to directly instantiate a `.Figure` instance. This is usually
100+
only necessary if you want to create your own GUI application and not use
101+
the pyplot application. See the
102+
embedding examples in :doc:`/gallery/user_interfaces/` for examples of
103+
how to do this.
104+
105+
Figure options
106+
--------------
107+
108+
There are a few options available when creating figures. The Figure size on
109+
the screen is set by *figsize* and *dpi*. *figsize* is the ``(width, height)``
110+
of the Figure in inches (or, if prefered, units of 72 typographic points). *dpi*
111+
are how many pixels per inch the figure will be rendered at. To make you Figures
112+
appear on the screen at the physical size you requested, you should set *dpi*
113+
to the same *dpi* as your graphics system. Note that many graphics systems now use
114+
a "dpi ratio" to specify how many screen pixels are used to represent a graphics
115+
pixel. Matplotlib applies the dpi ratio to the *dpi* passed to the figure to make
116+
it have higher resolution, so you should pass the lower number to the figure.
117+
118+
The *facecolor*, *edgecolor*, *linewidth*, and *frameon* options all change the appearance of the
119+
figure in expected ways, with *frameon* making the figure transparent if set to *False*.
120+
121+
Finally, the user can specify a layout engine for the figure with the *layout*
122+
parameter. Currently Matplotlib supplies
123+
:doc:`"constrained" </tutorials/intermediate/constrainedlayout_guide>`,
124+
:ref:`"compressed" <compressed_layout>` and
125+
:doc:`"tight" </tutorials/intermediate/tight_layout_guide>` layout engines. These
126+
rescale axes inside the Figure to prevent overlap of ticklabels, and try and align
127+
axes, and can save signficant manual adjustment of artists on a Figure for many
128+
common cases.
129+
130+
.. _saving_figures:
131+
132+
Saving Figures
133+
==============
134+
135+
Finally, Figures can be saved to disk using the `~.Figure.savefig` method.
136+
``fig.savefig('MyFigure.png', dpi=200)`` will save a PNG formatted figure to
137+
the file ``MyFigure.png`` in the current directory on disk with 200 dots-per-inch
138+
resolution. Note that the filename can include a relative or absolute path to
139+
any place on the file system.
140+
141+
Many types of output are supported, including raster formats like PNG, GIF, JPEG,
142+
TIFF and vector formats like PDF, EPS, and SVG.
143+
144+
By default, the size of the saved Figure is set by the Figure size (in inches) and, for the raster
145+
formats, the *dpi*. If *dpi* is not set, then the *dpi* of the Figure is used.
146+
Note that *dpi* still has meaning for vector formats like PDF if the Figure includes
147+
Artists that have been :doc:`rasterized </gallery/misc/rasterization_demo>`; the
148+
*dpi* specified will be the resolution of the rasterized objects.
149+
150+
It is possible to change the size of the Figure using the *bbox_inches* argument
151+
to savefig. This can be specified manually, again in inches. However, by far
152+
the most common use is ``bbox_inches='tight'``. This option trims, or expands, the
153+
size of the figure so that it is tight around all the artists in a figure, with a
154+
small pad that can be specified by *pad_inches*, which defaults to 0.1 inches.
155+
The dashed box in the plot below shows the portion of the figure that would be
156+
saved if ``bbox_inches='tight'`` were used in savefig.
157+
158+
.. plot::
159+
160+
import matplotlib.pyplot as plt
161+
from matplotlib.patches import FancyBboxPatch
162+
163+
fig, ax = plt.subplots(figsize=(4, 2), facecolor='0.8')
164+
ax.set_position([0.1, 0.2, 0.8, 0.7])
165+
ax.set_aspect(1)
166+
bb = ax.get_tightbbox()
167+
bb = bb.padded(10)
168+
fancy = FancyBboxPatch(bb.p0, bb.width, bb.height, fc='none',
169+
ec=(0, 0.0, 0, 0.5), lw=2, linestyle='--',
170+
transform=None, clip_on=False)
171+
ax.add_patch(fancy)

doc/users/explain/index.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ Explanations
99
:maxdepth: 2
1010

1111
api_interfaces.rst
12+
figures.rst
1213
backends.rst
1314
writing_a_backend_pyplot_interface.rst
1415
interactive.rst

lib/matplotlib/figure.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@
1212
1313
`SubplotParams`
1414
Control the default spacing between subplots.
15+
16+
See :ref:`figure_explanation` for narrative on how figures are used in
17+
Matplotlib.
1518
"""
1619

1720
from contextlib import ExitStack

0 commit comments

Comments
 (0)