问题
I currently have a matplotlib figure with 16 subplots, 4 columns and 4 rows. I have the following code produced that loops through each subplot and plots different data on each of the 16 subplots:
fac_list = [one, two, three, four, five, six, seven, eight, nine, ten , eleven, twelve,
thirteen, fourteen, fifteen, sixteen]
color = ['blue','red']
ds_i = 0
for row in range(0,subplot_shape[0]):
for col in range(0,subplot_shape[1]):
fac = fac_list[ds_i]
plot('total',
currentname=fac,
subplot_index=(row,col),
linestyle='-',
marker='.',
label='NEW',
color=color[0])
leg2 = axes[row][col].legend(loc='upper left',bbox_to_anchor=(-0.10, 1.04), prop={'size':8},
frameon=False, markerscale=0, handlelength=0)
for line, text in zip(leg2.get_lines(), leg2.get_texts()):
text.set_color(line.get_color())
#axes[row][col].text(1.1,new_obj['total'].values[-1],new_obj['total'].values[-1],horizontalalignment='center',fontsize=5, rotation=45,
#transform=axes[row][col].transAxes, color=color[0])
ds_i += 1
Currently, I've got it so the commented out lines show the final y-axis value of only the last item in fac_list (sixteen), but this value shows up on every subplot in my figure, not just the last subplot (which is the subplot it should be showing up under). How do I loop through the subplots correctly so that the final y-axis value for each item in fac_list shows up in each corresponding subplot (one in fac_list shows up on subplot (0,0), two in fac_list shows up on subplot (0,1), etc.)? Nothing I've tried has worked so far.
回答1:
Uncomment the line and bring it at the same indentation level as the for loop for the column
for row in range(0,subplot_shape[0]):
for col in range(0,subplot_shape[1]):
...
...
for line, text in zip(leg2.get_lines(), leg2.get_texts()):
text.set_color(line.get_color())
# Place the following line as it is in this answer
axes[row][col].text(1.1,new_obj['total'].values[-1],new_obj['total'].values[-1],
horizontalalignment='center',fontsize=5, rotation=45,
transform=axes[row][col].transAxes, color=color[0])
来源:https://stackoverflow.com/questions/58599034/how-do-i-properly-loop-through-the-subplots-of-a-matplotlib-figure-to-show-the-f