matplotlib是Python 2D绘图库。也是python中公认的数据可视化工具。
二、绘制基础例子使用pycharm进行绘制
# 导入atplotlib.pyplot绘图包 import matplotlib.pyplot as plt # 数据分析包 import numpy as np # 创建一个包含一个axes的figure axes指的就是传统的x轴,y轴 fig, ax = plt.subplots(); # 绘制图像 ax.plot([1, 2, 3, 4], [1, 4, 2, 3]); # 展示图像 plt.show();三、Figure的组成
一个完整的matplotlib图像通常会包括以下四个层级,这些层级也被称为容器(container):
-
Figure:顶层级,用来容纳所有绘图元素
-
Axes:matplotlib宇宙的核心,容纳了大量元素用来构造一幅幅子图,一个figure可以由一个或多个子图组成
-
Axis:axes的下属层级,用于处理所有和坐标轴,网格有关的元素
-
Tick:axis的下属层级,用来处理所有和刻度有关的元素
matplotlib提供了两种最常用的绘图接口
- 显式创建figure和axes,在上面调用绘图方法,也被称为OO模式(object-oriented style)
(通过下属级axes进行调用)
# 导入atplotlib.pyplot绘图包
import matplotlib.pyplot as plt
# 数据分析包
import numpy as np
#添加代码块显示中文
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus']=False
# numpy.linspace(start, stop, num=50,
# endpoint=True, retstep=False, dtype=None, axis=0)
#start:起始位置 stop:终止位置 num:生成的样本数
#endpoint:是否包括stop位置 retstep:回显步长和样本
x = np.linspace(start=0, stop=2, num=100)
#创建figure(fig)下属元素 axes(ax)
fig, ax = plt.subplots()
#x的一次幂
ax.plot(x, x, label='linear')
#x的二次幂
ax.plot(x, x**2, label='quadratic')
#x的三次幂
ax.plot(x, x**3, label='cubic')
# 设置坐标轴的名称
ax.set_xlabel('x 轴')
ax.set_ylabel('y 轴')
#设置标题
ax.set_title("对比X的123次幂曲线")
#设置lengend
ax.legend()
plt.show()
运行结果:
numpy.linespace官方使用说明
2. 依赖pyplot自动创建figure和axes,结果与上述一致就不进行展示。(直接依赖于库方式调用方法)
x = np.linspace(0, 2, 100)
plt.plot(x, x, label='linear')
plt.plot(x, x**2, label='quadratic')
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend()
plt.show()



