Python矩阵作图库matplotlib的初级使用
- matplotlib背景介绍:
第三方库matplotlib(没有的话,可在终端输入"pip install matplotlib"进行安装)是一款高质量的2D作图库,可被广泛地应用于支持Python的环境中。并且,如果在某些情境下需要绘制一些基础的3D图,这个时候可以结合标准库mpl_toolkits.mplot3d来使用。出于Python语言的便携性,从而为我们提供了一套轻量级的作图方案。
由于网络上的资料大多不太符合官方推荐的作图方式,且很多内容并没有一个清晰的逻辑。笔者此处重新整理几个简单的示例,仅供参考!
-
简单作图示例:
1 import numpy 2 import matplotlib.pyplot as plt 3 4 x = numpy.linspace(0, 2, 100) 5 6 plt.figure(figsize=(8, 4)) 7 8 plt.plot(x, x, label='linear') 9 plt.plot(x, x**2, label='quadratic') 10 plt.plot(x, x**3, label='cubic') 11 12 # 设置展示区间 13 plt.xlim(-1, 3) 14 plt.ylim(-1, 10) 15 16 # 设置展示信息 17 plt.xlabel('$x$') 18 plt.ylabel('$y$') 19 plt.title('simple_plot') 20 plt.legend(loc='best') 21 22 # 保存图片 23 plt.savefig(fname='test_plot.png', dpi=500) 24 25 # 展示图片 26 plt.show() 27 # 关闭图片 28 plt.close()
明确三层作图对象:
1. 整个图片对象 $ ightarrow$ figure
2. 图片内的子图对象 $ ightarrow$ axes
3. 子图内的轴对象 $ ightarrow$ axis
1 import numpy 2 import matplotlib.pyplot as plt 3 4 # 明确三层作图对象: figure, axes, axis 5 # 整个图片对象, 图片内的子图对象, 子图内的轴对象 6 7 x = numpy.linspace(0, 2, 100) 8 y = 1 + numpy.sin(2 * numpy.pi * x) 9 10 # 创建图片对象 11 fig = plt.figure(figsize=(8, 4)) 12 fig.suptitle('figure_title') 13 14 # 创建子图对象 15 axes = plt.subplot() 16 axes.plot(x, y, label='$sin(x)$') 17 axes.set(xlim=(-1, 3), ylim=(-1, 10), xlabel='$x$', ylabel='$y$', title='axes_title') 18 axes.grid() 19 axes.legend() 20 21 # fig.tight_layout() 22 fig.savefig('test_plot.png', dpi=500) 23 24 plt.show() 25 plt.close()