【问题标题】:What's the point of "plt.figure"?“plt.figure”有什么意义?
【发布时间】:2018-02-15 21:59:41
【问题描述】:
import numpy as np
import matplotlib.pyplot as plt

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)

plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')

plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

根据官方 Matplotlib 文档(https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figure) 一个图形函数将

"如果提供了num,并且已经存在该id的figure,则make 活动,并返回对它的引用。 "

我尝试在没有 plt.figure 的 Ipython 上执行上述操作,但它仍然显示了两张所需的图片。

【问题讨论】:

    标签: python python-3.x matplotlib


    【解决方案1】:

    plt.figure 有用的三种情况:

    1. 获取图形的句柄。 在许多情况下,拥有图形的句柄是很有用的,即存储matplotlib.figure.Figure 实例的变量,以便以后使用在。示例:

      fig = plt.figure()
      #... other code
      fig.autofmt_xdate()
      
    2. 设置图形参数。为图形设置一些参数的选项是将它们作为参数提供给plt.figure,例如

      plt.figure(figsize=(10,7), dpi=144) 
      
    3. 创建多个图形。 为了在同一个脚本中创建多个图形,可以使用plt.figure。示例:

      plt.figure()      # create a figure
      plt.plot([1,2,3])
      plt.figure()      # create another figure
      plt.plot([4,5,6]) # successive commands are plotted to the new figure
      

    在许多其他情况下,实际上不需要使用plt.figure。使用 pyplot 接口,调用任何绘图命令就足以创建图形,并且您始终可以使用 plt.gcf() 获取当前图形的句柄。

    从另一个角度来看,通常不仅需要图形的句柄,还需要绘制坐标轴。在这种情况下,使用plt.subplots 更有利,fig, ax = plt.subplots()。

    【讨论】:

    • 好的,我创建了一个图(或者说,几个图)。现在,我如何参考或选择一个特定的图形来显示我的情节/图像?有没有。?或者,所有这些都只是按顺序发生,你需要记住这一点吗?
    【解决方案2】:

    plt.figure 为您提供一个新图形,并根据给定的参数打开一个新图形或不打开一个新图形。比较:

    plt.figure(1)
    plt.plot(x1, y1)
    plt.plot(x2, y2)
    

    到

    plt.figure(1)
    plt.plot(x1, y1)
    plt.figure(2)
    plt.plot(x2, y2)
    

    到

    plt.figure(1)
    plt.plot(x1, y1)
    plt.figure(1)
    plt.plot(x2, y2)
    

    您将看到第一个示例等于第三个示例,因为您在第三个示例中使用第二个 plt.figure(1) 调用检索了相同的图形句柄。

    【讨论】:

      猜你喜欢
      • 2011-09-26
      • 2010-11-29
      • 2010-10-15
      • 2011-02-05
      • 2012-02-28
      • 2018-01-13
      • 2015-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多