Simple plot
Visit this page for full documentation on simple plots using pyplot.
More in-depth plot() documentation and legend() documentation.
Multiple figures and subplots
A very good and more detailed guide on subplots and figures can be found here.
import matplotlib.pyplot as plt import numpy as np # Some example data to display x = np.linspace(0, 2 * np.pi, 400) y = np.sin(x ** 2)
A single plot
subplots() without arguments return a Figure and a single Axes. When dealing with multiple plots in the same figure, the different axes will seperate the different subplots from eachother within the figure.
Stacking subplots in one direction
The first two optional arguments of pyplot.subplots() define the number of rows and columns of the subplot grid.
When stacking in one direction only, the returned axs is a 1D numpy array containing the list of created Axes.
If you are creating just a few Axes, it's handy to unpack them immediately to dedicated variables for each Axes. That way, we can use ax1 instead of the more verbose axs[0].
To obtain side-by-side subplots, pass parameters 1, 2 for one row and two columns.
Stacking subplots in two directions
When stacking in two directions, the returned axs is a 2D numpy array. If you have to set parameters for each subplot it's handy to iterate over all subplots in a 2D grid using for ax in axs.flat:.
axes.flat is not a function, it's an atribute of the numpy.ndarray. ndarray.flat is a 1-D iterator over the array. This is a numpy.flatiter instance, which acts similarly to, but is not a subclass of Python’s built-in iterator object.
Multiple figures
Creating multiple figures can be achieved in a number of ways. Below, we will demonstrate two different approaches.
To display all figures at once, only call plt.show() at the end of the last figure. As an extra practice, try moving the call or adding more, what happens, and why?
You can create multiple figures by using multiple figure() calls with an increasing figure number. Of course, each figure can contain as many axes and subplots as your heart desires:
plt.figure(1) # the first figure plt.subplot(211) # the first subplot in the first figure plt.plot([1, 2, 3]) plt.subplot(212) # the second subplot in the first figure plt.plot([4, 5, 6]) plt.figure(2) # a second figure plt.plot([4, 5, 6]) # creates a subplot(111) by default plt.figure(1) # figure 1 current; subplot(212) still current plt.subplot(211) # make subplot(211) in figure1 current plt.title('Easy as 1, 2, 3') # subplot 211 title
Quiver plot
More in-depth quiver documentation and functions.
The plot autoscaling does not take into account the arrows, so those on the boundaries may reach out of the picture. This is not an easy problem to solve in a perfectly general way. The recommended workaround is to manually set the Axes limits in such a case. An example showing autoscaling vs manually is shown below.
Contour plot
Further demos on contour plots and contour labels.