Reputation: 201
I wrote a code to automatically plot multiple grid subplots based on number of cells available, I did the following:
cell=10
ax = {}
from matplotlib import pyplot as plt
fig = plt.figure(figsize=(10, 4))
for subgrd in range(cell):
if subgrd < cell / 2:
for subgrd2 in range(int(cell / 2)):
key = 'ax' + str(subgrd)
value = plt.subplot2grid((2, int(cell / 2)), (0, subgrd2))
ax[key] = value
else:
for subgrd2 in range(int(cell / 2)):
key = 'ax' + str(subgrd)
value = plt.subplot2grid((2, int(cell / 2)), (1, subgrd2))
ax[key] = value
print("count ax",len(ax))
for axval in range(len(ax)):
print(str(axval))
ax['ax'+str(axval)].plot([[1,2],[4,3]])
ax['ax'+str(axval)].axes.xaxis.set_visible(False)
ax['ax'+str(axval)].axes.yaxis.set_visible(False)
plt.show()
Somehow the above code is only showing the data on two plots, don't know why?
Upvotes: 0
Views: 265
Reputation: 56610
Your nested for loop is replacing the contents of the ax
dictionary from earlier columns. Get rid of the nested loop, and calculate the row and column based on subgrd
. That way, you only assign each key once.
cell=10
ax = {}
from matplotlib import pyplot as plt
fig = plt.figure(figsize=(10, 4))
row_count = 2
column_count = (cell+row_count-1) // row_count
for subgrd in range(cell):
row = subgrd // column_count
column = subgrd % column_count
key = 'ax' + str(subgrd)
value = plt.subplot2grid((row_count, column_count), (row, column))
ax[key] = value
print("count ax",len(ax))
for axval in range(len(ax)):
print(str(axval))
ax['ax'+str(axval)].plot([[1,2],[4,3]])
ax['ax'+str(axval)].axes.xaxis.set_visible(False)
ax['ax'+str(axval)].axes.yaxis.set_visible(False)
plt.show()
Upvotes: 1