前言
上一篇讲的是单图绘制,而多个图形在同一个图像中的绘制也是常见的。
1.组合图绘制
- 绘制原理:将不同类型图形的代码放置在一起,前提是这些图形的横坐标必须共享,Matplotlib 才能自动将它们组合显示在一张图中。
- 示例代码:
x = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
y_bar = [3, 4, 6, 8, 9, 10, 9, 11, 7, 8]
y_line = [2, 3, 5, 7, 8, 9, 8, 10, 6, 7]
plt.bar(x, y_bar)
plt.plot(x, y_line, '-o', color='y')
2.图形位置定义
(1)基本概念
figure
:相当于绘画用的画板,是一个顶层容器,用于容纳所有的绘图元素。axes
:相当于铺在画板上的画布,我们在画布上进行具体的绘图操作,如plot
、set_xlabel
等。
(2)使用 fig.add_axes()
方法
- 功能:向
figure
画板中添加自定义位置和大小的画布axes
。 - 参数:
add_axes([left, bottom, width, height])
,其中left
和bottom
表示画布左下角的坐标,width
和height
表示画布的宽度和高度,取值范围是[0, 1]
。 - 示例代码:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 20) # 生成数据
y = x * x + 2
fig = plt.figure() # 新建图形对象
axes = fig.add_axes([0.5, 0.5, 0.8, 0.8]) # 控制画布的左, 下, 宽度, 高度
axes.plot(x, y, 'r')
- 大图套小图效果:通过多次调用
add_axes()
方法添加不同大小和位置的画布,实现大图套小图。
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') # 小画布
(3)使用 plt.subplots()
方法
- 功能:创建一个包含多个子图的图形,返回一个
figure
对象和一个包含多个axes
对象的数组。 - 基本用法:
fig, axes = plt.subplots()
axes.plot(x, y, 'r')
- 子图拼接:通过设置
nrows
和ncols
参数,可以将多张图按一定顺序拼接在一起。
fig, axes = plt.subplots(nrows=1, ncols=2) # 子图为 1 行,2 列
for ax in axes:
ax.plot(x, y, 'r')
- 调节画布尺寸和显示精度:通过
figsize
参数调节画布的尺寸(单位为英寸),通过dpi
参数调节显示精度(每英寸点数)。
fig, axes = plt.subplots(figsize=(16, 9), dpi=50) # 通过 figsize 调节尺寸, dpi 调节显示精度
axes.plot(x, y, 'r')