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

Skip to content

Commit ad2c869

Browse files
committed
Minor fixes in Basic Usage tutorial
- fix typos and PEP8 (line 338) - apply terminology and unify capitalization acc. to https://matplotlib.org/stable/devel/style_guide.html#terminology - replace -- by en dash (–), as smartquotes is set to False in conf.py - explicitly apply ConciseDateFormatter so that it's clear why the date axis is formatted the way it is(examples\ticks\date_concise_formatter.py registers the ConciseDateConverter and when the documentation is being built, this example is processed before the tutorials and hence the registered converter is still in effect) - apply auto aspect to imshow axes for a visually more pleasing effect - remove redundant redefinition of x at line 246 and move definition of xdata at line 208 to where it is used
1 parent 505cdff commit ad2c869

File tree

1 file changed

+68
-66
lines changed

1 file changed

+68
-66
lines changed

tutorials/introductory/usage.py

Lines changed: 68 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@
2121
# widgets, etc.), each of which can contain one or more `~.axes.Axes`, an
2222
# area where points can be specified in terms of x-y coordinates (or theta-r
2323
# 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:
2626

2727
fig, ax = plt.subplots() # Create a figure containing a single axes.
2828
ax.plot([1, 2, 3, 4], [1, 4, 2, 3]); # Plot some data on the axes.
@@ -33,33 +33,33 @@
3333
# Parts of a Figure
3434
# =================
3535
#
36-
# Here are the components of a Matplotlib figure.
36+
# Here are the components of a Matplotlib Figure.
3737
#
3838
# .. image:: ../../_static/anatomy.png
3939
#
4040
# :class:`~matplotlib.figure.Figure`
4141
# ----------------------------------
4242
#
43-
# The **whole** figure. The figure keeps
43+
# The **whole** figure. The Figure keeps
4444
# 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
4646
# even nested subfigures.
4747
#
48-
# The easiest way to create a new figure is with pyplot::
48+
# The easiest way to create a new Figure is with pyplot::
4949
#
5050
# fig = plt.figure() # an empty figure with no Axes
5151
# fig, ax = plt.subplots() # a figure with a single Axes
5252
# fig, axs = plt.subplots(2, 2) # a figure with a 2x2 grid of Axes
5353
#
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
5656
# :doc:`Matplotlib backends </users/explain/backends>` support zooming and
5757
# panning on figure windows.
5858
#
5959
# :class:`~matplotlib.axes.Axes`
6060
# ------------------------------
6161
#
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
6363
# plotting data, and usually includes two (or three in the case of 3D)
6464
# :class:`~matplotlib.axis.Axis` objects (be aware of the difference
6565
# between **Axes** and **Axis**) that provide ticks and tick labels to
@@ -70,15 +70,15 @@
7070
# :meth:`~matplotlib.axes.Axes.set_ylabel`).
7171
#
7272
# 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
7474
# plotting methods defined on them (e.g. ``ax.plot()``, shown above, uses
7575
# the `~.Axes.plot` method)
7676
#
7777
# :class:`~matplotlib.axis.Axis`
7878
# ------------------------------
7979
#
8080
# 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
8282
# of the ticks is determined by a `~matplotlib.ticker.Locator` object and the
8383
# ticklabel strings are formatted by a `~matplotlib.ticker.Formatter`. The
8484
# combination of the correct `.Locator` and `.Formatter` gives very fine
@@ -87,11 +87,11 @@
8787
# :class:`~matplotlib.artist.Artist`
8888
# ----------------------------------
8989
#
90-
# Basically, everything visible on the figure is an artist (even
90+
# Basically, everything visible on the Figure is an Artist (even
9191
# `.Figure`, `Axes <.axes.Axes>`, and `~.axis.Axis` objects). This includes
9292
# `.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
9595
# an Artist cannot be shared by multiple Axes, or moved from one to another.
9696
#
9797
# .. _input_types:
@@ -109,7 +109,7 @@
109109
# b = np.matrix([[1, 2], [3, 4]])
110110
# b_asarray = np.asarray(b)
111111
#
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
113113
# `numpy.recarray`, or a `pandas.DataFrame`. Matplotlib allows you provide
114114
# the ``data`` keyword argument and generate plots passing the strings
115115
# corresponding to the *x* and *y* variables.
@@ -131,21 +131,22 @@
131131
# Coding styles
132132
# =============
133133
#
134-
# The object-oriented and the pyplot interfaces
135-
# ---------------------------------------------
134+
# The explicit and the implicit approach of programming
135+
# -----------------------------------------------------
136136
#
137137
# As noted above, there are essentially two ways to use Matplotlib:
138138
#
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).
143143
#
144-
# So one can use the OO-style
144+
# So one can use the explicit style
145145

146146
x = np.linspace(0, 2, 100) # Sample data.
147147

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.
149150
fig, ax = plt.subplots(figsize=(5, 2.7), constrained_layout=True)
150151
ax.plot(x, x, label='linear') # Plot some data on the axes.
151152
ax.plot(x, x**2, label='quadratic') # Plot more data on the axes...
@@ -156,7 +157,7 @@
156157
ax.legend(); # Add a legend.
157158

158159
###############################################################################
159-
# or the pyplot-style:
160+
# or the implicit style:
160161

161162
x = np.linspace(0, 2, 100) # Sample data.
162163

@@ -175,11 +176,11 @@
175176
# figure creation. See the corresponding section in the gallery for more info:
176177
# :ref:`user_interfaces`.)
177178
#
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.
183184
#
184185
# .. note::
185186
#
@@ -205,14 +206,13 @@ def my_plotter(ax, data1, data2, param_dict):
205206
# which you would then use twice to populate two subplots:
206207

207208
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
209209
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(5, 2.7))
210210
my_plotter(ax1, data1, data2, {'marker': 'x'})
211211
my_plotter(ax2, data3, data4, {'marker': 'o'});
212212

213213
###############################################################################
214214
# 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;
216216
# Matplotlib has one at `mpl-cookiecutter
217217
# <https://github.com/matplotlib/matplotlib-extension-cookiecutter>`_
218218
#
@@ -221,9 +221,9 @@ def my_plotter(ax, data1, data2, param_dict):
221221
# ===============
222222
#
223223
# 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
227227
# after the fact with `~.Line2D.set_linestyle`.
228228

229229
fig, ax = plt.subplots(figsize=(5, 2.7))
@@ -237,21 +237,20 @@ def my_plotter(ax, data1, data2, param_dict):
237237
# ------
238238
#
239239
# 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
241241
# list of specifications. Some Artists will take multiple colors. i.e. for
242242
# a `~.Axes.scatter` plot, the edge of the markers can be different colors
243243
# from the interior:
244244

245245
fig, ax = plt.subplots(figsize=(5, 2.7))
246-
x = np.arange(len(data1))
247246
ax.scatter(data1, data2, s=50, facecolor='C0', edgecolor='k');
248247

249248
###############################################################################
250249
# Linewidths, linestyles, and markersizes
251250
# ---------------------------------------
252251
#
253252
# 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
255254
# can have a linestyle. See the :doc:`linestyles example
256255
# </gallery/lines_bars_and_markers/linestyles>`.
257256
#
@@ -318,21 +317,21 @@ def my_plotter(ax, data1, data2, param_dict):
318317
# where the ``r`` preceding the title string signifies that the string is a
319318
# *raw* string and not to treat backslashes as python escapes.
320319
# 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
322321
# :doc:`/tutorials/text/mathtext`. You can also use LaTeX directly to format
323322
# 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`.
325324
#
326325
# Annotations
327326
# -----------
328327
#
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
330329
# to *xy*, to a piece of text at *xytext*:
331330

332331
fig, ax = plt.subplots(figsize=(5, 2.7))
333332

334333
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)
336335
line, = ax.plot(t, s, lw=2)
337336

338337
ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
@@ -366,9 +365,9 @@ def my_plotter(ax, data1, data2, param_dict):
366365
# Axis scales and ticks
367366
# =====================
368367
#
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*.
372371
#
373372
# Scales
374373
# ------
@@ -381,6 +380,7 @@ def my_plotter(ax, data1, data2, param_dict):
381380
# manually:
382381

383382
fig, axs = plt.subplots(1, 2, figsize=(5, 2.7), constrained_layout=True)
383+
xdata = np.arange(len(data1)) # make an ordinal for this
384384
data = 10**data1
385385
axs[0].plot(xdata, data)
386386

@@ -390,14 +390,15 @@ def my_plotter(ax, data1, data2, param_dict):
390390
##############################################################################
391391
# The scale sets the mapping from data values to spacing along the Axis. This
392392
# 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`.
395395
#
396396
# Tick locators and formatters
397397
# ----------------------------
398398
#
399399
# 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`:
401402

402403
fig, axs = plt.subplots(2, 1, constrained_layout=True)
403404
axs[0].plot(xdata, data1)
@@ -422,11 +423,13 @@ def my_plotter(ax, data1, data2, param_dict):
422423
# well as floating point numbers. These get special locators and formatters
423424
# as appropriate. For dates:
424425

425-
fig, ax = plt.subplots(figsize=(5, 3.7), constrained_layout=True)
426+
fig, ax = plt.subplots(figsize=(5, 2.7), constrained_layout=True)
426427
dates = np.arange(np.datetime64('2021-11-15'), np.datetime64('2021-12-25'),
427428
np.timedelta64(1, 'h'))
428429
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);
430433

431434
##############################################################################
432435
# For more information see the date examples
@@ -436,7 +439,7 @@ def my_plotter(ax, data1, data2, param_dict):
436439
# :doc:`/gallery/lines_bars_and_markers/categorical_variables`).
437440

438441
fig, ax = plt.subplots(figsize=(5, 2.7), constrained_layout=True)
439-
categories = ['turnips', 'rutabega', 'cucumber', 'pumpkins']
442+
categories = ['turnips', 'rutabaga', 'cucumber', 'pumpkins']
440443

441444
ax.bar(categories, np.random.rand(len(categories)));
442445

@@ -464,7 +467,7 @@ def my_plotter(ax, data1, data2, param_dict):
464467
fig.colorbar(co, ax=axs[0, 1])
465468
axs[0, 1].set_title('contourf()')
466469

467-
pc = axs[1, 0].imshow(Z**2 * 100, cmap='plasma',
470+
pc = axs[1, 0].imshow(Z**2 * 100, cmap='plasma', aspect='auto',
468471
norm=mpl.colors.LogNorm(vmin=0.01, vmax=100))
469472
fig.colorbar(pc, ax=axs[1, 0], extend='both')
470473
axs[1, 0].set_title('imshow() with LogNorm()')
@@ -499,43 +502,42 @@ def my_plotter(ax, data1, data2, param_dict):
499502
# Adding a `~.Figure.colorbar` gives a key to relate the color back to the
500503
# underlying data. Colorbars are figure-level Artists, and are attached to
501504
# 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
503506
# colorbars can be complex: see
504507
# :doc:`/gallery/subplots_axes_and_figures/colorbar_placement` for
505508
# details. You can also change the appearance of colorbars with the
506509
# *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.
510513
#
511514
#
512-
# Working with multiple figures and axes
515+
# Working with multiple Figures and Axes
513516
# ======================================
514517
#
515-
# You can open multiple figures with multiple calls to
518+
# You can open multiple Figures with multiple calls to
516519
# ``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.
518521
#
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
520523
# ``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`.
522525

523526
fig, axd = plt.subplot_mosaic([['upleft', 'right'],
524527
['lowleft', 'right']], constrained_layout=True)
525528
axd['upleft'].set_title('upleft')
526529
axd['lowleft'].set_title('lowleft')
527-
axd['right'].set_title('right')
528-
plt.show()
530+
axd['right'].set_title('right');
529531

530532
###############################################################################
531-
# Matplotlib has quite sophisticated tools for arranging axes: See
533+
# Matplotlib has quite sophisticated tools for arranging Axes: See
532534
# :doc:`/tutorials/intermediate/arranging_axes` and
533535
# :doc:`/tutorials/provisional/mosaic`.
534536
#
535537
#
536538
# More reading
537539
# ============
538540
#
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

Comments
 (0)