Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitaf481d9

Browse files
committed
DOC: explain figures [skip actions] [skip appveyor] [skip azp]
1 parent651a874 commitaf481d9

File tree

3 files changed

+191
-0
lines changed

3 files changed

+191
-0
lines changed

‎doc/users/explain/figures.rst

Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
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+
:doc:`pyplot</tutorials/introductory/pyplot>` interface. As noted in
69+
:ref:`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+
Sometimes we want to have a nested layout in a Figure, with two or more sets of
97+
Axes that do not necessarily share the same subplot grid.
98+
We can use `~.Figure.add_subfigure` or `~.Figure.subfigures` to create virtual
99+
figures inside a parent Figure; see
100+
:doc:`/gallery/subplots_axes_and_figures/subfigures` for more details.
101+
102+
..plot::
103+
:include-source:
104+
105+
fig = plt.figure(layout='constrained', facecolor='beige')
106+
fig.suptitle('Figure')
107+
figL, figR = fig.subfigures(1, 2)
108+
figL.set_facecolor('0.9')
109+
axL = figL.subplots(2, 1, sharex=True)
110+
figL.suptitle('Left subfigure')
111+
figR.set_facecolor('0.7')
112+
axR = figR.subplots(1, 2, sharey=True)
113+
figR.suptitle('Right subfigure')
114+
115+
It is possible to directly instantiate a `.Figure` instance. This is usually
116+
only necessary if you want to create your own GUI application and not use
117+
the pyplot application. See the
118+
embedding examples in:doc:`/gallery/user_interfaces/index` for examples of
119+
how to do this.
120+
121+
Figure options
122+
--------------
123+
124+
There are a few options available when creating figures. The Figure size on
125+
the screen is set by *figsize* and *dpi*. *figsize* is the ``(width, height)``
126+
of the Figure in inches (or, if prefered, units of 72 typographic points). *dpi*
127+
are how many pixels per inch the figure will be rendered at. To make your Figures
128+
appear on the screen at the physical size you requested, you should set *dpi*
129+
to the same *dpi* as your graphics system. Note that many graphics systems now use
130+
a "dpi ratio" to specify how many screen pixels are used to represent a graphics
131+
pixel. Matplotlib applies the dpi ratio to the *dpi* passed to the figure to make
132+
it have higher resolution, so you should pass the lower number to the figure.
133+
134+
The *facecolor*, *edgecolor*, *linewidth*, and *frameon* options all change the appearance of the
135+
figure in expected ways, with *frameon* making the figure transparent if set to *False*.
136+
137+
Finally, the user can specify a layout engine for the figure with the *layout*
138+
parameter. Currently Matplotlib supplies
139+
:doc:`"constrained"</tutorials/intermediate/constrainedlayout_guide>`,
140+
:ref:`"compressed"<compressed_layout>` and
141+
:doc:`"tight"</tutorials/intermediate/tight_layout_guide>` layout engines. These
142+
rescale axes inside the Figure to prevent overlap of ticklabels, and try and align
143+
axes, and can save signficant manual adjustment of artists on a Figure for many
144+
common cases.
145+
146+
.. _saving_figures:
147+
148+
Saving Figures
149+
==============
150+
151+
Finally, Figures can be saved to disk using the `~.Figure.savefig` method.
152+
``fig.savefig('MyFigure.png', dpi=200)`` will save a PNG formatted figure to
153+
the file ``MyFigure.png`` in the current directory on disk with 200 dots-per-inch
154+
resolution. Note that the filename can include a relative or absolute path to
155+
any place on the file system.
156+
157+
Many types of output are supported, including raster formats like PNG, GIF, JPEG,
158+
TIFF and vector formats like PDF, EPS, and SVG.
159+
160+
By default, the size of the saved Figure is set by the Figure size (in inches) and, for the raster
161+
formats, the *dpi*. If *dpi* is not set, then the *dpi* of the Figure is used.
162+
Note that *dpi* still has meaning for vector formats like PDF if the Figure includes
163+
Artists that have been:doc:`rasterized</gallery/misc/rasterization_demo>`; the
164+
*dpi* specified will be the resolution of the rasterized objects.
165+
166+
It is possible to change the size of the Figure using the *bbox_inches* argument
167+
to savefig. This can be specified manually, again in inches. However, by far
168+
the most common use is ``bbox_inches='tight'``. This option trims, or expands, the
169+
size of the figure so that it is tight around all the artists in a figure, with a
170+
small pad that can be specified by *pad_inches*, which defaults to 0.1 inches.
171+
The dashed box in the plot below shows the portion of the figure that would be
172+
saved if ``bbox_inches='tight'`` were used in savefig.
173+
174+
..plot::
175+
176+
import matplotlib.pyplot as plt
177+
from matplotlib.patches import FancyBboxPatch
178+
179+
fig, ax = plt.subplots(figsize=(4, 2), facecolor='0.8')
180+
ax.set_position([0.1, 0.2, 0.8, 0.7])
181+
ax.set_aspect(1)
182+
bb = ax.get_tightbbox()
183+
bb = bb.padded(10)
184+
fancy = FancyBboxPatch(bb.p0, bb.width, bb.height, fc='none',
185+
ec=(0, 0.0, 0, 0.5), lw=2, linestyle='--',
186+
transform=None, clip_on=False)
187+
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
fromcontextlibimportExitStack

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp