在Matplotlib中使用fig.add_subplot的语法介绍

72 阅读1分钟

你可以使用以下基本语法在Matplotlib中创建子图:

import matplotlib.pyplot as plt

#define figure
fig = plt.figure()

#add first subplot in layout that has 3 rows and 2 columns
fig.add_subplot(321)

#add fifth subplot in layout that has 3 rows and 2 columns
fig.add_subplot(325)

...

下面的例子展示了如何在实践中使用这种语法。

例子1:用偶数布局添加子图

下面的代码显示了如何在一个3行2列的布局中创建6个子图:

import matplotlib.pyplot as plt

#define figure
fig = plt.figure()

#add subplots
fig.add_subplot(321).set_title('321')
fig.add_subplot(322).set_title('322')
fig.add_subplot(323).set_title('323')
fig.add_subplot(324).set_title('324')
fig.add_subplot(325).set_title('325')
fig.add_subplot(326).set_title('326')

#display plots
plt.show()

fig.add_subplot in Matplotlib

注意,结果是在一个3行2列的布局中显示6个子图。

例2:在不均匀的布局中添加子图

下面的代码显示了如何以如下方式创建四个子图:

  • 其中三个情节是在一个有3行2列的网格中创建的。
  • 第四幅图是在一个1行2列的网格中创建的。
import matplotlib.pyplot as plt

#define figure
fig = plt.figure()

#add subplots
fig.add_subplot(321).set_title('321')
fig.add_subplot(323).set_title('323')
fig.add_subplot(325).set_title('325')
fig.add_subplot(122).set_title('122')

#display plots
plt.show()

最终结果是三个子图显示在3×2网格中,而最后一个子图显示在1×2网格中。

其他资源

下面的教程解释了如何在Matplotlib中执行其他常见的操作:

如何调整Matplotlib子图之间的间距
如何调整Matplotlib中子图的大小
如何在Matplotlib中给子图添加标题