“plt.figure”有什么意义?

时间:2017-09-07 08:36:55

标签: python python-3.x matplotlib

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的数字,请执行此操作   active,并返回对它的引用。 “

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

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:3)

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)调用检索相同的图形句柄。