首页 文章

为什么许多例子在Matplotlib / pyplot / python中使用“fig,ax = plt.subplots()”

提问于
浏览
163

我正在学习通过学习示例来学习 matplotlib ,并且在创建单个绘图之前,很多示例似乎包含如下所示的行...

fig, ax = plt.subplots()

这里有些例子...

我看到这个函数用了很多,尽管这个例子只是试图创建一个图表 . 还有其他一些优势吗? subplots() 的官方演示在创建单个图表时也使用了 f, ax = subplots ,之后它只引用了ax . 这是他们使用的代码 .

# Just a figure and one subplot
f, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')

2 回答

  • 208

    plt.subplots() 是一个返回包含图形和轴对象的元组的函数 . 因此,当使用 fig, ax = plt.subplots() 时,您将此元组解压缩到变量 figax 中 . 如果您想要更改图形级别属性或稍后将图形保存为图像文件(例如,使用 fig.savefig('yourfilename.png') ,那么 fig 非常有用 . 您肯定不会看到这一点 . 此外,所有轴对象(具有绘图方法的对象),无论如何都有一个父图形对象,因此:

    fig, ax = plt.subplots()
    

    比这更简洁:

    fig = plt.figure()
    ax = fig.add_subplot(111)
    
  • 27

    这里只是一个补充 .

    以下问题是如果我想在图中有更多的子图?

    如文档中所述,我们可以使用 fig = plt.subplots(nrows=2, ncols=2) 在一个图形对象中设置一组带有网格(2,2)的子图 .

    然后我们知道, fig, ax = plt.subplots() 返回一个元组,让我们首先尝试 fig, ax1, ax2, ax3, ax4 = plt.subplots(nrows=2, ncols=2) .

    ValueError: not enough values to unpack (expected 4, got 2)
    

    它引发了一个错误,但不用担心,因为我们现在看到 plt.subplots() 实际上返回了一个包含两个元素的元组 . 第一个必须是一个图形对象,另一个应该是一组子图对象 .

    那么让我们再试一次:

    fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(nrows=2, ncols=2)
    

    并检查类型:

    type(fig) #<class 'matplotlib.figure.Figure'>
    type(ax1) #<class 'matplotlib.axes._subplots.AxesSubplot'>
    

    当然,如果你使用参数(nrows = 1,ncols = 4),那么格式应该是:

    fig, [ax1, ax2, ax3, ax4] = plt.subplots(nrows=1, ncols=4)
    

    所以请记住保持列表的构造与我们在图中设置的子图网格相同 .

    希望这对你有所帮助 .

相关问题