5
5
6
6
This tutorial covers some basic usage patterns and best-practices to
7
7
help you get started with Matplotlib.
8
+ """
8
9
9
- .. _general_concepts:
10
-
11
- General Concepts
12
- ================
13
-
14
- :mod:`matplotlib` has an extensive codebase that can be daunting to many
15
- new users. However, most of matplotlib can be understood with a fairly
16
- simple conceptual framework and knowledge of a few important points.
17
-
18
- Plotting requires action on a range of levels, from the most general
19
- (e.g., 'contour this 2-D array') to the most specific (e.g., 'color
20
- this screen pixel red'). The purpose of a plotting package is to assist
21
- you in visualizing your data as easily as possible, with all the necessary
22
- control -- that is, by using relatively high-level commands most of
23
- the time, and still have the ability to use the low-level commands when
24
- needed.
25
-
26
- Therefore, everything in matplotlib is organized in a hierarchy. At the top
27
- of the hierarchy is the matplotlib "state-machine environment" which is
28
- provided by the :mod:`matplotlib.pyplot` module. At this level, simple
29
- functions are used to add plot elements (lines, images, text, etc.) to
30
- the current axes in the current figure.
31
-
32
- .. note::
10
+ # sphinx_gallery_thumbnail_number = 4
11
+ import matplotlib .pyplot as plt
12
+ import numpy as np
33
13
34
- Pyplot's state-machine environment behaves similarly to MATLAB and
35
- should be most familiar to users with MATLAB experience.
14
+ ##############################################################################
15
+ #
16
+ # A simple example
17
+ # ================
18
+ #
19
+ # Matplotlib graphs your data on `~.figure.Figure`\s (i.e., windows, Jupyter
20
+ # widgets, etc.), each of which can contain one or more `~.axes.Axes` (i.e., an
21
+ # area where points can be specified in terms of x-y coordinates (or theta-r
22
+ # in a polar plot, or x-y-z in a 3D plot, etc.). The most simple way of
23
+ # creating a figure with an axes is using `.pyplot.subplots`. We can then use
24
+ # `.Axes.plot` to draw some data on the axes:
36
25
37
- The next level down in the hierarchy is the first level of the object-oriented
38
- interface, in which pyplot is used only for a few functions such as figure
39
- creation, and the user explicitly creates and keeps track of the figure
40
- and axes objects. At this level, the user uses pyplot to create figures,
41
- and through those figures, one or more axes objects can be created. These
42
- axes objects are then used for most plotting actions.
26
+ fig , ax = plt .subplots () # Create a figure containing a single axes.
27
+ ax .plot ([1 , 2 , 3 , 4 ], [1 , 4 , 2 , 3 ]) # Plot some data on the axes.
43
28
44
- For even more control -- which is essential for things like embedding
45
- matplotlib plots in GUI applications -- the pyplot level may be dropped
46
- completely, leaving a purely object-oriented approach.
47
- """
29
+ ###############################################################################
30
+ # Many other plotting libraries or languages do not require you to explicitly
31
+ # create an axes. For example, in MATLAB, one can just do
32
+ #
33
+ # .. code-block:: matlab
34
+ #
35
+ # plot([1, 2, 3, 4], [1, 4, 2, 3]) % MATLAB plot.
36
+ #
37
+ # and get the desired graph.
38
+ #
39
+ # In fact, you can do the same in Matplotlib: for each `~.axes.Axes` graphing
40
+ # method, there is a corresponding function in the :mod:`matplotlib.pyplot`
41
+ # module that performs that plot on the "current" axes, creating that axes (and
42
+ # its parent figure) if they don't exist yet. So the previous example can be
43
+ # written more shortly as
48
44
49
- # sphinx_gallery_thumbnail_number = 3
50
- import matplotlib .pyplot as plt
51
- import numpy as np
45
+ plt .plot ([1 , 2 , 3 , 4 ], [1 , 4 , 2 , 3 ]) # Matplotlib plot.
52
46
53
47
###############################################################################
54
48
# .. _figure_parts:
55
49
#
56
50
# Parts of a Figure
57
51
# =================
58
52
#
59
- # .. image:: ../../_static/anatomy.png
53
+ # Now, let's have a deeper look at the components of a Matplotlib figure.
60
54
#
55
+ # .. image:: ../../_static/anatomy.png
61
56
#
62
57
# :class:`~matplotlib.figure.Figure`
63
58
# ----------------------------------
67
62
# 'special' artists (titles, figure legends, etc), and the **canvas**.
68
63
# (Don't worry too much about the canvas, it is crucial as it is the
69
64
# object that actually does the drawing to get you your plot, but as the
70
- # user it is more-or-less invisible to you). A figure can have any
71
- # number of :class:`~matplotlib.axes.Axes`, but to be useful should have
65
+ # user it is more-or-less invisible to you). A figure can contain any
66
+ # number of :class:`~matplotlib.axes.Axes`, but will typically have
72
67
# at least one.
73
68
#
74
69
# The easiest way to create a new figure is with pyplot:
75
70
76
- fig = plt .figure () # an empty figure with no axes
77
- fig .suptitle ('No axes on this figure' ) # Add a title so we know which it is
78
-
79
- fig , ax_lst = plt .subplots (2 , 2 ) # a figure with a 2x2 grid of Axes
71
+ fig = plt .figure () # an empty figure with no Axes
72
+ fig , ax = plt .subplots () # a figure with a single Axes
73
+ fig , axs = plt .subplots (2 , 2 ) # a figure with a 2x2 grid of Axes
80
74
75
+ # It's convenient to create the axes together with the figure, but you can
76
+ # also add axes later on, allowing for more complex axes layouts.
81
77
82
78
###############################################################################
83
79
# :class:`~matplotlib.axes.Axes`
141
137
#
142
138
# and to convert a `np.matrix` ::
143
139
#
144
- # b = np.matrix([[1,2],[3,4]])
140
+ # b = np.matrix([[1, 2], [3, 4]])
145
141
# b_asarray = np.asarray(b)
146
142
#
147
- # .. _pylab:
143
+ # .. _coding_styles:
144
+ #
145
+ # The object-oriented interface and the pyplot interface
146
+ # ======================================================
148
147
#
149
- # Matplotlib, pyplot and pylab: how are they related?
150
- # ====================================================
148
+ # As noted above, there are essentially two ways to use Matplotlib:
151
149
#
152
- # Matplotlib is the whole package and :mod:`matplotlib.pyplot` is a module in
153
- # Matplotlib.
150
+ # - Explicitly create figures and axes, and call methods on them (the
151
+ # "object-oriented (OO) style").
152
+ # - Rely on pyplot to automatically create and manage the figures and axes, and
153
+ # use pyplot functions for plotting.
154
154
#
155
- # For functions in the pyplot module, there is always a "current" figure and
156
- # axes (which is created automatically on request). For example, in the
157
- # following example, the first call to ``plt.plot`` creates the axes, then
158
- # subsequent calls to ``plt.plot`` add additional lines on the same axes, and
159
- # ``plt.xlabel``, ``plt.ylabel``, ``plt.title`` and ``plt.legend`` set the
160
- # axes labels and title and add a legend.
155
+ # So one can do (OO-style)
161
156
162
157
x = np .linspace (0 , 2 , 100 )
163
158
164
- plt .plot (x , x , label = 'linear' )
165
- plt .plot (x , x ** 2 , label = 'quadratic' )
166
- plt .plot (x , x ** 3 , label = 'cubic' )
159
+ # Note that even in the OO-style, we use `.pyplot.figure` to create the figure.
160
+ fig , ax = plt .subplots () # Create a figure and an axes.
161
+ ax .plot (x , x , label = 'linear' ) # Plot some data on the axes.
162
+ ax .plot (x , x ** 2 , label = 'quadratic' ) # Plot more data on the axes...
163
+ ax .plot (x , x ** 3 , label = 'cubic' ) # ... and some more.
164
+ ax .set_xlabel ('x label' ) # Add an x-label to the axes.
165
+ ax .set_ylabel ('y label' ) # Add a y-label to the axes.
166
+ ax .set_title ("Simple Plot" ) # Add a title to the axes.
167
+ ax .legend () # Add a legend.
168
+
169
+ ###############################################################################
170
+ # or (pyplot-style)
167
171
172
+ x = np .linspace (0 , 2 , 100 )
173
+
174
+ plt .plot (x , x , label = 'linear' ) # Plot some data on the (implicit) axes.
175
+ plt .plot (x , x ** 2 , label = 'quadratic' ) # etc.
176
+ plt .plot (x , x ** 3 , label = 'cubic' )
168
177
plt .xlabel ('x label' )
169
178
plt .ylabel ('y label' )
170
-
171
179
plt .title ("Simple Plot" )
172
-
173
180
plt .legend ()
174
181
175
- plt .show ()
176
-
177
182
###############################################################################
178
- # :mod:`pylab` is a convenience module that bulk imports
179
- # :mod:`matplotlib.pyplot` (for plotting) and :mod:`numpy`
180
- # (for mathematics and working with arrays) in a single namespace.
181
- # pylab is deprecated and its use is strongly discouraged because
182
- # of namespace pollution. Use pyplot instead.
183
- #
184
- # For non-interactive plotting it is suggested
185
- # to use pyplot to create the figures and then the OO interface for
186
- # plotting.
187
- #
188
- # .. _coding_styles:
189
- #
190
- # Coding Styles
191
- # ==================
192
- #
193
- # When viewing this documentation and examples, you will find different
194
- # coding styles and usage patterns. These styles are perfectly valid
195
- # and have their pros and cons. Just about all of the examples can be
196
- # converted into another style and achieve the same results.
197
- # The only caveat is to avoid mixing the coding styles for your own code.
183
+ # Actually there is a third approach, for the case where you are embedding
184
+ # Matplotlib in a GUI application, which completely drops pyplot, even for
185
+ # figure creation. We won't discuss it here; see the corresponding section in
186
+ # the gallery for more info (:ref:`user_interfaces`).
187
+ #
188
+ # Matplotlib's documentation and examples use both the OO and the pyplot
189
+ # approaches (which are equally powerful), and you should feel free to use
190
+ # either (however, it is preferrable pick one of them and stick to it, instead
191
+ # of mixing them). In general, we suggest to restrict pyplot to interactive
192
+ # plotting (e.g., in a Jupyter notebook), and to prefer the OO-style for
193
+ # non-interactive plotting (in functions and scripts that are intended to be
194
+ # reused as part of a larger project).
198
195
#
199
196
# .. note::
200
- # Developers for matplotlib have to follow a specific style and guidelines.
201
- # See :ref:`developers-guide-index`.
202
197
#
203
- # Of the different styles, there are two that are officially supported.
204
- # Therefore, these are the preferred ways to use matplotlib.
198
+ # In older examples, you may find examples that instead used the so-called
199
+ # :mod:`pylab` interface, via ``from pylab import *``. This star-import
200
+ # imports everything both from pyplot and from :mod:`numpy`, so that one
201
+ # could do ::
205
202
#
206
- # For the pyplot style, the imports at the top of your
207
- # scripts will typically be::
208
- #
209
- # import matplotlib.pyplot as plt
210
- # import numpy as np
211
- #
212
- # Then one calls, for example, np.arange, np.zeros, np.pi, plt.figure,
213
- # plt.plot, plt.show, etc. Use the pyplot interface
214
- # for creating figures, and then use the object methods for the rest:
215
-
216
- x = np .arange (0 , 10 , 0.2 )
217
- y = np .sin (x )
218
- fig , ax = plt .subplots ()
219
- ax .plot (x , y )
220
- plt .show ()
221
-
222
- ###############################################################################
223
- # So, why all the extra typing instead of the MATLAB-style (which relies
224
- # on global state and a flat namespace)? For very simple things like
225
- # this example, the only advantage is academic: the wordier styles are
226
- # more explicit, more clear as to where things come from and what is
227
- # going on. For more complicated applications, this explicitness and
228
- # clarity becomes increasingly valuable, and the richer and more
229
- # complete object-oriented interface will likely make the program easier
230
- # to write and maintain.
203
+ # x = linspace(0, 2, 100)
204
+ # plot(x, x, label='linear')
205
+ # ...
231
206
#
207
+ # for an even more MATLAB-like style. This approach is strongly discouraged
208
+ # nowadays and deprecated; it is only mentioned here because you may still
209
+ # encounter it in the wild.
232
210
#
233
211
# Typically one finds oneself making the same plots over and over
234
212
# again, but with different data sets, which leads to needing to write
@@ -262,6 +240,7 @@ def my_plotter(ax, data1, data2, param_dict):
262
240
out = ax .plot (data1 , data2 , ** param_dict )
263
241
return out
264
242
243
+ ###############################################################################
265
244
# which you would then use as:
266
245
267
246
data1 , data2 , data3 , data4 = np .random .randn (4 , 100 )
@@ -270,12 +249,13 @@ def my_plotter(ax, data1, data2, param_dict):
270
249
271
250
###############################################################################
272
251
# or if you wanted to have 2 sub-plots:
252
+
273
253
fig , (ax1 , ax2 ) = plt .subplots (1 , 2 )
274
254
my_plotter (ax1 , data1 , data2 , {'marker' : 'x' })
275
255
my_plotter (ax2 , data3 , data4 , {'marker' : 'o' })
276
256
277
257
###############################################################################
278
- # Again, for these simple examples this style seems like overkill, however
258
+ # For these simple examples this style seems like overkill, however
279
259
# once the graphs get slightly more complex it pays off.
280
260
#
281
261
#
0 commit comments