【问题标题】:Size of subplots in loop: Python循环中子图的大小:Python
【发布时间】:2021-03-09 15:31:48
【问题描述】:

我有一个循环以 (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()

【问题讨论】:

    标签: python loops matplotlib size subplot


    【解决方案1】:

    您之前尝试过 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-14
      • 1970-01-01
      • 2012-05-05
      • 2020-05-30
      • 2019-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多