有两种方式。
第一种:使用subplots_adjust
方法手动调整
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2, 2) # 创建一个2x2的子图网格
# 调整子图之间的距离
plt.subplots_adjust(hspace=0.5, wspace=0.5)
# 在子图上绘制数据或图形
# axs[0, 0].plot(...)
# axs[0, 1].plot(...)
# axs[1, 0].plot(...)
# axs[1, 1].plot(...)
plt.show()
第二种:使用tight_layout
方法自动调整
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2, 2) # 创建一个2x2的子图网格
# 使用tight_layout方法调整子图布局
plt.tight_layout()
# 在子图上绘制数据或图形
# axs[0, 0].plot(...)
# axs[0, 1].plot(...)
# axs[1, 0].plot(...)
# axs[1, 1].plot(...)
plt.show()