Python的matplotlib包
2020-01-09 本文已影响0人
LiuShaodong
我们前面讲到 Python 的两个科学计算库,numpy 和 pandas,相信小伙伴们已经可以熟练使用这两个库中的常见方法。华罗庚老先生曾经说过这样一句话,“数形结合百般好,数形分离万事难”,图形是我们科学计算的重要工具。在本篇我们将结合 numpy 和 pandas 包来给小伙伴们介绍一个非常好用的画图库 matplotlib,matplotlib 非常适合进行交互式制图,承接上两篇,本篇继续采用 jupyter notebook 进行演示。
首先,导入 pandas、numpy 和 matplotlib 包,结合 pandas 的 Series
函数生成一个角标从 0 到 999 的一维数组:
In [1]: import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.Series(np.random.randn(1000),index=np.arange(1000))
data.plot()
plt.show()
Out [1]:

同样,我们也可以结合 pandas 中的 DataFrame
函数生成一个矩阵,并按照矩阵的列画出 4 条线:
In [2]: data = pd.DataFrame(np.random.randn(1000,4),index=np.arange(1000),columns=list('ABCD'))
data = data.cumsum() # 累加
data.plot()
plt.show()
Out [2]:

接下来,我们将 A 作为 x 轴,将 B 作为 y 轴,画出散点图,观察 A 与 B 是否有关系:
In [3]: data.plot.scatter(x='A',y='B',color='Red',label='Class 1')
plt.show()
Out [3]:

我们也可以用最简单的方式,画出一条折线,并修改一下线条的风格、颜色和标记:
In [4]: x = [1, 2, 3, 4]
y = [1, 2, 5, 7]
plt.plot(x, y, color="blue", linestyle="--", marker="*", linewidth=1.0)
plt.show()
Out [4]:

关于上文提到的线条的风格、颜色和标记的参照表,我们摘抄如下:
线条风格 | 实线 | 虚线 | 长虚线(上方代码中使用的) | 点划线 | 无线条(点) |
---|---|---|---|---|---|
代码 | - | : | -- | -. | None(默认) |
线条颜色 | 红色 | 黄色 | 绿色 | 蓝色(上方代码中使用的) | 黑色 | 白色 | 青色 |
---|---|---|---|---|---|---|---|
代码 | r | y | g | b | k | w | c |
线条标记 | 代码 | 线条标记 | 代码 | 线条标记 | 代码 | 线条标记 | 代码 |
---|---|---|---|---|---|---|---|
圆圈 | o(小写字母o) | 点 | . | 星号 | * | 加号 | + |
朝下三角 | v(小写字母v) | 朝上三角 | ^ | 朝左三角 | < | 朝右三角 | > |
大菱形 | D | 小菱形 | d | 正方形 | s | 五边形 | p |
为了让图更清晰易懂,我们可以再额外加上标题和标签:
In [5]: x = np.arange(4)
y1 = np.exp(x)
y2 = np.exp(x*2)
plt.plot(x, y1, color="r", linestyle="-", marker="^", linewidth=1, label="y1")
plt.plot(x, y2, color="b", linestyle="-", marker="s", linewidth=1, label="y2")
plt.title("Figure 1") # 声明标题为 Figure 1
plt.legend(loc='upper left', bbox_to_anchor=(0.1, 0.9)) # 在左上角 upper left 声明标签
plt.show()
Out [5]:

在某些情况下,我们也可以给图添加网格和背景色,更有助于参照和对比数据:
In [6]: x = np.arange(4)
y1 = np.exp(x)
y2 = np.exp(x*2)
plt.subplot(facecolor="w") # 要先定义
plt.plot(x, y1, color="r", linestyle="-", marker="^", linewidth=1, label="y1")
plt.plot(x, y2, color="b", linestyle="-", marker="s", linewidth=1, label="y2")
plt.title("Figure 1")
plt.legend(loc='upper left', bbox_to_anchor=(0.1, 0.9))
plt.grid(color="k",linestyle=":")
plt.show()
Out [6]:

我们还可以更为详细地用箭头指向某条线,做详细的注释:
In [7]: x = np.arange(4)
y1 = np.exp(x)
y2 = np.exp(x*2)
plt.subplot(facecolor="w") # 要先定义
plt.plot(x, y1, color="r", linestyle="-", marker="^", linewidth=1, label="y1")
plt.plot(x, y2, color="b", linestyle="-", marker="s", linewidth=1, label="y2")
plt.title("Figure 1")
plt.legend(loc='upper left', bbox_to_anchor=(0.1, 0.9))
plt.grid(color="k",linestyle=":")
plt.annotate('y2 = np.exp(x*2)', xy=(2, 50), xytext=(1.5, 210), arrowprops=dict(facecolor='k', headwidth=5, width=1))
plt.show()
Out [7]:

annotate
的第一个参数 'y2 = np.exp(x*2)' 是注释的文本信息,xy
表示要注释的点的坐标,xytext
表示注释文本的起始坐标,arrowprops
表示箭头,facecolor
表示箭头颜色,headwidth
表示箭头宽度,width
表示箭身宽度。