21
21
# widgets, etc.), each of which can contain one or more `~.axes.Axes`, an
22
22
# area where points can be specified in terms of x-y coordinates (or theta-r
23
23
# in a polar plot, x-y-z in a 3D plot, etc). The simplest way of
24
- # creating a figure with an axes is using `.pyplot.subplots`. We can then use
25
- # `.Axes.plot` to draw some data on the axes :
24
+ # creating a Figure with an Axes is using `.pyplot.subplots`. We can then use
25
+ # `.Axes.plot` to draw some data on the Axes :
26
26
27
27
fig , ax = plt .subplots () # Create a figure containing a single axes.
28
28
ax .plot ([1 , 2 , 3 , 4 ], [1 , 4 , 2 , 3 ]); # Plot some data on the axes.
33
33
# Parts of a Figure
34
34
# =================
35
35
#
36
- # Here are the components of a Matplotlib figure .
36
+ # Here are the components of a Matplotlib Figure .
37
37
#
38
38
# .. image:: ../../_static/anatomy.png
39
39
#
40
40
# :class:`~matplotlib.figure.Figure`
41
41
# ----------------------------------
42
42
#
43
- # The **whole** figure. The figure keeps
43
+ # The **whole** figure. The Figure keeps
44
44
# track of all the child :class:`~matplotlib.axes.Axes`, a group of
45
- # 'special' artists (titles, figure legends, colorbars, etc), and
45
+ # 'special' Artists (titles, figure legends, colorbars, etc), and
46
46
# even nested subfigures.
47
47
#
48
- # The easiest way to create a new figure is with pyplot::
48
+ # The easiest way to create a new Figure is with pyplot::
49
49
#
50
50
# fig = plt.figure() # an empty figure with no Axes
51
51
# fig, ax = plt.subplots() # a figure with a single Axes
52
52
# fig, axs = plt.subplots(2, 2) # a figure with a 2x2 grid of Axes
53
53
#
54
- # It is often convenient to create the axes together with the figure , but you
55
- # can also manually add axes later on. Note that many
54
+ # It is often convenient to create the Axes together with the Figure , but you
55
+ # can also manually add Axes later on. Note that many
56
56
# :doc:`Matplotlib backends </users/explain/backends>` support zooming and
57
57
# panning on figure windows.
58
58
#
59
59
# :class:`~matplotlib.axes.Axes`
60
60
# ------------------------------
61
61
#
62
- # An Axes is an artist attached to a figure that contains a region for
62
+ # An Axes is an Artist attached to a Figure that contains a region for
63
63
# plotting data, and usually includes two (or three in the case of 3D)
64
64
# :class:`~matplotlib.axis.Axis` objects (be aware of the difference
65
65
# between **Axes** and **Axis**) that provide ticks and tick labels to
70
70
# :meth:`~matplotlib.axes.Axes.set_ylabel`).
71
71
#
72
72
# The :class:`~.axes.Axes` class and its member functions are the primary
73
- # entry point to working with the OO interface, and have most of the
73
+ # entry point to working with the OOP interface, and have most of the
74
74
# plotting methods defined on them (e.g. ``ax.plot()``, shown above, uses
75
75
# the `~.Axes.plot` method)
76
76
#
77
77
# :class:`~matplotlib.axis.Axis`
78
78
# ------------------------------
79
79
#
80
80
# These objects set the scale and limits and generate ticks (the marks
81
- # on the axis ) and ticklabels (strings labeling the ticks). The location
81
+ # on the Axis ) and ticklabels (strings labeling the ticks). The location
82
82
# of the ticks is determined by a `~matplotlib.ticker.Locator` object and the
83
83
# ticklabel strings are formatted by a `~matplotlib.ticker.Formatter`. The
84
84
# combination of the correct `.Locator` and `.Formatter` gives very fine
87
87
# :class:`~matplotlib.artist.Artist`
88
88
# ----------------------------------
89
89
#
90
- # Basically, everything visible on the figure is an artist (even
90
+ # Basically, everything visible on the Figure is an Artist (even
91
91
# `.Figure`, `Axes <.axes.Axes>`, and `~.axis.Axis` objects). This includes
92
92
# `.Text` objects, `.Line2D` objects, :mod:`.collections` objects, `.Patch`
93
- # objects, etc... When the figure is rendered, all of the
94
- # artists are drawn to the **canvas**. Most Artists are tied to an Axes; such
93
+ # objects, etc. When the Figure is rendered, all of the
94
+ # Artists are drawn to the **canvas**. Most Artists are tied to an Axes; such
95
95
# an Artist cannot be shared by multiple Axes, or moved from one to another.
96
96
#
97
97
# .. _input_types:
109
109
# b = np.matrix([[1, 2], [3, 4]])
110
110
# b_asarray = np.asarray(b)
111
111
#
112
- # Most methods will also parse an addressible object like a *dict*, a
112
+ # Most methods will also parse an addressable object like a *dict*, a
113
113
# `numpy.recarray`, or a `pandas.DataFrame`. Matplotlib allows you provide
114
114
# the ``data`` keyword argument and generate plots passing the strings
115
115
# corresponding to the *x* and *y* variables.
131
131
# Coding styles
132
132
# =============
133
133
#
134
- # The object-oriented and the pyplot interfaces
135
- # ---------------------------------------------
134
+ # The explicit and the implicit approach of programming
135
+ # -----------------------------------------------------
136
136
#
137
137
# As noted above, there are essentially two ways to use Matplotlib:
138
138
#
139
- # - Explicitly create figures and axes , and call methods on them (the
140
- # "object- oriented (OO ) style").
141
- # - Rely on pyplot to automatically create and manage the figures and axes , and
142
- # use pyplot functions for plotting.
139
+ # - Explicitly create Figures and Axes , and call methods on them (the explicit
140
+ # or "object oriented programming (OOP ) style").
141
+ # - Rely on pyplot to automatically create and manage the Figures and Axes , and
142
+ # use pyplot functions for plotting (the implicit style) .
143
143
#
144
- # So one can use the OO- style
144
+ # So one can use the explicit style
145
145
146
146
x = np .linspace (0 , 2 , 100 ) # Sample data.
147
147
148
- # Note that even in the OO-style, we use `.pyplot.figure` to create the figure.
148
+ # Note that even in the explicit style, we use `.pyplot.figure` to create the
149
+ # Figure.
149
150
fig , ax = plt .subplots (figsize = (5 , 2.7 ), constrained_layout = True )
150
151
ax .plot (x , x , label = 'linear' ) # Plot some data on the axes.
151
152
ax .plot (x , x ** 2 , label = 'quadratic' ) # Plot more data on the axes...
156
157
ax .legend (); # Add a legend.
157
158
158
159
###############################################################################
159
- # or the pyplot- style:
160
+ # or the implicit style:
160
161
161
162
x = np .linspace (0 , 2 , 100 ) # Sample data.
162
163
175
176
# figure creation. See the corresponding section in the gallery for more info:
176
177
# :ref:`user_interfaces`.)
177
178
#
178
- # Matplotlib's documentation and examples use both the OO and the pyplot
179
- # styles. In general, we suggest using the OO style, particularly for
180
- # complicated plots, and functions and scripts that are intended to be reused
181
- # as part of a larger project. However, the pyplot style can be very
182
- # conveneient for quick interactive work.
179
+ # Matplotlib's documentation and examples use both the explicit and the
180
+ # implicit styles. In general, we suggest using the explicit style,
181
+ # particularly for complicated plots, and functions and scripts that are
182
+ # intended to be reused as part of a larger project. However, the implicit
183
+ # style can be very convenient for quick interactive work.
183
184
#
184
185
# .. note::
185
186
#
@@ -205,14 +206,13 @@ def my_plotter(ax, data1, data2, param_dict):
205
206
# which you would then use twice to populate two subplots:
206
207
207
208
data1 , data2 , data3 , data4 = np .random .randn (4 , 100 ) # make 4 random data sets
208
- xdata = np .arange (len (data1 )) # make an ordinal for this
209
209
fig , (ax1 , ax2 ) = plt .subplots (1 , 2 , figsize = (5 , 2.7 ))
210
210
my_plotter (ax1 , data1 , data2 , {'marker' : 'x' })
211
211
my_plotter (ax2 , data3 , data4 , {'marker' : 'o' });
212
212
213
213
###############################################################################
214
214
# Note that if you want to install these as a python package, or any other
215
- # customizations you could use use one of the many templates on the web;
215
+ # customizations you could use one of the many templates on the web;
216
216
# Matplotlib has one at `mpl-cookiecutter
217
217
# <https://github.com/matplotlib/matplotlib-extension-cookiecutter>`_
218
218
#
@@ -221,9 +221,9 @@ def my_plotter(ax, data1, data2, param_dict):
221
221
# ===============
222
222
#
223
223
# Most plotting methods have styling options for the Artists, accessible either
224
- # when a plotting method is called, or from a "setter" on the artist . In the
225
- # plot below we manaully set the *color*, *linewidth*, and *linestyle* of the
226
- # artists created by `~.Axes.plot`, and we set the linestyle of the second line
224
+ # when a plotting method is called, or from a "setter" on the Artist . In the
225
+ # plot below we manually set the *color*, *linewidth*, and *linestyle* of the
226
+ # Artists created by `~.Axes.plot`, and we set the linestyle of the second line
227
227
# after the fact with `~.Line2D.set_linestyle`.
228
228
229
229
fig , ax = plt .subplots (figsize = (5 , 2.7 ))
@@ -237,21 +237,20 @@ def my_plotter(ax, data1, data2, param_dict):
237
237
# ------
238
238
#
239
239
# Matplotlib has a very flexible array of colors that are accepted for most
240
- # artists ; see the :doc:`colors tutorial </tutorials/colors/colors>` for a
240
+ # Artists ; see the :doc:`colors tutorial </tutorials/colors/colors>` for a
241
241
# list of specifications. Some Artists will take multiple colors. i.e. for
242
242
# a `~.Axes.scatter` plot, the edge of the markers can be different colors
243
243
# from the interior:
244
244
245
245
fig , ax = plt .subplots (figsize = (5 , 2.7 ))
246
- x = np .arange (len (data1 ))
247
246
ax .scatter (data1 , data2 , s = 50 , facecolor = 'C0' , edgecolor = 'k' );
248
247
249
248
###############################################################################
250
249
# Linewidths, linestyles, and markersizes
251
250
# ---------------------------------------
252
251
#
253
252
# Line widths are typically in typographic points (1 pt = 1/72 inch) and
254
- # available for artists that have stroked lines. Similarly, stroked lines
253
+ # available for Artists that have stroked lines. Similarly, stroked lines
255
254
# can have a linestyle. See the :doc:`linestyles example
256
255
# </gallery/lines_bars_and_markers/linestyles>`.
257
256
#
@@ -318,21 +317,21 @@ def my_plotter(ax, data1, data2, param_dict):
318
317
# where the ``r`` preceding the title string signifies that the string is a
319
318
# *raw* string and not to treat backslashes as python escapes.
320
319
# Matplotlib has a built-in TeX expression parser and
321
- # layout engine, and ships its own math fonts -- for details see
320
+ # layout engine, and ships its own math fonts – for details see
322
321
# :doc:`/tutorials/text/mathtext`. You can also use LaTeX directly to format
323
322
# your text and incorporate the output directly into your display figures or
324
- # saved postscript -- see :doc:`/tutorials/text/usetex`.
323
+ # saved postscript – see :doc:`/tutorials/text/usetex`.
325
324
#
326
325
# Annotations
327
326
# -----------
328
327
#
329
- # We can also annotate points on a plot, odten by connecting an arrow pointing
328
+ # We can also annotate points on a plot, often by connecting an arrow pointing
330
329
# to *xy*, to a piece of text at *xytext*:
331
330
332
331
fig , ax = plt .subplots (figsize = (5 , 2.7 ))
333
332
334
333
t = np .arange (0.0 , 5.0 , 0.01 )
335
- s = np .cos (2 * np .pi * t )
334
+ s = np .cos (2 * np .pi * t )
336
335
line , = ax .plot (t , s , lw = 2 )
337
336
338
337
ax .annotate ('local max' , xy = (2 , 1 ), xytext = (3 , 1.5 ),
@@ -366,9 +365,9 @@ def my_plotter(ax, data1, data2, param_dict):
366
365
# Axis scales and ticks
367
366
# =====================
368
367
#
369
- # Each Axes has two (or three) `~.axis.Axis` objects represnting the x- and
370
- # y-axis. These control the *scale* of the axis , the tick *Locators * and the
371
- # tick *Formatters *.
368
+ # Each Axes has two (or three) `~.axis.Axis` objects representing the x- and
369
+ # y-axis. These control the *scale* of the Axis , the tick *locators * and the
370
+ # tick *formatters *.
372
371
#
373
372
# Scales
374
373
# ------
@@ -381,6 +380,7 @@ def my_plotter(ax, data1, data2, param_dict):
381
380
# manually:
382
381
383
382
fig , axs = plt .subplots (1 , 2 , figsize = (5 , 2.7 ), constrained_layout = True )
383
+ xdata = np .arange (len (data1 )) # make an ordinal for this
384
384
data = 10 ** data1
385
385
axs [0 ].plot (xdata , data )
386
386
@@ -390,14 +390,15 @@ def my_plotter(ax, data1, data2, param_dict):
390
390
##############################################################################
391
391
# The scale sets the mapping from data values to spacing along the Axis. This
392
392
# happens in both directions, and gets combined into a *transform*, which
393
- # is the way that Matplotlib maps from data co-ordinates to Axes, Figure, or
394
- # screen co-ordinates . See :doc:`/tutorials/advanced/transforms_tutorial`.
393
+ # is the way that Matplotlib maps from data coordinates to Axes, Figure, or
394
+ # screen coordinates . See :doc:`/tutorials/advanced/transforms_tutorial`.
395
395
#
396
396
# Tick locators and formatters
397
397
# ----------------------------
398
398
#
399
399
# Each Axis has a tick *locator* and *formatter* that choose where along the
400
- # axes to put tick marks. A simple interface to this is `~.Axes.set_xticks`:
400
+ # Axis objects to put tick marks. A simple interface to this is
401
+ # `~.Axes.set_xticks`:
401
402
402
403
fig , axs = plt .subplots (2 , 1 , constrained_layout = True )
403
404
axs [0 ].plot (xdata , data1 )
@@ -422,11 +423,13 @@ def my_plotter(ax, data1, data2, param_dict):
422
423
# well as floating point numbers. These get special locators and formatters
423
424
# as appropriate. For dates:
424
425
425
- fig , ax = plt .subplots (figsize = (5 , 3 .7 ), constrained_layout = True )
426
+ fig , ax = plt .subplots (figsize = (5 , 2 .7 ), constrained_layout = True )
426
427
dates = np .arange (np .datetime64 ('2021-11-15' ), np .datetime64 ('2021-12-25' ),
427
428
np .timedelta64 (1 , 'h' ))
428
429
data = np .cumsum (np .random .randn (len (dates )))
429
- ax .plot (dates , data );
430
+ ax .plot (dates , data )
431
+ cdf = mpl .dates .ConciseDateFormatter (ax .xaxis .get_major_locator ())
432
+ ax .xaxis .set_major_formatter (cdf );
430
433
431
434
##############################################################################
432
435
# For more information see the date examples
@@ -436,7 +439,7 @@ def my_plotter(ax, data1, data2, param_dict):
436
439
# :doc:`/gallery/lines_bars_and_markers/categorical_variables`).
437
440
438
441
fig , ax = plt .subplots (figsize = (5 , 2.7 ), constrained_layout = True )
439
- categories = ['turnips' , 'rutabega ' , 'cucumber' , 'pumpkins' ]
442
+ categories = ['turnips' , 'rutabaga ' , 'cucumber' , 'pumpkins' ]
440
443
441
444
ax .bar (categories , np .random .rand (len (categories )));
442
445
@@ -464,7 +467,7 @@ def my_plotter(ax, data1, data2, param_dict):
464
467
fig .colorbar (co , ax = axs [0 , 1 ])
465
468
axs [0 , 1 ].set_title ('contourf()' )
466
469
467
- pc = axs [1 , 0 ].imshow (Z ** 2 * 100 , cmap = 'plasma' ,
470
+ pc = axs [1 , 0 ].imshow (Z ** 2 * 100 , cmap = 'plasma' , aspect = 'auto' ,
468
471
norm = mpl .colors .LogNorm (vmin = 0.01 , vmax = 100 ))
469
472
fig .colorbar (pc , ax = axs [1 , 0 ], extend = 'both' )
470
473
axs [1 , 0 ].set_title ('imshow() with LogNorm()' )
@@ -499,43 +502,42 @@ def my_plotter(ax, data1, data2, param_dict):
499
502
# Adding a `~.Figure.colorbar` gives a key to relate the color back to the
500
503
# underlying data. Colorbars are figure-level Artists, and are attached to
501
504
# a ScalarMappable (where they get their information about the norm and
502
- # colormap) and usually steal space from a parent axes . Placement of
505
+ # colormap) and usually steal space from a parent Axes . Placement of
503
506
# colorbars can be complex: see
504
507
# :doc:`/gallery/subplots_axes_and_figures/colorbar_placement` for
505
508
# details. You can also change the appearance of colorbars with the
506
509
# *extend* keyword to add arrows to the ends, and *shrink* and *aspect* to
507
- # control the size. Finally, the colorbar will have default Locators
508
- # and Formatters appropriate to the Norm . These can be changed as for
509
- # other axis objects.
510
+ # control the size. Finally, the colorbar will have default locators
511
+ # and formatters appropriate to the norm . These can be changed as for
512
+ # other Axis objects.
510
513
#
511
514
#
512
- # Working with multiple figures and axes
515
+ # Working with multiple Figures and Axes
513
516
# ======================================
514
517
#
515
- # You can open multiple figures with multiple calls to
518
+ # You can open multiple Figures with multiple calls to
516
519
# ``fig = plt.figure()`` or ``fig2, ax = plt.subplots()``. By keeping the
517
- # object references you can add artists to either figure .
520
+ # object references you can add Artists to either Figure .
518
521
#
519
- # Multiple axes can be added a number of ways, but the most basic is
522
+ # Multiple Axes can be added a number of ways, but the most basic is
520
523
# ``plt.subplots()`` as used above. One can achieve more complex layouts,
521
- # with axes spanning columns or rows, using `~.pyplot.subplot_mosaic`.
524
+ # with Axes objects spanning columns or rows, using `~.pyplot.subplot_mosaic`.
522
525
523
526
fig , axd = plt .subplot_mosaic ([['upleft' , 'right' ],
524
527
['lowleft' , 'right' ]], constrained_layout = True )
525
528
axd ['upleft' ].set_title ('upleft' )
526
529
axd ['lowleft' ].set_title ('lowleft' )
527
- axd ['right' ].set_title ('right' )
528
- plt .show ()
530
+ axd ['right' ].set_title ('right' );
529
531
530
532
###############################################################################
531
- # Matplotlib has quite sophisticated tools for arranging axes : See
533
+ # Matplotlib has quite sophisticated tools for arranging Axes : See
532
534
# :doc:`/tutorials/intermediate/arranging_axes` and
533
535
# :doc:`/tutorials/provisional/mosaic`.
534
536
#
535
537
#
536
538
# More reading
537
539
# ============
538
540
#
539
- # - For more plot types see :doc:`Plot types </plot_types/index>` and the
540
- # :doc:`API reference </api/index>`, in particlar the
541
- # :doc:`Axes API </api/axes_api>`.
541
+ # For more plot types see :doc:`Plot types </plot_types/index>` and the
542
+ # :doc:`API reference </api/index>`, in particlar the
543
+ # :doc:`Axes API </api/axes_api>`.
0 commit comments