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.). 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:
3625
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.
4328
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
4844
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.
5246
5347###############################################################################
5448# .. _figure_parts:
5549#
5650# Parts of a Figure
5751# =================
5852#
59- # .. image:: ../../_static/anatomy.png
53+ # Now, let's have a deeper look at the components of a Matplotlib figure.
6054#
55+ # .. image:: ../../_static/anatomy.png
6156#
6257# :class:`~matplotlib.figure.Figure`
6358# ----------------------------------
6762# 'special' artists (titles, figure legends, etc), and the **canvas**.
6863# (Don't worry too much about the canvas, it is crucial as it is the
6964# 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
7267# at least one.
7368#
7469# The easiest way to create a new figure is with pyplot:
7570
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
8074
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.
8177
8278###############################################################################
8379# :class:`~matplotlib.axes.Axes`
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 , 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)
167171
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' )
168177plt .xlabel ('x label' )
169178plt .ylabel ('y label' )
170-
171179plt .title ("Simple Plot" )
172-
173180plt .legend ()
174181
175- plt .show ()
176-
177182###############################################################################
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).
198195#
199196# .. note::
200- # Developers for matplotlib have to follow a specific style and guidelines.
201- # See :ref:`developers-guide-index`.
202197#
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 ::
205202#
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+ # ...
231206#
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.
232210#
233211# Typically one finds oneself making the same plots over and over
234212# again, but with different data sets, which leads to needing to write
@@ -262,6 +240,7 @@ def my_plotter(ax, data1, data2, param_dict):
262240 out = ax .plot (data1 , data2 , ** param_dict )
263241 return out
264242
243+ ###############################################################################
265244# which you would then use as:
266245
267246data1 , data2 , data3 , data4 = np .random .randn (4 , 100 )
@@ -270,12 +249,13 @@ def my_plotter(ax, data1, data2, param_dict):
270249
271250###############################################################################
272251# or if you wanted to have 2 sub-plots:
252+
273253fig , (ax1 , ax2 ) = plt .subplots (1 , 2 )
274254my_plotter (ax1 , data1 , data2 , {'marker' : 'x' })
275255my_plotter (ax2 , data3 , data4 , {'marker' : 'o' })
276256
277257###############################################################################
278- # Again, for these simple examples this style seems like overkill, however
258+ # For these simple examples this style seems like overkill, however
279259# once the graphs get slightly more complex it pays off.
280260#
281261#
0 commit comments