【Matplotlib】子图布局

Matplotlib进阶教程:布局讲解

自定义图形布局

可以创建axes的网格状组合的方法:

1)subplots()

用于创建图形和axes的主要函数。它类似于 matplotlib.pyplot.subplot(),但会同时创建并放置图形上的所有axes。

2)GridSpec

指定将放置子图的网格几何形状。要设置网格的行数和列数,也可调整子图的布局参数(如left、right等)。

3)SubplotSpec

在给定的 GridSpec 中指定子图的位置。

4)subplot2grid()

实例1:

gridspec 的强大之处在于能够创建跨行和列的子图。注意用于选择每个子图将占据的gridspec部分的 Numpy 切片语法。

我们也可以使用 Figure.add_gridspec方法创建不同宽度的子图:

python 复制代码
import matplotlib.pyplot as plt
 
fig3 = plt.figure(constrained_layout=True)
gs = fig3.add_gridspec(3, 3)
f3_ax1 = fig3.add_subplot(gs[0, :])
f3_ax1.set_title('gs[0, :]')
f3_ax2 = fig3.add_subplot(gs[1, :-1])
f3_ax2.set_title('gs[1, :-1]')
f3_ax3 = fig3.add_subplot(gs[1:, -1])
f3_ax3.set_title('gs[1:, -1]')
f3_ax4 = fig3.add_subplot(gs[-1, 0])
f3_ax4.set_title('gs[-1, 0]')
f3_ax5 = fig3.add_subplot(gs[-1, -2])
f3_ax5.set_title('gs[-1, -2]')
 
plt.show()

效果:

这里add_gridspec(3, 3)表示划分整个布局为3*3
gs[0,:]表示所占据的子图网格为第一行,
gs[-1,0]即最后一行,第一列
gs[1:,-1]表示第二行到最后一行,最后一列

实例2:

python 复制代码
fig = plt.figure(figsize=(12, 12), constrained_layout=True)
gs = fig.add_gridspec(8, 8)

imgs = generated_images[-1].reshape(8, 8, 28, 28)
for n_row in range(8):
    for n_col in range(8):
        f_ax = fig.add_subplot(gs[n_row, n_col])   

效果:

这里add_gridspec(8, 8)表示划分整个布局为8*8

两个for循环依次遍历行和列,则子图将整个布局填满。

相关推荐
PacosonSWJTU2 天前
python使用matplotlib画图
开发语言·python·matplotlib
Caron_xcb3 天前
大数据——解决Matplotlib 字体不足问题(Linux\mac\windows)
大数据·linux·matplotlib
迷人的小荔枝7 天前
seaborn
matplotlib
玫瑰花店9 天前
ubuntu中解决matplotlib无法显示中文问题
linux·ubuntu·matplotlib
龙虎榜小红牛系统14 天前
Python项目源码63:病历管理系统1.0(tkinter+sqlite3+matplotlib)
python·sqlite·matplotlib
eqwaak018 天前
Matplotlib高阶技术全景解析(续):动态交互、三维可视化与性能优化
开发语言·python·语言模型·性能优化·交互·matplotlib
T0uken19 天前
【Python】Matplotlib:立体永生花绘制
开发语言·python·matplotlib
captain_keating20 天前
使用matplotlib绘制Raincloud图/云雨图/柱状图/小提琴图
python·matplotlib
YiSLWLL22 天前
使用Tauri 2.3.1+Leptos 0.7.8开发桌面小程序汇总
python·rust·sqlite·matplotlib·visual studio code
满怀101524 天前
【Python进阶】数据可视化:Matplotlib从入门到实战
python·信息可视化·数据分析·matplotlib·数据可视化