Nih*_*lum 10 python automation loops subplot
我想要在子图中生成和组织一定数量的数字,并且我想自动查找要在子图中指定的列和行的数量。到目前为止,我发现的最好方法是计算子图总数的平方根,将其四舍五入到上部整数,并自动删除空子图。但当子图数量增多时,这种方法就不是最好的了。您知道更好的方法吗?
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
Run Code Online (Sandbox Code Playgroud)
小智 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
Run Code Online (Sandbox Code Playgroud)
在这种情况下,因子 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
Run Code Online (Sandbox Code Playgroud)