
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人
4.3 Matplotlib速成
Matplotlib是Python中著名的2D绘图库,使用方法比较简单,按照下面的三步进行操作就能很简单地完成绘图。
调用plot()、scatter()等方法,并为绘图填充数据。数据是NumPy的ndarray类型的对象。
设定数据标签,使用xlabel()、ylabel()方法。
展示绘图结果,使用show()方法。
4.3.1 绘制线条图
下面是一个简单的绘制线条图的例子,代码如下:
import matplotlib.pyplot as plt import numpy as np # 定义绘图的数据 myarray=np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) # 初始化绘图 plt.plot(myarray) # 设定x轴和y轴 plt.xlabel('x axis') plt.ylabel('y axis') # 绘图 plt.show()
执行结果如图4-1所示。

图4-1
4.3.2 散点图
下面是一个简单的绘制散点图的例子,代码如下:
import matplotlib.pyplot as plt import numpy as np # 定义绘图的数据 myarray1=np.array([1,2,3]) myarray2=np.array([11,21,31]) # 初始化绘图 plt.scatter(myarray1, myarray2) # 设定x轴和y轴 plt.xlabel('x axis') plt.ylabel('y axis') # 绘图 plt.show()
执行结果如图4-2所示。

图4-2
Matplotlib提供了很多种类的图表的绘制功能。在http://matplotlib.org/gallery.html提供了超过100种示例,详细情况可以参考Matplotlib API的说明。