如何自动设置行数和列数子图

How to automatically set number of rows & columns subplots

提问人:Nihilum 提问时间:4/12/2021 最后编辑:Nihilum 更新时间:10/6/2023 访问量:787

问:

我有一定数量的图形要在子图中生成和组织,并且我想自动找到要在子图中指定的列和行的数量。到目前为止,我发现的最好的方法是计算子图总数的平方根,将其四舍五入到上面的 int,然后自动删除空子图。但是,当子图的数量增加时,这种方法并不是最好的。你知道更好的方法吗?

import numpy as np
import matplotlib.pylab as plt


percentile = np.linspace(0.1,0.9,10)
test = np.linspace(0,10,123)
nb = int(np.sqrt(len(percentile))) + 1

# the "test" variable is not important. The "percentile" dictates how many subplots I want

fig, axs = plt.subplots(nb,nb, figsize=(15, 15), facecolor='w', edgecolor='k')

count = 0
for l in range(0,nb):
    for c in range(0,nb):
            
            if count < len(percentile):            
                axs[l,c].plot(test*percentile[count])

            else:
                axs[l,c].set_visible(False)
            
            count = count + 1
Python 循环 自动化 子图

评论


答:

0赞 C L 10/6/2023 #1

对于给定数量的子图,最好不要留下任何空白的子图,并具有相对方形的子图网格。对于许多个子图,一对最接近的因子为您提供了网格的最大方形形状,而不会留下任何空白子图。

def close_factors(number):
    ''' 
    find the closest pair of factors for a given number
    '''
    factor1 = 0
    factor2 = number
    while factor1 +1 <= factor2:
        factor1 += 1
        if number % factor1 == 0:
            factor2 = number // factor1
        
    return factor1, factor2

在这种情况下,因子 1 将始终比因子 2 宽,因此程序员可以决定他们首先选择宽度还是高度。

但是,如果一个数字是质数或至少没有一组靠近的因子,这不会给出一个非常方形的子图网格。
在这种情况下,可能需要将一些子图保留为网格末尾的空白图,以换取一组更方形的子图。

def almost_factors(number):
    '''
    find a pair of factors that are close enough for a number that is close enough
    '''
    while True:
        factor1, factor2 = close_factors(number)
        if 1/2 * factor1 <= factor2: # the fraction in this line can be adjusted to change the threshold aspect ratio
            break
        number += 1
    return factor1, factor2