55
66This tutorial covers some basic usage patterns and best-practices to
77help you get started with Matplotlib.
8+ """
89
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
3313
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.). In the following example, we
23+ # create a figure using the `.pyplot.figure` function, an axes on that figure
24+ # using the `.Figure.add_subplot` method, and graph some data on that axes
25+ # using the `.Axes.plot` method:
3626
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.
27+ fig = plt .figure () # Create a figure.
28+ ax = fig .add_subplot () # Add an axes to the figure.
29+ ax .plot ([1 , 2 , 3 , 4 ], [1 , 4 , 2 , 3 ]) # Plot some data on the axes.
4330
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- """
31+ ###############################################################################
32+ # Many other plotting libraries or languages do not require you to explicitly
33+ # create an axes. For example, in MATLAB, one can just do
34+ #
35+ # .. code-block:: matlab
36+ #
37+ # plot([1, 2, 3, 4], [1, 4, 2, 3]) % MATLAB plot.
38+ #
39+ # and get the desired graph.
40+ #
41+ # In fact, you can do the same in Matplotlib: for each `~.axes.Axes` graphing
42+ # method, there is a corresponding function in the :mod:`matplotlib.pyplot`
43+ # module that performs that plot on the "current" axes, creating that axes (and
44+ # its parent figure) if they don't exist yet. So the previous example can be
45+ # written more shortly as
4846
49- # sphinx_gallery_thumbnail_number = 3
50- import matplotlib .pyplot as plt
51- import numpy as np
47+ plt .plot ([1 , 2 , 3 , 4 ], [1 , 4 , 2 , 3 ]) # Matplotlib plot.
5248
5349###############################################################################
5450# .. _figure_parts:
5551#
5652# Parts of a Figure
5753# =================
5854#
59- # .. image:: ../../_static/anatomy.png
55+ # Now, let's have a deeper look at the components of a Matplotlib figure.
6056#
57+ # .. image:: ../../_static/anatomy.png
6158#
6259# :class:`~matplotlib.figure.Figure`
6360# ----------------------------------
7875
7976fig , ax_lst = plt .subplots (2 , 2 ) # a figure with a 2x2 grid of Axes
8077
81-
8278###############################################################################
8379# :class:`~matplotlib.axes.Axes`
8480# ------------------------------
141137#
142138# and to convert a `np.matrix` ::
143139#
144- # b = np.matrix([[1,2],[3,4]])
140+ # b = np.matrix([[1, 2], [3, 4]])
145141# b_asarray = np.asarray(b)
146142#
147- # .. _pylab:
143+ # .. _coding_styles:
144+ #
145+ # The object-oriented interface and the pyplot interface
146+ # ======================================================
148147#
149- # Matplotlib, pyplot and pylab: how are they related?
150- # ====================================================
148+ # As noted above, there are essentially two ways to use Matplotlib:
151149#
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.
154154#
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)
161156
162157x = np .linspace (0 , 2 , 100 )
163158
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 = plt .figure () # Create a figure.
161+ ax = fig .add_subplot () # Add an axes to the figure.
162+ ax .plot (x , x , label = 'linear' ) # Plot some data on the axes.
163+ ax .plot (x , x ** 2 , label = 'quadratic' ) # Plot more data on the axes...
164+ ax .plot (x , x ** 3 , label = 'cubic' ) # ... and some more.
165+ ax .set_xlabel ('x label' ) # Add an x-label to the axes.
166+ ax .set_ylabel ('y label' ) # Add a y-label to the axes.
167+ ax .set_title ("Simple Plot" ) # Add a title to the axes.
168+ ax .legend () # Add a legend.
169+
170+ ###############################################################################
171+ # or (pyplot-style)
167172
173+ x = np .linspace (0 , 2 , 100 )
174+
175+ plt .plot (x , x , label = 'linear' ) # Plot some data on the (implicit) axes.
176+ plt .plot (x , x ** 2 , label = 'quadratic' ) # etc.
177+ plt .plot (x , x ** 3 , label = 'cubic' )
168178plt .xlabel ('x label' )
169179plt .ylabel ('y label' )
170-
171180plt .title ("Simple Plot" )
172-
173181plt .legend ()
174182
175- plt .show ()
176-
177183###############################################################################
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.
184+ # Actually there is a third approach, for the case where you are embedding
185+ # Matplotlib in a GUI application, which completely drops pyplot, even for
186+ # figure creation. We won't discuss it here; see the corresponding section in
187+ # the gallery for more info (:ref:`user_interfaces`).
188+ #
189+ # Matplotlib's documentation and examples use both the OO and the pyplot
190+ # approaches (which are equally powerful), and you should feel free to use
191+ # either (however, it is preferrable pick one of them and stick to it, instead
192+ # of mixing them). In general, we suggest to restrict pyplot to interactive
193+ # plotting (e.g., in a Jupyter notebook), and to prefer the OO-style for
194+ # non-interactive plotting (in functions and scripts that are intended to be
195+ # reused as part of a larger project).
198196#
199197# .. note::
200- # Developers for matplotlib have to follow a specific style and guidelines.
201- # See :ref:`developers-guide-index`.
202198#
203- # Of the different styles, there are two that are officially supported.
204- # Therefore, these are the preferred ways to use matplotlib.
199+ # In older examples, you may find examples that instead used the so-called
200+ # :mod:`pylab` interface, via ``from pylab import *``. This star-import
201+ # imports everything both from pyplot and from :mod:`numpy`, so that one
202+ # could do ::
205203#
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.
204+ # x = linspace(0, 2, 100)
205+ # plot(x, x, label='linear')
206+ # ...
231207#
208+ # for an even more MATLAB-like style. This approach is strongly discouraged
209+ # nowadays and deprecated; it is only mentioned here because you may still
210+ # encounter it in the wild.
232211#
233212# Typically one finds oneself making the same plots over and over
234213# again, but with different data sets, which leads to needing to write
@@ -262,6 +241,7 @@ def my_plotter(ax, data1, data2, param_dict):
262241 out = ax .plot (data1 , data2 , ** param_dict )
263242 return out
264243
244+ ###############################################################################
265245# which you would then use as:
266246
267247data1 , data2 , data3 , data4 = np .random .randn (4 , 100 )
@@ -270,12 +250,13 @@ def my_plotter(ax, data1, data2, param_dict):
270250
271251###############################################################################
272252# or if you wanted to have 2 sub-plots:
253+
273254fig , (ax1 , ax2 ) = plt .subplots (1 , 2 )
274255my_plotter (ax1 , data1 , data2 , {'marker' : 'x' })
275256my_plotter (ax2 , data3 , data4 , {'marker' : 'o' })
276257
277258###############################################################################
278- # Again, for these simple examples this style seems like overkill, however
259+ # For these simple examples this style seems like overkill, however
279260# once the graphs get slightly more complex it pays off.
280261#
281262#
0 commit comments