首页 > 编程笔记 > Python笔记 阅读:2

Matplotlib subplots()函数用法详解(附带实例)

Matplotlib 可以实现在一张图上绘制多个子图表。Matplotlib 提供了三种方法,分别是 subplot() 函数、subplots() 函数和 add_subplot() 方法。

subplots() 函数用于创建画布和子图,语法格式如下:
matplotllib.pyplot.subplots(nrows, ncols, sharex, sharey, squeeze, subplot_kw, gridspec_kw, **fig_kw)
主要参数说明:
【实例】绘制一个 2 行 3 列包含 6 个子图的空图表,使用 subplots() 函数只需三行代码。
# 导入matplotlib模块
import matplotlib.pyplot as plt

# 绘制2行3列包含6个子图的空图表
figure, axes = plt.subplots(2, 3)
plt.show()  # 显示图表
在上述代码中,figure 和 axes 是两个关键点:
【实例】使用 subplots() 函数将前面所学的简单图表整合到一张图表上,效果如下图所示:


图 1 多子图图表

程序代码如下:
import matplotlib.pyplot as plt  # 导入matplotlib模块
figure, axes = plt.subplots(2, 2)  # 创建2行2列的图表
axes[0, 0].plot([1, 2, 3, 4, 5])  # 在第1行第1列的位置绘制折线图
axes[0, 1].plot([1, 2, 3, 4, 5], [2, 5, 8, 12, 18], 'ro')  # 在第1行第2列的位置绘制散点图
# 在第2行第1列的位置绘制柱形图
x = [1, 2, 3, 4, 5, 6]
height = [10, 20, 30, 40, 50, 60]
axes[1, 0].bar(x, height)
# 在第2行第2列的位置绘制饼形图
x = [2, 5, 12, 70, 2, 9]
axes[1, 1].pie(x, autopct='%1.1f%%')
plt.show()  # 显示图表

相关文章