讲师中心 微信公众号

工具推荐

视频效率加速
SoundView
SoundView

字幕擦除翻译、配音口型同步

Seko
Seko

AI短剧一键生成成片

剧云
剧云

中文短剧剧本制作平台

updream

一键生成高质量推广成片

手册目录

Python 教程

浏览5178
更新时间2025-08-06

显示多个图表

通过 subplot() 函数,您可以在一个图形中绘制多个图表:

实例

绘制 2 个图表:

import matplotlib.pyplot as plt
import numpy as np

# 图表 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(1, 2, 1)
plt.plot(x,y)

# 图表 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

plt.subplot(1, 2, 2)
plt.plot(x,y)

plt.show()
运行实例 »

点击 "运行实例" 按钮查看在线实例

结果:

Matplotlib 子图

subplot() 函数

subplot() 函数接受三个参数,这些参数描述了图形的布局。

布局以行和列组织,分别由第一个和第二个参数表示。

第三个参数表示当前图表的索引。

plt.subplot(1, 2, 1)
# 图形有 1 行,2 列,这个图表是第一个图表。
plt.subplot(1, 2, 2)
# 图形有 1 行,2 列,这个图表是第二个图表。

因此,如果我们想要一个具有 2 行 1 列的图形(意味着两个图表将上下显示而不是并排显示),我们可以这样写语法:

实例

上下显示 2 个图表:

import matplotlib.pyplot as plt
import numpy as np

# 图表 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(2, 1, 1)
plt.plot(x,y)

# 图表 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

plt.subplot(2, 1, 2)
plt.plot(x,y)

plt.show()
运行实例 »

点击 "运行实例" 按钮查看在线实例

结果:

Matplotlib 子图

您可以在一个图形上绘制任意数量的图表,只需描述行数、列数和图表的索引即可。

实例

Draw 6 plots:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(2, 3, 1)
plt.plot(x,y)

x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

plt.subplot(2, 3, 2)
plt.plot(x,y)

x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(2, 3, 3)
plt.plot(x,y)

x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

plt.subplot(2, 3, 4)
plt.plot(x,y)

x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(2, 3, 5)
plt.plot(x,y)

x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

plt.subplot(2, 3, 6)
plt.plot(x,y)

plt.show()
运行实例 »

点击 "运行实例" 按钮查看在线实例

结果:

Matplotlib 子图

标题

您可以使用 title() 函数为每个图表添加标题:

实例

2 plots, with titles:

import matplotlib.pyplot as plt
import numpy as np

# 图表 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(1, 2, 1)
plt.plot(x,y)
plt.title("销售")

# 图表 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.title("收入")

plt.show()
运行实例 »

点击 "运行实例" 按钮查看在线实例

结果:

Matplotlib 子图

总标题

您可以使用 suptitle() 函数为整个图形添加标题:

实例

为整个图形添加标题:

import matplotlib.pyplot as plt
import numpy as np

# 图表 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(1, 2, 1)
plt.plot(x,y)
plt.title("销售")

# 图表 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.title("收入")

plt.suptitle("我的商店")
plt.show()
运行实例 »

点击 "运行实例" 按钮查看在线实例

结果:

Matplotlib 子图
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn