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

Skip to content

Commit 29865c6

Browse files
committed
DOC: fix levels in user/explain/figure
1 parent 5f29763 commit 29865c6

File tree

2 files changed

+271
-258
lines changed

2 files changed

+271
-258
lines changed
Lines changed: 257 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,257 @@
1+
2+
.. redirect-from:: /users/explain/figure
3+
4+
.. _figure_explanation:
5+
6+
+++++++++++++++++++++++
7+
Introduction to Figures
8+
+++++++++++++++++++++++
9+
10+
.. plot::
11+
:include-source:
12+
13+
fig = plt.figure(figsize=(2, 2), facecolor='lightskyblue',
14+
layout='constrained')
15+
fig.suptitle('Figure')
16+
ax = fig.add_subplot()
17+
ax.set_title('Axes', loc='left', fontstyle='oblique', fontsize='medium')
18+
19+
When looking at Matplotlib visualization, you are almost always looking at
20+
Artists placed on a `~.Figure`. In the example above, the figure is the
21+
blue region and `~.Figure.add_subplot` has added an `~.axes.Axes` artist to the
22+
`~.Figure` (see :ref:`figure_parts`). A more complicated visualization can add
23+
multiple Axes to the Figure, colorbars, legends, annotations, and the Axes
24+
themselves can have multiple Artists added to them
25+
(e.g. ``ax.plot`` or ``ax.imshow``).
26+
27+
.. contents:: :local:
28+
29+
30+
.. _viewing_figures:
31+
32+
Viewing Figures
33+
================
34+
35+
We will discuss how to create Figures in more detail below, but first it is
36+
helpful to understand how to view a Figure. This varies based on how you are
37+
using Matplotlib, and what :ref:`Backend <what-is-a-backend>` you are using.
38+
39+
Notebooks and IDEs
40+
------------------
41+
42+
.. figure:: /_static/FigureInline.png
43+
:alt: Image of figure generated in Jupyter Notebook with inline backend.
44+
:width: 400
45+
46+
Screenshot of a `Jupyter Notebook <https://jupyter.org>`_, with a figure
47+
generated via the default `inline
48+
<https://github.com/ipython/matplotlib-inline>`_ backend.
49+
50+
51+
If you are using a Notebook (e.g. `Jupyter <https://jupyter.org>`_) or an IDE
52+
that renders Notebooks (PyCharm, VSCode, etc), then they have a backend that
53+
will render the Matplotlib Figure when a code cell is executed. One thing to
54+
be aware of is that the default Jupyter backend (``%matplotlib inline``) will
55+
by default trim or expand the figure size to have a tight box around Artists
56+
added to the Figure (see :ref:`saving_figures`, below). If you use a backend
57+
other than the default "inline" backend, you will likely need to use an ipython
58+
"magic" like ``%matplotlib notebook`` for the Matplotlib :ref:`notebook
59+
<jupyter_notebooks_jupyterlab>` or ``%matplotlib widget`` for the `ipympl
60+
<https://matplotlib.org/ipympl/>`_ backend.
61+
62+
.. figure:: /_static/FigureNotebook.png
63+
:alt: Image of figure generated in Jupyter Notebook with notebook
64+
backend, including a toolbar.
65+
:width: 400
66+
67+
Screenshot of a Jupyter Notebook with an interactive figure generated via
68+
the ``%matplotlib notebook`` magic. Users should also try the similar
69+
`widget <https://matplotlib.org/ipympl/>`_ backend if using `JupyterLab
70+
<https://jupyterlab.readthedocs.io/en/stable/>`_.
71+
72+
73+
.. seealso::
74+
:ref:`interactive_figures`.
75+
76+
Standalone scripts and interactive use
77+
--------------------------------------
78+
79+
If the user is on a client with a windowing system, there are a number of
80+
:ref:`Backends <what-is-a-backend>` that can be used to render the Figure to
81+
the screen, usually using a Python Qt, Tk, or Wx toolkit, or the native MacOS
82+
backend. These are typically chosen either in the user's :ref:`matplotlibrc
83+
<customizing-with-matplotlibrc-files>`, or by calling, for example,
84+
``matplotlib.use('QtAgg')`` at the beginning of a session or script.
85+
86+
.. figure:: /_static/FigureQtAgg.png
87+
:alt: Image of figure generated from a script via the QtAgg backend.
88+
:width: 370
89+
90+
Screenshot of a Figure generated via a python script and shown using the
91+
QtAgg backend.
92+
93+
When run from a script, or interactively (e.g. from an
94+
`iPython shell <https://https://ipython.readthedocs.io/en/stable/>`_) the Figure
95+
will not be shown until we call ``plt.show()``. The Figure will appear in
96+
a new GUI window, and usually will have a toolbar with Zoom, Pan, and other tools
97+
for interacting with the Figure. By default, ``plt.show()`` blocks
98+
further interaction from the script or shell until the Figure window is closed,
99+
though that can be toggled off for some purposes. For more details, please see
100+
:ref:`controlling-interactive`.
101+
102+
Note that if you are on a client that does not have access to a windowing
103+
system, the Figure will fallback to being drawn using the "Agg" backend, and
104+
cannot be viewed, though it can be :ref:`saved <saving_figures>`.
105+
106+
.. seealso::
107+
:ref:`interactive_figures`.
108+
109+
.. _creating_figures:
110+
111+
Creating Figures
112+
================
113+
114+
By far the most common way to create a figure is using the
115+
:ref:`pyplot <pyplot_tutorial>` interface. As noted in
116+
:ref:`api_interfaces`, the pyplot interface serves two purposes. One is to spin
117+
up the Backend and keep track of GUI windows. The other is a global state for
118+
Axes and Artists that allow a short-form API to plotting methods. In the
119+
example above, we use pyplot for the first purpose, and create the Figure object,
120+
``fig``. As a side effect ``fig`` is also added to pyplot's global state, and
121+
can be accessed via `~.pyplot.gcf`.
122+
123+
Users typically want an Axes or a grid of Axes when they create a Figure, so in
124+
addition to `~.pyplot.figure`, there are convenience methods that return both
125+
a Figure and some Axes. A simple grid of Axes can be achieved with
126+
`.pyplot.subplots` (which
127+
simply wraps `.Figure.subplots`):
128+
129+
.. plot::
130+
:include-source:
131+
132+
fig, axs = plt.subplots(2, 2, figsize=(4, 3), layout='constrained')
133+
134+
More complex grids can be achieved with `.pyplot.subplot_mosaic` (which wraps
135+
`.Figure.subplot_mosaic`):
136+
137+
.. plot::
138+
:include-source:
139+
140+
fig, axs = plt.subplot_mosaic([['A', 'right'], ['B', 'right']],
141+
figsize=(4, 3), layout='constrained')
142+
for ax_name in axs:
143+
axs[ax_name].text(0.5, 0.5, ax_name, ha='center', va='center')
144+
145+
Sometimes we want to have a nested layout in a Figure, with two or more sets of
146+
Axes that do not share the same subplot grid.
147+
We can use `~.Figure.add_subfigure` or `~.Figure.subfigures` to create virtual
148+
figures inside a parent Figure; see
149+
:doc:`/gallery/subplots_axes_and_figures/subfigures` for more details.
150+
151+
.. plot::
152+
:include-source:
153+
154+
fig = plt.figure(layout='constrained', facecolor='lightskyblue')
155+
fig.suptitle('Figure')
156+
figL, figR = fig.subfigures(1, 2)
157+
figL.set_facecolor('thistle')
158+
axL = figL.subplots(2, 1, sharex=True)
159+
axL[1].set_xlabel('x [m]')
160+
figL.suptitle('Left subfigure')
161+
figR.set_facecolor('paleturquoise')
162+
axR = figR.subplots(1, 2, sharey=True)
163+
axR[0].set_title('Axes 1')
164+
figR.suptitle('Right subfigure')
165+
166+
It is possible to directly instantiate a `.Figure` instance without using the
167+
pyplot interface. This is usually only necessary if you want to create your
168+
own GUI application or service that you do not want carrying the pyplot global
169+
state. See the embedding examples in :ref:`user_interfaces` for examples of
170+
how to do this.
171+
172+
Figure options
173+
--------------
174+
175+
There are a few options available when creating figures. The Figure size on
176+
the screen is set by *figsize* and *dpi*. *figsize* is the ``(width, height)``
177+
of the Figure in inches (or, if preferred, units of 72 typographic points). *dpi*
178+
are how many pixels per inch the figure will be rendered at. To make your Figures
179+
appear on the screen at the physical size you requested, you should set *dpi*
180+
to the same *dpi* as your graphics system. Note that many graphics systems now use
181+
a "dpi ratio" to specify how many screen pixels are used to represent a graphics
182+
pixel. Matplotlib applies the dpi ratio to the *dpi* passed to the figure to make
183+
it have higher resolution, so you should pass the lower number to the figure.
184+
185+
The *facecolor*, *edgecolor*, *linewidth*, and *frameon* options all change the appearance of the
186+
figure in expected ways, with *frameon* making the figure transparent if set to *False*.
187+
188+
Finally, the user can specify a layout engine for the figure with the *layout*
189+
parameter. Currently Matplotlib supplies
190+
:ref:`"constrained" <constrainedlayout_guide>`,
191+
:ref:`"compressed" <compressed_layout>` and
192+
:ref:`"tight" <tight_layout_guide>` layout engines. These
193+
rescale axes inside the Figure to prevent overlap of ticklabels, and try and align
194+
axes, and can save significant manual adjustment of artists on a Figure for many
195+
common cases.
196+
197+
Adding Artists
198+
--------------
199+
200+
The `~.FigureBase` class has a number of methods to add artists to a `~.Figure` or
201+
a `~.SubFigure`. By far the most common are to add Axes of various configurations
202+
(`~.FigureBase.add_axes`, `~.FigureBase.add_subplot`, `~.FigureBase.subplots`,
203+
`~.FigureBase.subplot_mosaic`) and subfigures (`~.FigureBase.subfigures`). Colorbars
204+
are added to Axes or group of Axes at the Figure level (`~.FigureBase.colorbar`).
205+
It is also possible to have a Figure-level legend (`~.FigureBase.legend`).
206+
Other Artists include figure-wide labels (`~.FigureBase.suptitle`,
207+
`~.FigureBase.supxlabel`, `~.FigureBase.supylabel`) and text (`~.FigureBase.text`).
208+
Finally, low-level Artists can be added directly using `~.FigureBase.add_artist`
209+
usually with care being taken to use the appropriate transform. Usually these
210+
include ``Figure.transFigure`` which ranges from 0 to 1 in each direction, and
211+
represents the fraction of the current Figure size, or ``Figure.dpi_scale_trans``
212+
which will be in physical units of inches from the bottom left corner of the Figure
213+
(see :ref:`transforms_tutorial` for more details).
214+
215+
216+
.. _saving_figures:
217+
218+
Saving Figures
219+
==============
220+
221+
Finally, Figures can be saved to disk using the `~.Figure.savefig` method.
222+
``fig.savefig('MyFigure.png', dpi=200)`` will save a PNG formatted figure to
223+
the file ``MyFigure.png`` in the current directory on disk with 200 dots-per-inch
224+
resolution. Note that the filename can include a relative or absolute path to
225+
any place on the file system.
226+
227+
Many types of output are supported, including raster formats like PNG, GIF, JPEG,
228+
TIFF and vector formats like PDF, EPS, and SVG.
229+
230+
By default, the size of the saved Figure is set by the Figure size (in inches) and, for the raster
231+
formats, the *dpi*. If *dpi* is not set, then the *dpi* of the Figure is used.
232+
Note that *dpi* still has meaning for vector formats like PDF if the Figure includes
233+
Artists that have been :doc:`rasterized </gallery/misc/rasterization_demo>`; the
234+
*dpi* specified will be the resolution of the rasterized objects.
235+
236+
It is possible to change the size of the Figure using the *bbox_inches* argument
237+
to savefig. This can be specified manually, again in inches. However, by far
238+
the most common use is ``bbox_inches='tight'``. This option "shrink-wraps", trimming
239+
or expanding as needed, the size of the figure so that it is tight around all the artists
240+
in a figure, with a small pad that can be specified by *pad_inches*, which defaults to
241+
0.1 inches. The dashed box in the plot below shows the portion of the figure that
242+
would be saved if ``bbox_inches='tight'`` were used in savefig.
243+
244+
.. plot::
245+
246+
import matplotlib.pyplot as plt
247+
from matplotlib.patches import FancyBboxPatch
248+
249+
fig, ax = plt.subplots(figsize=(4, 2), facecolor='lightskyblue')
250+
ax.set_position([0.1, 0.2, 0.8, 0.7])
251+
ax.set_aspect(1)
252+
bb = ax.get_tightbbox()
253+
bb = bb.padded(10)
254+
fancy = FancyBboxPatch(bb.p0, bb.width, bb.height, fc='none',
255+
ec=(0, 0.0, 0, 0.5), lw=2, linestyle='--',
256+
transform=None, clip_on=False)
257+
ax.add_patch(fancy)

0 commit comments

Comments
 (0)