循环中子图的大小:Python

Size of subplots in loop: Python

我有一个循环以 (nx3) 模式生成不同数量的子图,其中 n 相对于子图的数量增加。我想修复每个子图的大小(所有子图的大小都相等),以确保它们输出得很好。

我的代码是一个更大脚本的一部分,但这是子图循环:

for i in range(len(iters)):                                             # range(amount of iterations)
            iter = int(iters[i])

            plt.subplot(n, 3, i+1)
            # plotting and scaling accordingly to iteration:
            scaleFactor = frac**(len(iters)-i-1)
            plt.plot(points[0, :iter]/scaleFactor, points[1, :iter]/scaleFactor, 'b-', linewidth=1)
            plt.xlim([0, 1])
            plt.ylim([-0.25, 0.525])
            plt.title('Iteration %i' %i)
            plt.xlabel('x')
            plt.ylabel('y')
     
      plt.show()

您以前尝试过 gridspec 包吗?它可以很好地控制子图的大小和间距。您首先定义网格对象 (gs),然后在调用 add_subplot.

时选择要使用的网格部分
from matplotlib import gridspec

iters = 'abcdefghijklmnop' ### left image in example output

### right image in example output
# iters = 'abcdefghijklmnopqrstuvwxyz' 

rows = int(len(iters)/3)+1
fig = plt.figure(figsize=(6, 1.2*rows))
gs = gridspec.GridSpec(rows, 3, wspace=0.25, hspace=0.45)

for i in range(len(iters)):
    ax = fig.add_subplot(gs[i])
    ax.plot([1,2], [2,1])
plt.show()