在 Matplotlib
中,面向对象编程的核心思想是创建图形对象(figure object)。通过图形对象来调用其它的方法和属性,这样有助于我们更好地处理多个画布。在这个过程中,pyplot
负责生成图形对象,并通过该对象来添加一个或多个 axes 对象(即绘图区域)。
Matplotlib
提供了matplotlib.figure
图形类模块,它包含了创建图形对象的方法。通过调用 pyplot 模块中 figure() 函数来实例化 figure 对象。
如下所示:
1
2
3
|
from matplotlib import pyplot as plt #创建图形对象 fig = plt.figure() |
该函数的参数值,如下所示:
参数 | 说明 |
---|---|
figsize | 指定画布的大小,(宽度,高度),单位为英寸。 |
dpi | 指定绘图对象的分辨率,即每英寸多少个像素,默认值为80。 |
facecolor | 背景颜色。 |
dgecolor | 边框颜色。 |
frameon | 是否显示边框。 |
下面使用 figure() 创建一个空白画布:
1
|
fig = plt.figure() |
我们使用add_axes()
将 axes
轴域添加到画布中。
如下所示:
1
|
ax = fig.add_axes([ 0 , 0 , 1 , 1 ]) |
add_axes()
的参数值是一个序列,序列中的 4 个数字分别对应图形的左侧,底部,宽度,和高度,且每个数字必须介于 0 到 1 之间。
设置 x 和 y 轴的标签以及标题,如下所示:
1
2
3
|
ax.set_title( "sine wave" ) ax.set_xlabel( 'angle' ) ax.set_ylabel( 'sine' ) |
调用 axes 对象的 plot() 方法,对 x 、 y 数组进行绘图操作:
1
|
ax.plot(x,y) |
完整的代码如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
|
from matplotlib import pyplot as plt import numpy as np import math x = np.arange( 0 , math.pi * 2 , 0.05 ) y = np.sin(x) fig = plt.figure() ax = fig.add_axes([ 0 , 0 , 1 , 1 ]) ax.plot(x,y) ax.set_title( "sine wave" ) ax.set_xlabel( 'angle' ) ax.set_ylabel( 'sine' ) plt.show() |
输出结果如下:
在 Jupyter Notebook 中运行程序,结果如下:
到此这篇关于基于Matplotlib
调用 pyplot
模块中 figure()
函数处理 figure图形对象的文章就介绍到这了,更多相关Matplotlib figure图形对象内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/ccc369639963/article/details/122980719