I have a list of crops, I need to divide the list into sublists of 48 items and then plot them in a mosaic, I have been doing it manually. How can I do it automatically?
This is the code I use:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np
p1 = listf[:48]
p2 = listf[48:96]
p3 = listf[96:144]
p4 = listf[144:192]
p5 = listf[192:240]
p6 = listf[240:288]
p7 = listf[288:336]
p8 = listf[336:384]
p9 = listf[384:432]
p10 = listf[432:480]
p11 = listf[480:528]
p12 = listf[528:576]
p13 = listf[576:624]
p14 = listf[624:642]
final = [p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13,p14]
for idx, part in enumerate(final):
nc = 8
#fig = plt.figure(figsize=(8, (len(part)/6) * 8), dpi=600)
fig = plt.figure(figsize=(9, 6), dpi=300)
grid = ImageGrid(fig, 111, # similar to subplot(111)
#nrows_ncols=(int((len(part))/2), nc), # creates 12x2 grid of axes
nrows_ncols=(6, nc),
axes_pad=0.2, # pad between axes in inch.
)
for ax, im in zip(grid, part):
# Iterating over the grid returns the Axes.
ax.tick_params(labelbottom= False,labeltop = False, labelleft = False, labelright = False)
ax.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB))
fig.suptitle('Predicted vs Real', fontsize=15 )
CodePudding user response:
my_lists = list(zip(*[iter(my_big_list)]*48))
is a common(ish) pattern to do this without numpy or pandas I think
a more readable version
split_size = 48
my_lists = [my_big_list[i:i split_size] for i in range(0,len(my_big_list),split_size)]
CodePudding user response:
If you need each group to have 48, and are sure that the total is divisible by 48:
final = np.array_split(listf, len(listf)//48)
If you need 14 groups:
final = np.array_split(listf, 14)
If you aren't sure that it's divisible by 48:
listf = [1,3] * 40 * 10
len_list = len(listf)
if len_listH:
x = 48*(len_list//48)
temp_list = listf[x:]
listf = listf[:x]
final = np.array_split(listf, len(listf)//48)
final.append(temp_list)
print([len(x) for x in final])
Output, all 48 except the last set:
[48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 32]