【Python】matplotlib分格显示

参考:matplotlib图形整合之多个子图一起绘制_matplotlib多子图_王小王-123的博客-CSDN博客

方式一:

python 复制代码
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

plt.figure()
# 方式一: gridspec
# rowspan:行的跨度,colspan:列的跨度
# 第一格
ax1=plt.subplot2grid((3,3),(0,0), colspan=3, rowspan=1)
ax1.plot([1,2],[1,4])
ax1.set_xlabel("xlabel")
ax1.set_ylabel("ylabel")
ax1.set_title("ax1_title")
# ax1.set_xlim(0,4)
# ax1.set_ylim(0,6)
ax1.grid()
# 第二格
ax2=plt.subplot2grid((3,3),(1,0), colspan=2, rowspan=1)
# 第三格
ax3=plt.subplot2grid((3,3),(1,2), rowspan=2)
# 第四格
ax4=plt.subplot2grid((3,3),(2,0))
# 第五格
ax4=plt.subplot2grid((3,3),(2,1))

plt.tight_layout()
plt.show()

显示结果:

方式二:

python 复制代码
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# 方式二: easy to define structure
plt.figure(num=33)
gs = gridspec.GridSpec(3,3)
x11 = plt.subplot(gs[0,:])     # gs[0, :]  从第1行(索引0)开始,占了所有列(:)
x11.set_title("gs[0, :]")
x21 = plt.subplot(gs[1,:2])    # gs[1, :2] 从第2行(索引1)开始,占了前2列(:2)
x21.set_title("gs[1,:2]")
x22 = plt.subplot(gs[1:,2])    # gs[1:, 2] 从第2行(1:)开始占了之后的所有行(2,3行),占了第3列(索引2)
x22.set_title("gs[1:,2]")
x31 = plt.subplot(gs[-1,0])    # gs[-1, 0] 该子图占了第3行(索引-1),第1列(0)
x31.set_title("gs[-1,0]")
x32 = plt.subplot(gs[-1,-2])   # gs[-1, -2] 该子图占了第3行(-1),第2列(-2)
x32.set_title("gs[-1,-2]")

plt.tight_layout()
plt.show()

显示结果

方式三:

python 复制代码
import matplotlib.pyplot as plt

fig, ((ax11,ax12,ax13),(ax21,ax22,ax23),(ax31,ax32,ax33)) = plt.subplots(3,3,sharex=True,sharey=True)
ax11.scatter([1,2],[1,4])
ax12.plot([1,2,3,4],[1,4,9,16])

plt.tight_layout()
plt.show()

显示结果:

相关推荐
IVEN_4 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang5 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮5 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling5 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮9 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽9 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers