API 参考#
使用该库时,您通常会创建 Figure和Axes对象并调用它们的方法来添加内容和修改外观。
matplotlib.figure:轴创建,图形级内容matplotlib.axes:大多数绘图方法、轴标签、访问轴样式等。
示例:我们创建一个 Figurefig和 Axes ax。然后我们调用它们的方法来绘制数据,添加轴标签和图形标题。
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 4, 0.05)
y = np.sin(x*np.pi)
fig, ax = plt.subplots(figsize=(3,2), constrained_layout=True)
ax.plot(x, y)
ax.set_xlabel('t [s]')
ax.set_ylabel('S [V]')
ax.set_title('Sine wave')
fig.set_facecolor('lightsteelblue')
使用模式#
下面我们描述了几种使用 Matplotlib 绘图的常用方法。请参阅 Matplotlib 应用程序接口 (API),了解支持的用户 API 之间的权衡。
显式 API #
Matplotlib 的核心是一个面向对象的库。如果您需要对绘图进行更多控制和自定义,我们建议您直接使用对象。
在许多情况下,您将创建一个Figure和一个或多个
Axes使用pyplot.subplots,从那时起只对这些对象工作。但是,也可以Figure显式创建 s(例如,在 GUI 应用程序中包含它们时)。
进一步阅读:
大多数示例使用面向对象的方法(pyplot 部分除外)
隐式 API #
matplotlib.pyplot是使 Matplotlib 像 MATLAB 一样工作的函数集合。每个 pyplot 函数都会对图形进行一些更改:例如,创建图形,在图形中创建绘图区域,在绘图区域中绘制一些线条,用标签装饰绘图等。
pyplot主要用于交互式绘图和程序化绘图生成的简单案例。
进一步阅读:
pylab API(不鼓励)#
警告
由于大量导入全局命名空间可能会导致意外行为,因此强烈建议不要使用 pylab。改为使用matplotlib.pyplot
。
pylab是一个包含matplotlib.pyplot, numpy, numpy.fft,
numpy.linalg,numpy.random和一些附加功能的模块,所有这些都在一个命名空间中。它最初的目的是通过将所有函数导入全局命名空间来模仿类似 MATLAB 的工作方式。这在当今被认为是不好的风格。
模块#
按字母顺序排列的模块列表:
matplotlibmatplotlib.afmmatplotlib.animationmatplotlib.artistmatplotlib.axesmatplotlib.axismatplotlib.backend_basesmatplotlib.backend_managersmatplotlib.backend_toolsmatplotlib.backendsmatplotlib.beziermatplotlib.blocking_inputmatplotlib.categorymatplotlib.cbookmatplotlib.cmmatplotlib.collectionsmatplotlib.colorbarmatplotlib.colorsmatplotlib.containermatplotlib.contourmatplotlib.datesmatplotlib.docstringmatplotlib.dvireadmatplotlib.figurematplotlib.font_managermatplotlib.fontconfig_patternmatplotlib.ft2fontmatplotlib.gridspecmatplotlib.hatchmatplotlib.imagematplotlib.layout_enginematplotlib.legendmatplotlib.legend_handlermatplotlib.linesmatplotlib.markersmatplotlib.mathtextmatplotlib.mlabmatplotlib.offsetboxmatplotlib.patchesmatplotlib.pathmatplotlib.patheffectsmatplotlib.pyplotmatplotlib.projectionsmatplotlib.quivermatplotlib.rcsetupmatplotlib.sankeymatplotlib.scalematplotlib.sphinxext.mathmplmatplotlib.sphinxext.plot_directivematplotlib.spinesmatplotlib.stylematplotlib.tablematplotlib.testingmatplotlib.textmatplotlib.texmanagermatplotlib.textpathmatplotlib.tickermatplotlib.tight_bboxmatplotlib.tight_layoutmatplotlib.transformsmatplotlib.trimatplotlib.type1fontmatplotlib.unitsmatplotlib.widgetsmatplotlib._apimatplotlib._enumsmpl_toolkits.mplot3dmpl_toolkits.axes_grid1mpl_toolkits.axisartist