当我知道我所需要的图的总数时,我试图弄清楚如何计算子图维,我希望这个排列是一个正方形(可能有几个空的子图)。
例如,如果我需要22个子图,那么我将为总共25个子图创建一个5x5
网格,然后只留下三个子图为空。
因此,我想我正在寻找一个算法,我输入22,得到5,例如。有人知道用python (如果可能的话,可以使用lambda函数)做这件事的捷径吗?
(也可以选择其他方法或预先制定的解决方案,我正在为熊猫数据字典做多个子图矩阵)
发布于 2017-03-29 17:16:31
这应该适用于你想要做的事。我还没有尝试使用lambda函数,但我怀疑要修改这个函数会很困难。不会有任何空图,因为算法一旦超出要绘制的值,就会停止。
我把字典分成键列表和值列表,因为我写这篇文章时最初是在处理列表。直到try子句的所有内容都会正常工作,而不会将值转换为列表。如果您想要填充空图,而不是使用hack-y break_test位,则可以将子图的所有代码放入try子句中。
奇怪的断续版本:
fig = plt.figure()
# Makes organizing the plots easier
key_list, val_list = [k, v for k, v in dict.getitems()]
# We take advantage of the fact that int conversions always round down
floor = int(np.sqrt(len(val_list))
# If the number of plots is a perfect square, we're done.
# Otherwise, we take the next highest perfect square to build our subplots
if floor ** 2 == len(val_list):
sq_chk = floor
else:
sq_chk = floor + 1
plot_count = 0
# The try/except makes sure we can gracefully stop building plots once
# we've exhausted our dictionary values.
for i in range(sq_chk):
for j in range(sq_chk):
try:
break_test = val_list[plot_count]
except:
break
ax = fig.add_subplot(sq_chk, sq_chk, plot_count + 1)
ax.set_title(key_list[plot_count])
...
# Whatever you want to do with your plots
...
plot_count += 1
plt.show()
无间断版本:
fig = plt.figure()
key_list, val_list = [k, v for k, v in dict.getitems()]
floor = int(np.sqrt(len(dict))
if floor ** 2 == len(dict):
sq_chk = floor
else:
sq_chk = floor + 1
plot_count = 0
# Everything from the original snippet should be nested in the try clause
for i in range(sq_chk):
for j in range(sq_chk):
try:
ax = fig.add_subplot(sq_chk, sq_chk, plot_count + 1)
ax.set_title(key_list[plot_count])
...
# Whatever you want to do with your plots
...
plot_count += 1
except:
plot_count +=1
plt.show()
https://stackoverflow.com/questions/43025705
复制相似问题