【问题标题】:Python - matplotlib - differences between subplot() and subplots()Python - matplotlib - subplot() 和 subplots() 之间的区别
【发布时间】:2019-02-12 08:22:45
【问题描述】:

我在编码方面有点新手,因此在 python 中这可能听起来很愚蠢,但是 python 中 matplotlib 的 .subplot() 和 .subplots() 方法之间的主要区别是什么?

我在其他任何地方都没有找到这个解释,在阅读了 https://matplotlib.org/ 的文档后,我推断使用这两种方法,您可以创建任意数量的图形和绘图......所以对我来说,它们似乎都是完全相同的东西,它们只是处理绘图、轴等的方式不同......还是我错了?

顺便说一句,如果有什么不同,我会在 jupyter notebook 中使用 python3。

【问题讨论】:

    标签: python windows python-3.x matplotlib jupyter-notebook


    【解决方案1】:

    1。 matplotlib.pyplot.subplots()

    来自matplotlib.pyplot.subplots()上的文档页面:

    这个实用程序包装器可以方便地在一次调用中创建子图的公共布局,包括封闭的图形对象。

    这意味着您可以使用这个单一函数创建一个包含多个子图的图形,而只需一行代码。例如,下面的代码将返回 fig(图形对象)和 axes(2x3 轴对象数组,可让您轻松访问每个子图):

    fig, axes = plt.subplots(nrows=2, ncols=3)
    

    2。 matplotlib.pyplot.subplot()

    相比之下,matplotlib.pyplot.subplot() 仅在指定的网格位置创建单个子图轴。这意味着它将需要几行代码才能达到与matplot.pyplot.subplots() 在上面的一行代码中所做的相同的结果:

    # first you have to make the figure
    fig = plt.figure(1)
    
    # now you have to create each subplot individually
    ax1 = plt.subplot(231)
    ax2 = plt.subplot(232)
    ax3 = plt.subplot(233)
    ax4 = plt.subplot(234)
    ax5 = plt.subplot(235)
    ax6 = plt.subplot(236)
    

    或者你也可以使用fig的内置方法:

    ax1 = fig.add_subplot(231)
    ax2 = fig.add_subplot(232)
    ax3 = fig.add_subplot(233)
    ax4 = fig.add_subplot(234)
    ax5 = fig.add_subplot(235)
    ax6 = fig.add_subplot(236)
    

    结论

    上面的代码可以用一个循环来压缩,但使用起来仍然相当乏味。因此,我建议您使用matplotlib.pyplot.subplots(),因为它更简洁易用。

    【讨论】:

    • 这同样适用于add_subplot(),您每次都添加一个子图。例如:ax = fig.add_subplot(111) 表示只有一个网格 1x1 的图。 ax = fig.add_subplot(121) 表示 1x2 网格中的第一个子图,ax = fig.add_subplot(122) 表示 1x2 网格中的第二个子图
    • @LZYan@Bazingaa,谢谢! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    • 2021-06-10
    • 2021-01-02
    • 2016-03-26
    • 2011-03-24
    • 2014-01-03
    • 2019-05-04
    相关资源
    最近更新 更多