Python 2.7 plt.subplot()和plt.figure()之间的差异

Python 2.7 plt.subplot()和plt.figure()之间的差异,python-2.7,matplotlib,Python 2.7,Matplotlib,在python matplotlib中,有两种用于绘制绘图的约定: 一, 二, 两者都有做同一件事的不同方式。例如定义轴标签 哪一个更好用?一个比另一个有什么优势? 或者,使用matplotlib绘制图形的“良好实践”是什么?尽管@tacaswell已经对关键区别作了简要评论。我将根据自己使用matplotlib的经验对这个问题进行补充 plt.figure只创建一个figure(但其中没有轴),这意味着您必须指定ax来放置数据(线、散点、图像)。最低代码应如下所示: import numpy

在python matplotlib中,有两种用于绘制绘图的约定:

一,

二,

两者都有做同一件事的不同方式。例如定义轴标签

哪一个更好用?一个比另一个有什么优势?
或者,使用matplotlib绘制图形的“良好实践”是什么?

尽管@tacaswell已经对关键区别作了简要评论。我将根据自己使用
matplotlib
的经验对这个问题进行补充


plt.figure
只创建一个
figure
(但其中没有
轴),这意味着您必须指定ax来放置数据(线、散点、图像)。最低代码应如下所示:

import numpy as np
import matplotlib.pyplot as plt

# create a figure
fig = plt.figure(figsize=(7.2, 7.2))
# generate ax1
ax1 = fig.add_axes([0.1, 0.1, 0.5, 0.5])
# generate ax2, make it red to distinguish
ax2 = fig.add_axes([0.6, 0.6, 0.3, 0.3], fc='red')
# add data
x = np.linspace(0, 2*np.pi, 20)
y = np.sin(x)
ax1.plot(x, y)
ax2.scatter(x, y)
plt.子图(nrows=,ncols=)
的情况下,您将得到
轴数组(
AxesSubplot
)。它主要用于同时生成多个子地块。一些示例代码:

def display_axes(axes):
    for i, ax in enumerate(axes.ravel()):
        ax.text(0.5, 0.5, s='ax{}'.format(i+1), transform=ax.transAxes)

# create figures and (2x2) axes array
fig, axes = plt.subplots(2, 2, figsize=(7.2, 7.2))
# four (2*2=4) axes
ax1, ax2, ax3, ax4 = axes.ravel()
# for illustration purpose
display_axes(axes)
总结:
  • plt.figure()
    通常在需要对轴进行更多自定义时使用,例如位置、大小、颜色等。有关详细信息,请参见。(我个人更喜欢单独的情节)

  • plt.subplot()
    建议用于在网格中生成多个子地块。您还可以使用“gridspec”和“SubPlot”实现更高的灵活性,请参阅详细信息


plt.figure
只创建一个图形(但其中没有轴)
plt.subplot
采用可选参数(例如
plt.subplot(2,2)
)在图形中创建一个轴数组。
plt.figure
采用
plt.subplot
也采用可选参数。同样值得注意的是:matplotlib绘制到(在)轴上,因此最显式的代码通常表示类似于
ax1.plot(…)
。但是
pyplot
在解释器中最有帮助,因此如果您只定义了一个图形(如第一个示例中)并调用
plt.plot(…)
,pyplot将在当前图形上生成一个轴,并打印到该图形中。
import numpy as np
import matplotlib.pyplot as plt

# create a figure
fig = plt.figure(figsize=(7.2, 7.2))
# generate ax1
ax1 = fig.add_axes([0.1, 0.1, 0.5, 0.5])
# generate ax2, make it red to distinguish
ax2 = fig.add_axes([0.6, 0.6, 0.3, 0.3], fc='red')
# add data
x = np.linspace(0, 2*np.pi, 20)
y = np.sin(x)
ax1.plot(x, y)
ax2.scatter(x, y)
def display_axes(axes):
    for i, ax in enumerate(axes.ravel()):
        ax.text(0.5, 0.5, s='ax{}'.format(i+1), transform=ax.transAxes)

# create figures and (2x2) axes array
fig, axes = plt.subplots(2, 2, figsize=(7.2, 7.2))
# four (2*2=4) axes
ax1, ax2, ax3, ax4 = axes.ravel()
# for illustration purpose
display_axes(axes)