This is an English translation of the provided Chinese text. No explanations or text apart from the translation are provided.
Matplotlib Tutorial
Category Programming Techniques
Introduction
Matplotlib is perhaps the most widely used suite in the Python 2D-plotting field. It allows users to easily visualize data and offers a variety of output formats. This tutorial will explore common usages of matplotlib.
IPython and Pylab Mode
IPython is an enhanced version of Python. It has enhancements in the following areas: named input/output, use of system commands (shell commands), and debugging capabilities. After adding the argument -pylab (versions after 0.12 use --pylab) to IPython in the command line terminal, we can plot interactively like in Matlab or Mathematica.
Pylab
Pylab is an interface to the object-oriented plotting library of matplotlib. Its syntax is very similar to Matlab. That is, its main plotting commands have similar parameters to the corresponding commands in Matlab.
Download the example source code used in this article:
The download package contains two directories:
figures: Stores images generated by example code
scripts: Stores example code
Basic Plotting
In this section, we will start from simple to complex: first try to plot the sine and cosine function images on the same graph with the default configuration, and then gradually beautify it.
The first step is to obtain the values of the sine and cosine functions:
from pylab import *
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C, S = np.cos(X), np.sin(X)
X is a numpy array containing 256 evenly spaced values from −π to +π. C and S are numpy arrays of cosine and sine function values corresponding to these 256 values, respectively.
You can test the code in interactive mode in IPython, or you can download the code (the download link is these example images) and then execute:
python exercise_1.py
Using Default Configuration[Source Code File ]
Matplotlib's default configurations allow for user customization. You can adjust most of the default configurations: image size and resolution (dpi), line width, color, style, axis and grid properties, text and font properties, etc. However, the default configurations of matplotlib are usually good enough in most cases, and you may only want to change these default configurations in a few cases.
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C, S = np.cos(X), np.sin(X)
plt.plot(X, C)
plt.plot(X, S)
plt.show()
Details of Default Configuration[Source Code File ]
In the following code, we show the default configuration of matplotlib with annotated explanations, which includes all configurations related to plot styles. The configurations in the code are exactly the same as the default configurations, and you can modify the values interactively to observe the effects.
# Import everything from matplotlib (numpy can be used with the name np)
from pylab import *
# Create an 8 * 6 point (point) graph and set the resolution to 80
figure(figsize=(8,6), dpi=80)
# Create a new 1 * 1 subplot, and the following drawings are made in the first (and only) piece
subplot(1,1,1)
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C, S = np.cos(X), np.sin(X)
# Plot the cosine curve with a blue, continuous, and 1-pixel wide line
plot(X, C, color="blue", linewidth=1.0, linestyle="-")
# Plot the sine curve with a green, continuous, and 1-pixel wide line
plot(X, S, color="green", linewidth=1.0, linestyle="-")
# Set the upper and lower limits of the horizontal axis
xlim(-4.0,4.0)
# Set the horizontal axis marks
xticks(np.linspace(-4,4,9,endpoint=True))
# Set the upper and lower limits of the vertical axis
ylim(-1.0,1.0)
# Set the vertical axis marks
yticks(np.linspace(-1,1,5,endpoint=True))
# Save the image at a resolution
xytext=(-90, -50), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
...
Strive for Excellence[Source Code File ]
The label on the axis is obscured by the curve, which is intolerable for a perfectionist (just kidding). We can enlarge them and add a semi-transparent white background. This ensures that both the label and the curve are visible at the same time.
...
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(16)
label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65 ))
...
Images, Subplots, Axes, and Ticks
So far, we have been drawing images and axes in an implicit manner. This is convenient for quick drawings. We can also explicitly control the image, subplot, and axes. The 'image' in Matplotlib refers to the entire window content seen in the user interface. Inside the image, there are so-called 'subplots'. The position of the subplot is determined by the coordinate grid, while the 'axes' are not limited to this and can be placed at any position in the image. We have implicitly used images and subplots: when we call the plot function, matplotlib calls the gca() function and the gcf() function to obtain the current axes and image; if the image cannot be obtained, the figure() function is called to create one - strictly speaking, a figure with only one subplot is created using subplot(1,1,1).
Image
The so-called 'image' is the window with the title 'Figure #' in the GUI. The image number starts from 1, consistent with the style of MATLAB, which is different from the Python style that starts from 0. The following parameters are the attributes of the image:
Parameter | Default Value | Description |
---|---|---|
num | 1 | The number of images |
figsize | figure.figsize | The length and width of the image (inches) |
dpi | figure.dpi | Resolution (dots per inch) |
facecolor | figure.facecolor | The background color of the drawing area |
edgecolor | figure.edgecolor | The color of the edge of the drawing area |
frameon | True | Whether to draw the edge of the image |
These default values can be specified in the source file. However, except for the image number parameter, the other parameters are rarely modified.
You can close the window by clicking the X in the upper right corner of the graphical interface (on OS X, it's the upper left corner). Matplotlib also provides a function called close to close this window. The specific behavior of the close function depends on the parameters you provide:
No parameters passed: Close the current window;
Pass the window number or window instance as a parameter: Close the specified window;
all
: Close all windows.
Like other objects, you can use methods like setp or set_something to set the properties of the image.
Subplot
You can use subplots to place plots in a uniform coordinate grid. When using the subplot function, you need to specify the number of rows and columns of the grid, and which grid area you want to place the plot in. In addition, the gridspec function is more powerful, and you can also choose it to achieve this function.
Axes
Axes are similar to subplots, but they can be placed at any position in the image. Therefore, if you want to draw a small graph in a picture, you can use this feature.
Ticks
Good ticks are an important part of the image. The details of the tick system in Matplotlib can be customized by the user. You can use Tick Locators to specify where to place the ticks, and use Tick Formatters to adjust the style of the ticks. Major and minor ticks can be presented in
Grid [Source Code File ]
from pylab import *
axes = gca()
axes.set_xlim(0,4)
axes.set_ylim(0,3)
axes.set_xticklabels([])
axes.set_yticklabels([])
show()
Multiple Grids [Source Code File ]
from pylab import *
subplot(2,2,1)
subplot(2,2,3)
subplot(2,2,4)
show()
Polar Plot [Source Code File ]
from pylab import *
axes([0,0,1,1])
N = 20
theta = np.arange(0.0, 2*np.pi, 2*np.pi/N)
radii = 10*np.random.rand(N)
width = np.pi/4*np.random.rand(N)
bars = bar(theta, radii, width=width, bottom=0.0)
for r,bar in zip(radii, bars):
bar.set_facecolor( cm.jet(r/10.))
bar.set_alpha(0.5)
show()
3D Plot [Source Code File ]
from pylab import *
from mpl_toolkits.mplot3d import Axes3D
fig = figure()
ax = Axes3D(fig)
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot')
show()
Manuscript Plot [Source Code File ]
import numpy as np
import matplotlib.pyplot as plt
eqs = []
eqs.append((r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$"))
eqs.append((r"$\frac{d\rho}{d t} + \rho \vec{v}\cdot\nabla\vec{v} = -\nabla p + \mu\nabla^2 \vec{v} + \rho \vec{g}$"))
eqs.append((r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$"))
eqs.append((r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$"))
eqs.append((r"$F_G = G\frac{m_1m_2}{r^2}$"))
plt.axes([0.025,0.025,0.95,0.95])
for i in range(24):
index = np.random.randint(0,len(eqs))
eq = eqs[index]
size = np.random.uniform(12,32)
x,y = np.random.uniform(0,1,2)
alpha = np.random.uniform(0.25,.75)
plt.text(x, y, eq, ha='center', va='center', color="#11557c", alpha=alpha,
transform=plt.gca().transAxes, fontsize=size, clip_on=True)
plt.xticks([]), plt.yticks([])
# savefig('../figures/text_ex.png',dpi=48)
plt.show()
More References
Getting Started
[Artist tutorial](http://matplotlib.sourceforge