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

Skip to content

Commit c7ad141

Browse files
committed
DOC: quic_start and figure changes
1 parent 6a9dff8 commit c7ad141

File tree

4 files changed

+1024
-0
lines changed

4 files changed

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

0 commit comments

Comments
 (0)