显式和隐式接口#
如上所述,基本上有两种使用 Matplotlib 的方法:
显式创建图形和轴,并在它们上调用方法(“面向对象 (OO) 样式”)。
依靠 pyplot 隐式创建和管理图形和轴,并使用 pyplot 函数进行绘图。
有关隐式和显式接口之间权衡的解释,请参阅Matplotlib 应用程序接口 (API)。
所以可以使用 OO 风格
x = np.linspace(0, 2, 100) # Sample data.
# Note that even in the OO-style, we use `.pyplot.figure` to create the Figure.
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
ax.plot(x, x, label='linear') # Plot some data on the axes.
ax.plot(x, x**2, label='quadratic') # Plot more data on the axes...
ax.plot(x, x**3, label='cubic') # ... and some more.
ax.set_xlabel('x label') # Add an x-label to the axes.
ax.set_ylabel('y label') # Add a y-label to the axes.
ax.set_title("Simple Plot") # Add a title to the axes.
ax.legend(); # Add a legend.
或 pyplot 风格:
x = np.linspace(0, 2, 100) # Sample data.
plt.figure(figsize=(5, 2.7), layout='constrained')
plt.plot(x, x, label='linear') # Plot some data on the (implicit) axes.
plt.plot(x, x**2, label='quadratic') # etc.
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend();
(此外,还有第三种方法,在将 Matplotlib 嵌入 GUI 应用程序的情况下,它完全放弃了 pyplot,即使是用于图形创建也是如此。有关更多信息,请参阅图库中的相应部分:
在图形用户界面中嵌入 Matplotlib。)
Matplotlib 的文档和示例同时使用 OO 和 pyplot 样式。一般来说,我们建议使用 OO 风格,特别是对于复杂的绘图,以及旨在作为更大项目的一部分重用的函数和脚本。但是,pyplot 样式可以非常方便地进行快速交互工作。
笔记
您可以通过 找到使用该pylab接口的旧示例。这种方法被强烈反对。from pylab import *