matplotlib
可以完成各种绘图,使用该库首先要导入 pyplot
库。
import matplotlib.pyplot as plt
from matplotlib import pyplot as plt # 两种方法等效
代码风格
有两种风格完成图的绘制,一种是对象导向(OO)风格。这种风格适合于复杂绘图,代码可以被重用。
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
ax.plot(x, x, label='linear') # Plot some data on the axes.
ax.set_xlabel('x label') # Add an x-label to the axes.
ax.set_ylabel('y label') # Add a y-label to the axes.
ax.set_title("Simple Plot") # Add a title to the axes.
ax.legend(); # Add a legend.
还有一种是 pyplot
风格。这种风格适合于快速绘图。
plt.figure(figsize=(5, 2.7), layout='constrained')
plt.plot(x, x, label='linear') # Plot some data on the (implicit) axes.
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend();
figure
是一张画布,上面可以有各种各样的元素 axes
,比如包含轴、线等。在第一种风格中,subplots()
方法创建了一张图,画布赋值给 fig
,各种元素赋值给 ax
。第二种风格中的 plt.figure()
方法也完成了创建图的操作。其中 figsize
参数表示图片大小。
二维绘图
除了能够绘制各种图形之外,同时也可以美化显示方式。
图形
下面介绍了绘制折线图、柱形图、饼状图等常见图形的方法。
折线图
plot()
方法可以绘制折线图。该方法传入一个列表即可完成折线图绘制,认为这个列表值为 y
值,x
值从 0 开始递增。如果需要自定义 x
值,传入两个列表即可,第一个参数列表为 x
值,第二个参数列表为 y
值。
plt.plot([1, 3, 2, 4])
plt.plot([2, 3, 4, 5], [1, 3, 2, 4])
柱形图
bar()
方法用于绘制柱形图。
plt.bar([1, 2, 3], [3, 5, 2])
散点图
scatter()
方法用于绘制散点图。
x = np.random.ranf(1000)
y = np.random.ranf(1000)
plt.scatter(x, y)
饼状图
pie()
方法用于绘制饼状图。
plt.pie([2, 3, 5])
等高线图
contourf()
方法用于绘制等高线图。
x = np.linspace(-5, 5, 500)
y = np.linspace(-5, 5, 500)
X, Y = np.meshgrid(x, y)
Z = (1 - X / 2 + X ** 3 + Y ** 4) * np.exp(-X ** 2 - Y ** 2)
plt.contourf(X, Y, Z)
量场图
quiver()
方法用于绘制量场图,由向量组成的图像。
x, y = np.mgrid[0: 10, 0: 10]
plt.quiver(x, y)
样式
上文列举了绘制各种类型图形的方法,但都不够美观,可以通过设置各种参数让图形变得更加美观。
线性颜色
color
或 c
参数设置线性颜色,其输入可以是颜色的英文名或字母缩写,也可以是十六进制数。
plt.plot(x, y, color='r')
plt.plot(x, y, c='red')
plt.plot(x, y, c='#FF0000')
常见的颜色如下表。
符号 | 颜色 |
---|---|
b | 蓝色 |
g | 绿色 |
r | 红色 |
c | 蓝绿色 |
m | 品红色 |
y | 黄色 |
k | 黑色 |
w | 白色 |
线性样式
linestyle
或 ls
设置线性样式。
plt.plot(x, y, linestyle='--')
常见的线性样式如下表。
符号 | 样式 |
---|---|
- | 实线 |
-- | 虚线 |
-. | 虚电线 |
: | 点线 |
标记点
marker
设置标记点样式。
plt.plot(x, y, marker='s')
常见的标记点样式如下表。
符号 | 样式 |
---|---|
. | 点 |
, | 像素值 |
o | 圆形 |
s | 正方形 |
p | 五边形 |
h 、 H | 六边形 |
d 、 D | 菱形 |
+ | 加号形 |
x | 叉形 |
* | 星形 |
v 、^ 、< 、> | 三角形 |
1 、2 、3 、4 | 星形 |
| 、 _ | 线形 |
颜色、标记点、线
通过设定格式字符串的形式可以同时设定颜色、标记点和线的样式,将字符串作为第三个参数即可。
plt.plot(x, y, 'or--')
plt.plot(x, y, 'r--o')
这个例子设计了圆形的标记点、红色虚线。三者顺序部分先后。
透明度
alpha
参数可以设置线性的透明度,值从 0 - 1,值越小越透明。
x = [2, 3, 4, 5]
y = [3, 1, 2, 4]
plt.plot(x, y, alpha=0.8)
线宽
linewidth
或 lw
参数设置线的宽度,值要求是一个浮点数。
plt.plot(x, y, lw='3')
标题
set_title()
给图像加上标题。
plt.set_title('Figure 1')
轴标签刻度
set_xlim()
设置 x
轴的范围,ylim()
设置 y
轴的范围。
plt.set_xlim([0, 10])
set_xticks()
和 set_xticklabels()
分别完成给图像 x
轴设置刻度和标签的功能,前者是说明刻度要放在数据范围中的哪些位置,后者给这些位置打上标签。set_yticks()
和 set_yticklabels()
给 y
轴设置。
plt.set_xticks([0, 10, 20])
plt.set_xticklabels(['one', 'two', 'three'], rotation=30) # 倾斜 30°
set_xlabel()
设置 x
轴名称,set_ylabel()
设置 y
轴名称。
plt.set_xlabel('x')
plt.set_ylabel('y')
规范绘图
上文通过 plt
的方法快速绘制了各种图形,但更建议使用 OO 风格绘制图形。使用此种方法,首先要通过 figure()
方法或 subplots()
方法创建完整的图像。
fig, ax = plt.subplots()
可以为图增加图标题、轴名称、图例等。
axes.plot(x, x**2, color='red', marker='+')
axes.plot(x, x**3, linewidth=0.25, linestyle='--')
axes.set_xlabel('x') # x轴名称
axes.set_ylabel('y')
axes.set_title('title') # 图形名称
axes.legend(["y = x**2", "y = x**3"], loc=0) # 图例
loc
可取 1、2、3、4,分别表示右上角、左上角、左下角、右下角,还可取 0,表示自适应。在使用 plot
绘图时,也可以设置 label
参数作为图例。
还可以指定网格和轴范围。
axes.grid(True)
axes.set_xlim([2, 5])
axes.set_ylim([0, 60])
为了更好地理解图像,可以利用 text()
方法在图像上进行标注,前两个参数分表表示标注位置,第三个参数表示标注内容。还可以通过 fontsize
和 horizontalalignment
参数设置文字大小和对齐方式,annotate()
方法可以添加箭头。
绘制子图
subplots()
方法可以创建子图,通过 axes
下标形式选定子图。
fig, axes = plt.subplots(nrows=1, ncols=2) # 子图为 1 行,2 列
axes[0].plot(x, y)
axes[1].plot(y, x)
还可以通过使用 add_subplot()
方法来添加子图。前两个参数表示有 1×2 张子图,第三个参数表示第几张图。
fig = plt.figure()
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
subplots_adjust()
方法可以修改子图间距。
subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
图形位置
当需要自定义图形位置,使用 add_axes()
方法完成。
fig = plt.figure()
axes = fig.add_axes([0.5, 0.5, 0.8, 0.8])
axes.plot(x, y, 'r')
该方法也可以添加多个图。
fig = plt.figure()
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3])
axes1.plot(x, y, 'r')
axes2.plot(y, x, 'g')
三维绘图
三维绘图同样需要导入 pyplot
模块,此外还需要用到 mpl_toolkits.mplot3d
模块,绘图主要使用 Axes3D()
方法。
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
scatter()
方法用于绘制散点图,分别输入点的三维坐标值。plot()
方法用于绘制折线图。bar()
方法用于绘制柱状图。
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x, y, z)
fig = plt.figure()
ax = Axes3D(fig)
ax.plot(x, y, z)
plot_surface()
方法用于绘制曲面图。
fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(-2, 2, 0.1)
Y = np.arange(-2, 2, 0.1)
X, Y = np.meshgrid(X, Y)
Z = np.sqrt(X ** 2 + Y ** 2)
ax.plot_surface(X, Y, Z, cmap=plt.cm.winter)
cmap
参数表示配色方案。
除了用 Axes3D()
声明三维图形外,也可以用 projection='3d'
声明三维图形。
fig = plt.figure(figsize=(14, 6))
ax = fig.add_subplot(1, 2, 1, projection='3d')
ax.plot_surface(X, Y, Z, cmap=plt.cm.winter)
图像保存
利用 plt.savefig()
方法可以将当前图标保存到文件,该方法相当于 Figure
对象的实例化方法 savefig()
。
plt.savefig('path.png', dpi=400, bbox_inches='tight')
其中,dpi
参数控制每英寸点数分辨率,bbox_inches
可以剪除当前图标周围的空白部分)。