Matplotlib 简明教程
Matplotlib - Object-oriented Interface
虽然可以快速使用 matplotlib.pyplot 模块生成绘图,但建议使用面向对象的方法,因为它可以更多地控制和自定义绘图。大多数函数也在 matplotlib.axes.Axes 类中提供。
While it is easy to quickly generate plots with the matplotlib.pyplot module, the use of object-oriented approach is recommended as it gives more control and customization of your plots. Most of the functions are also available in the matplotlib.axes.Axes class.
使用更正式的面向对象方法的主要思想是创建图对象,然后只需调出该对象的方法或属性。此方法有助于更好地处理其上有多个绘图的画布。
The main idea behind using the more formal object-oriented method is to create figure objects and then just call methods or attributes off of that object. This approach helps better in dealing with a canvas that has multiple plots on it.
在面向对象接口中,Pyplot 仅用于一些函数,例如图形创建,并且用户显式创建图形和轴对象并对其进行跟踪。在此级别,用户使用 Pyplot 创建图形,并且可以通过这些图形创建一或多个轴对象。然后,这些轴对象用于大多数绘图操作。
In object-oriented interface, Pyplot is used only for a few functions such as figure creation, and the user explicitly creates and keeps track of the figure and axes objects. At this level, the user uses Pyplot to create figures, and through those figures, one or more axes objects can be created. These axes objects are then used for most plotting actions.
首先,我们创建一个 figure 实例,该实例提供一个空画布。
To begin with, we create a figure instance which provides an empty canvas.
fig = plt.figure()
现在将轴添加到图形中。 add_axes() 方法需要一个包含 4 个元素的列表对象,这些元素分别对应于图形的左、下、宽和高。每个数字必须介于 0 和 1 之间−
Now add axes to figure. The add_axes() method requires a list object of 4 elements corresponding to left, bottom, width and height of the figure. Each number must be between 0 and 1 −
ax=fig.add_axes([0,0,1,1])
设置 x 和 y 轴的标签以及标题−
Set labels for x and y axis as well as title −
ax.set_title("sine wave")
ax.set_xlabel('angle')
ax.set_ylabel('sine')
调用轴对象的 plot() 方法。
Invoke the plot() method of the axes object.
ax.plot(x,y)
如果你正在使用 Jupyter notebook,则必须发出 %matplotlib inline 指令;pyplot 模块的 otherwistshow() 函数将显示绘图。
If you are using Jupyter notebook, the %matplotlib inline directive has to be issued; the otherwistshow() function of pyplot module displays the plot.
考虑执行以下代码−
Consider executing the following code −
from matplotlib import pyplot as plt
import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.plot(x,y)
ax.set_title("sine wave")
ax.set_xlabel('angle')
ax.set_ylabel('sine')
plt.show()