plt.subplots() 和 plt.figure() 的区别

Ved*_*aha 9 matplotlib python-2.7

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

 1. 

plt.figure(1,figsize=(400,8))
Run Code Online (Sandbox Code Playgroud)

 2. 

fig,ax = plt.subplots()
fig.set_size_inches(400,8)
Run Code Online (Sandbox Code Playgroud)

两者都有不同的方式来做同样的事情。例如定义轴标签。

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

ted*_*511 3

尽管@tacaswell 已经对关键区别进行了简短的评论。我将仅根据我自己的经验对这个问题添加更多内容matplotlib

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

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)
Run Code Online (Sandbox Code Playgroud)

在 的情况下plt.subplots(nrows=, ncols=),您将得到一个( )Figure数组。它主要用于同时生成许多子图。一些示例代码:AxesAxesSubplot

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)
Run Code Online (Sandbox Code Playgroud)

概括:

  • plt.figure()通常当您想要对轴进行更多自定义时使用,例如位置、大小、颜色等。您可以查看艺术家教程以了解更多详细信息。(我个人更喜欢这个对于个人情节)。

  • plt.subplots()建议在网格中生成多个子图。您还可以使用“gridspec”和“subplots”获得更高的灵活性,请参阅此处的详细信息。