【问题标题】:Numbering figure windows using the subplots command in matplotlib.pyplot使用 matplotlib.pyplot 中的 subplots 命令对图形窗口进行编号
【发布时间】:2021-05-26 07:24:31
【问题描述】:

在 matplotlib.pyplot 中使用命令中的子图时,有没有办法给图形编号? 当我想在图中有一个情节时,我可以使用

import matplotlib.pyplot as plt
plt.figure(2)
plot(x,y)

这将创建图 2 并在其中绘制图。但是,使用子图时我不能这样做

plt.figure(3)
f, ax = plt.subplots(1,2)
ax[0].plot(x,y)

这基本上显示了一个新的图 3,然后是另一个图 4,其中包含子图。我想给有子图的那个编号。

提前致谢。

【问题讨论】:

    标签: python matplotlib plot subplot figure


    【解决方案1】:

    在调用plt.show() 之后,您将无法再次绘制这些数字(除非并且直到您处于某个交互式会话中(?))。所以让我们假设你没有调用 plt.show()。在这种情况下,您可以通过图(1)重新激活第一个图。

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig = plt.figure(1, figsize=(10,4))
    fig.suptitle('First figure instance')
    

    现在让我们使用下面的代码创建第二个图,

    plt.figure(2, figsize=(10,5))
    plt.subplot(1, 2, 1)
    plt.plot(np.random.rand(3,2))
    plt.subplot(1, 2, 2)
    plt.plot(np.random.rand(3,2))
    plt.suptitle('second plot')
    
    sub1 = fig.add_subplot(221)
    plt.plot(np.random.rand(3,2))
    sub2 = fig.add_subplot(224)
    plt.plot(np.random.rand(3,2))
    plt.show()
    

    【讨论】:

      【解决方案2】:

      使用子图创建的图形会自动编号。您可以通过以下方式检查:

      fig1 = plt.figure(1)
      print(fig1.number)
      # 1
      
      fig2, axes = plt.subplots(1, 2)
      print(fig2.number)
      # 2
      plt.figure(2)  # this will not create a new figure
      

      使用面向对象的方法,我看不出您为什么要设置数字编号。

      但是,如果您真的想这样做,请查看 pyplot.subplots 的文档,有 fig_kw 会传递给 pyplot.figure。在这里,文档中的第一个参数是num=,您可以在其中指定图形编号。因此,您可以在plt.subplots() 中使用此参数:

      fig, axes = plt.subplots(1, 2, num=99)
      print(fig.number)
      # 99
      

      【讨论】:

      • 感谢 DavidG,它起作用了,我没有在文档中找到关键字参数“num”。感谢您指出。但是,它并没有达到我想要做的目的。我想运行一个生成多个图的代码,其中每个图都绘制了一些独特的东西,我想可视化每个图由于参数之一的变化(2个图,一个在参数更改之后和参数更改之前)相互叠加,而不是用新数据生成新数字)。为此,Jay Patel 的方法(如下)奏效了。
      猜你喜欢
      • 1970-01-01
      • 2016-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-06
      • 2020-06-28
      相关资源
      最近更新 更多