服务器 > 服务器 > Linux

matplotlib绘制多图技巧:subplot和subplots方法哪个更好用

104人参与 • 2026-09-29 • Linux

matplotlib 绘制多图

我们可以使用 pyplot 中的 subplot() 和 subplots() 方法来绘制多个子图。

subplot() 方法在绘图时需要指定位置,subplots() 方法可以一次生成多个,在调用时只需要调用生成对象的 ax 即可。

subplot

subplot(nrows, ncols, index, **kwargs)
subplot(pos, **kwargs)
subplot(**kwargs)
subplot(ax)

以上函数将整个绘图区域分成 nrows 行和 ncols 列,然后从左到右,从上到下的顺序对每个子区域进行编号 1...n ,左上的子区域的编号为 1、右下的区域编号为 n,编号可以通过参数 index 来设置。

设置 numrows = 1,numcols = 2,就是将图表绘制成 1x2 的图片区域,对应的坐标为:

(1, 1), (1, 2)

plotnum = 1, 表示的坐标为(1, 1), 即第一行第一列的子图。

plotnum = 2, 表示的坐标为(1, 2), 即第一行第二列的子图。

实例

import matplotlib.pyplot as plt
import numpy as np
#plot 1:
xpoints = np.array([0, 6])
ypoints = np.array([0, 100])
plt.subplot(1, 2, 1)
plt.plot(xpoints,ypoints)
plt.title("plot 1")
#plot 2:
x = np.array([1, 2, 3, 4])
y = np.array([1, 4, 9, 16])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.title("plot 2")
plt.suptitle("w3cschool subplot test")
plt.show()

显示结果如下:

设置 numrows = 2,numcols = 2,就是将图表绘制成 2x2 的图片区域, 对应的坐标为:

(1, 1), (1, 2)
(2, 1), (2, 2)

实例

import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x = np.array([0, 6])
y = np.array([0, 100])
plt.subplot(2, 2, 1)
plt.plot(x,y)
plt.title("plot 1")
#plot 2:
x = np.array([1, 2, 3, 4])
y = np.array([1, 4, 9, 16])
plt.subplot(2, 2, 2)
plt.plot(x,y)
plt.title("plot 2")
#plot 3:
x = np.array([1, 2, 3, 4])
y = np.array([3, 5, 7, 9])
plt.subplot(2, 2, 3)
plt.plot(x,y)
plt.title("plot 3")
#plot 4:
x = np.array([1, 2, 3, 4])
y = np.array([4, 5, 6, 7])
plt.subplot(2, 2, 4)
plt.plot(x,y)
plt.title("plot 4")
plt.suptitle("w3cschool subplot test")
plt.show()

显示结果如下:

subplots()

subplots() 方法语法格式如下:

matplotlib.pyplot.subplots(nrows=1, ncols=1, *, sharex=false, sharey=false, squeeze=true, subplot_kw=none, gridspec_kw=none, **fig_kw)

参数说明:

实例

import matplotlib.pyplot as plt
import numpy as np
# 创建一些测试数据 -- 图1
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
# 创建一个画像和子图 -- 图2
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('simple plot')
# 创建两个子图 -- 图3
f, (ax1, ax2) = plt.subplots(1, 2, sharey=true)
ax1.plot(x, y)
ax1.set_title('sharing y axis')
ax2.scatter(x, y)
# 创建四个子图 -- 图4
fig, axs = plt.subplots(2, 2, subplot_kw=dict(projection="polar"))
axs[0, 0].plot(x, y)
axs[1, 1].scatter(x, y)
# 共享 x 轴
plt.subplots(2, 2, sharex='col')
# 共享 y 轴
plt.subplots(2, 2, sharey='row')
# 共享 x 轴和 y 轴
plt.subplots(2, 2, sharex='all', sharey='all')
# 这个也是共享 x 轴和 y 轴
plt.subplots(2, 2, sharex=true, sharey=true)
# 创建标识为 10 的图,已经存在的则删除
fig, ax = plt.subplots(num=10, clear=true)
plt.show()

部分图表显示结果如下:

图1

图2

图3

图4

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

赞 (0)

您想发表意见!!点此发布评论

推荐阅读

Linux开机启动流程详解 init进程和运行级别怎么理解

09-29

Ubuntu软件安装与彻底卸载的完整指南

09-28

Linux如何查看jar包错误日志及持久化运行jar包

09-28

Linux查看进程用ps -ef还是ps aux?一文看懂区别

09-28

在Linux环境下为Nginx配置HTTPS的完整流程

09-28

Linux skill命令实现按用户或终端批量管理进程的实用指南

09-28

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论