首先导入 Matplotlib 库,为了后续更方便的操作,对 Matplotlib 中的 pyplot 模块进行了单独的导入,并且用简称来作为命名:
- import matplotlib as mpl
- import matplotlib.pyplot as plt
- plt.style.use('classic')
- %matplotlib inline
- import numpy as np
- x = np.linspace(0, 10, 100)
- fig = plt.figure()
- plt.plot(x, np.sin(x), '-')
- plt.plot(x, np.cos(x), '--');
通过 savefig 函数,我们可以将生成的图片保存在本地的文件目录中:
- fig.savefig('my_figure.png')
- !ls -lh my_figure.png
另外,通过 IPython.display 库中的 Image 模块,可以在 notebook 中对保存在本地的图像进行查看:
- from IPython.display import Image
- Image('my_figure.png')
- fig.canvas.get_supported_filetypes()
有时候,我们可能需要在同一张图表中显示多个相互独立的坐标系,这时候我们就可以用到 Matplotlib 中的 subplot 函数:
- plt.figure() # 创建绘图区域
- # 创建第一个图表分区,并设置当前图表的位置
- plt.subplot(2, 1, 1) # (行, 列, 分区序号)
- plt.plot(x, np.sin(x))
- # 创建第二个图表分区,并设置当前图表的位置
- plt.subplot(2, 1, 2)
- plt.plot(x, np.cos(x));
同时我们还有另外一种方式能够实现绘图区域的分区:
- # 首先创建绘图区域
- # ax 是用于表示图表位置顺序的数组
- fig, ax = plt.subplots(2)
- # 分别于对应的位置调用 plot() 函数
- ax[0].plot(x, np.sin(x))
- ax[1].plot(x, np.cos(x));
以上内容转自 数析学院,感兴趣的同学可以直接访问查看更多学习资料