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

10

我有一定数量的数字需要生成并组织在子图中,我希望自动找到列和行的数量以指定我的子图。目前我找到的最好方法是计算我的总子图数量的平方根,将其向上取整至整数,并自动删除空白的子图。但当子图数量增加时,这种方法并不是最好的。你知道更好的方法吗?

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
1个回答

0
对于给定数量的子图,最好不要留下任何空白子图,并且子图的网格形状相对较为方正。对于许多子图的数量,最接近的两个因数对给出了最为方正的网格形状,同时不留下任何空白子图。
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接