Reputation: 33
I'm new to programming may I know why my i
is not incrementing in the for loop. I want to update the plot name for each subplot. Thank you.
from matplotlib import pyplot as plt
fig= plt.figure()
fig,axes = plt.subplots(nrows=1, ncols=3,squeeze=False)
fig.tight_layout()
i=0
for current_ax in axes:
current_ax[i].set_title(f"plot: {i}")
i+=1
Upvotes: 2
Views: 247
Reputation: 1716
I would recommend using enumerate
here, as it is considered more Pythonic than indexing.
import matplotlib.pyplot as plt
fig = plt.figure()
fig, axes = plt.subplots(nrows=1, ncols=3, squeeze=False)
fig.tight_layout()
# enumerate titles for each plot (blue boxes in output below)
for i, ax in enumerate(axes.flat):
ax.set_title(f'Title {i}')
# label x and y axis for each plot (red boxes in output below)
plt.setp(axes, xlabel='x axis label')
plt.setp(axes, ylabel='y axis label')
Upvotes: 3
Reputation: 723
This is because your axes array is like shown below
[[<matplotlib.axes._subplots.AxesSubplot object at 0x000001DCA32BB2E0>
<matplotlib.axes._subplots.AxesSubplot object at 0x000001DCA54476A0>
<matplotlib.axes._subplots.AxesSubplot object at 0x000001DCA547D250>]]
so your array have only one plot with three objects in it. while you running your code the loop will only execute once. there is no problem with the counter increment. you can cross check this by printing i
at the end of loop. so to make work this code in your way first pull out the first element from the array which will make the axes array with 3 objects ie 3 plots.
from matplotlib import pyplot as plt
fig= plt.figure()
fig,axes = plt.subplots(nrows=1, ncols=3,squeeze=False)
fig.tight_layout()
i=0
print('figarray1',axes)
axes=axes[0]
print('figarray2',axes)
for current_ax in axes:
current_ax.set_title(f"plot: {i}")
i+=1
print(i)
plt.show()
output graph
Terminal Output
figarray1 [[<matplotlib.axes._subplots.AxesSubplot object at 0x0000020AEB72B2E0>
<matplotlib.axes._subplots.AxesSubplot object at 0x0000020AEF9266A0>
<matplotlib.axes._subplots.AxesSubplot object at 0x0000020AEF95D250>]]
figarray2 [<matplotlib.axes._subplots.AxesSubplot object at 0x0000020AEB72B2E0>
<matplotlib.axes._subplots.AxesSubplot object at 0x0000020AEF9266A0>
<matplotlib.axes._subplots.AxesSubplot object at 0x0000020AEF95D250>]
1
2
3
Upvotes: 3
Reputation: 12496
You do not need to use current_axes[i]
, just current_axes
.
Moreover, you could replace your for loop with this:
for i, current_ax in enumerate(axes, 0):
current_ax.set_title(f'Plot: {i}')
Upvotes: 3