1、知识梳理
Matplotlib是matplot库在python中的实现,是知名的数据可视化包,可以绘制动态图、动态图、交互图,广泛应用于科研论文中。Matplotlib与numpy、pandas结合,更加简洁易用。
Matplotlib与R的ggplot2类似,也是又容器组成,包括Figure,Axes、Axis和Tick:
-
Figure
:顶层级,用来容纳所有绘图元素 -
Axes
:matplotlib宇宙的核心,容纳了大量元素用来构造一幅幅子图,一个figure可以由一个或多个子图组成 -
Axis
:axes的下属层级,用于处理所有和坐标轴,网格有关的元素 -
Tick
:axis的下属层级,用来处理所有和刻度有关的元素
在matplotlib中,包括两种常见的绘图接口,
-
显式创建figure和axes,在上面调用绘图方法,也被称为OO模式(object-oriented style)
-
依赖pyplot自动创建figure和axes,并绘图
在实际使用中,第2中接口更常用一些。
2、实战练习
绘制简单图:
import numpy as np
from matplotlib.lines import Line2D
fig, ax = plt.subplots() # 创建一个包含一个axes的figure
ax.plot([1, 2, 3, 4], [1, 4, 2, 3]); # 绘制图像
plt.show()
第一种接口绘图:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.lines import Line2D
x = np.linspace(0, 2, 100)
fig, ax = plt.subplots()
ax.plot(x, x, label='linear')
ax.plot(x, x**2, label='quadratic')
ax.plot(x, x**3, label='cubic')
ax.set_xlabel('x label')
ax.set_ylabel('y label')
ax.set_title("Simple Plot")
ax.legend()
plt.show()
第二种接口绘图
import matplotlib.pyplot as plt
import numpy as np
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()