首页 > 解决方案 > 在 Matplotlib (Python) 中处理子图的比例

问题描述

您好我正在尝试使用 matplotlib 创建下面的子图。

子图

我有以下代码,但我似乎无法使用参数正确配置绘图。如果有任何帮助,我将不胜感激。欢迎 Python 上的任何其他绘图工具也可以帮助我以这种方式缝合 4 个绘图。

太感谢了!

gs1 = fig9.add_gridspec(nrows=8, ncols=8, top=0.6, bottom=0.1,left = 0, right = 0.65,
                        wspace=0.05, hspace=0.05)
# f9_ax1 = fig9.add_subplot(gs1[:-1, :])
ax2 = fig9.add_subplot(gs1[:1, :1])
ax3 = fig9.add_subplot(gs1[:1, 1:])

gs2 = fig9.add_gridspec(nrows=4, ncols=4, top=1.2, bottom=0.4, left = 0, right = 0.5,
                        wspace=0.05, hspace=0.05)
ax4 = fig9.add_subplot(gs1[1: , :1])
ax5 = fig9.add_subplot(gs1[1:, 1:])

上面的代码给出了这个 在此处输入图像描述

标签: pythonmatplotlibplot

解决方案


You can divide the figure for example in a 20 x 20 grid which means that one cell makes up 5% x 5% of the figure. Scaling your proportions 35/65 -> 7/13, 40/60 -> 8/12 and 50/50 -> 10/10 to this grid gives:

import matplotlib.pyplot as plt

fig = plt.figure(constrained_layout=True)
gs1 = fig.add_gridspec(nrows=20, ncols=20)
 
ax1 = fig.add_subplot(gs1[0:12, 0:7])     # top left     (size: 12x7  - 60x35)
ax2 = fig.add_subplot(gs1[0:12, 7:20])    # top right    (size: 12x13 - 60x65)
ax3 = fig.add_subplot(gs1[12:20, 0:10])   # bottom left  (size: 8x10  - 40x50)
ax4 = fig.add_subplot(gs1[12:20, 10:20])  # bottom right (size: 8x10  - 40x50)

grid spec

Note also the constrained_layout keyword, setting this to True shrinks the subplots to make all axis labels visible, this has the maybe unwanted affect of changing the aspect ratios slightly. When setting it to False the proportions are better preserved. However currently Constrained Layout is experimental and maybe changed or removed.

See also the documentation for more information.


推荐阅读