Understanding plt.figure() in Python

In Python, plt.figure() is a function used to create a new figure window and it returns a Figure object.

The specific usage is as follows:

import matplotlib.pyplot as plt

# 创建一个新的图形窗口
fig = plt.figure()

# 在图形窗口中绘制图形
plt.plot([1, 2, 3, 4])

# 显示图形
plt.show()

The plt.figure() function can take several parameters to set the properties of the figure window, such as window size and background color. Some common parameters include:

  1. Number: The identifier for the graphic window, used to distinguish between different graphic windows. By default, it is set to None, indicating that a number will be assigned automatically.
  2. Figure size: the dimensions of the graph window, measured in inches, with a default setting of (6.4, 4.8).
  3. DPI: The resolution of a graphic window, measured in dots per inch, defaulting to 100.

For example, the size of the figure window can be set by using the figsize parameter.

import matplotlib.pyplot as plt

# 创建一个大小为(10, 8)的图形窗口
fig = plt.figure(figsize=(10, 8))

# 在图形窗口中绘制图形
plt.plot([1, 2, 3, 4])

# 显示图形
plt.show()

In addition to creating a new figure window, the plt.figure() function can also be used to retrieve the current figure window for further operations. For example, you can use the fig.add_subplot() method to add a subplot to the current figure window.

In summary, the function plt.figure() is used to create a new figure window and returns a Figure object that can be used to customize and manipulate the window.

bannerAds