使用 Matplotlib 中的 pyplot.figure()

本教程解释了我们如何使用 matplotlib.pyplot.fig() 来改变 Matplotlib 图的各种属性。一个 Matplotlib 图只是一个顶层的容器,它包含了一个图的所有轴和属性。要了解更多关于 Matplotlib 图的细节,可以参考官方文档页。

使用 matplotlib.pyplot.fig() 来设置图的属性

matplotlib.pyplot.figure(num=None,
                         figsize=None,
                         dpi=None,
                         facecolor=None,
                         edgecolor=None,
                         frameon=True,
                         FigureClass=<class 'matplotlib.figure.Figure'>, 
                         clear=False,
                         **kwargs)

我们可以使用 matplotlib.pyplot.figure() 来创建一个新的图形,并设置各种参数的值来定制图形,如 figsizedpi 等。

示例:使用 matplotlib.pyplot.figure() 设置图形属性

import matplotlib.pyplot as plt
x=[1,2,3,4,5,6]
y=[4,3,5,6,7,4]
plt.figure(figsize=(8,6),
           facecolor='yellow')
plt.plot(x, y)
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Plot with figsize (8,6)")
plt.show()

输出:

使用 Matplotlib 中的 pyplot.figure()

它创建了图形对象,并将人物的宽度设置为 8 英寸,高度设置为 6 英寸。人脸颜色设置为黄色。

使用 matplotlib.pyplot.fig() 像图形添加子图

matplotlib.pyplot.figure() 返回一个图形对象,这个对象可以用来使用 add_subplot() 方法向图中添加子图。

import matplotlib.pyplot as plt
x=[1,2,3,4,5,6]
y=[4,3,5,6,7,4]
fig=plt.figure()
subplot1=fig.add_subplot(2,1,1)
subplot1.plot(x, y)
subplot2=fig.add_subplot(2,1,2)
subplot2.text(0.3, 0.5, '2nd Subplot')
fig.suptitle("Add subplots to a figure")
plt.show()

输出:

使用 Matplotlib 中的 pyplot.figure()

它为使用 matplotlib.pyplot.fig() 方法创建的图对象 fig 添加了两个子图。