LordVoldemort
LordVoldemort

Reputation: 33

Why is i not incrementing in for loop?

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.
Code screenshot

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

Answers (3)

Justin Dehorty
Justin Dehorty

Reputation: 1716

I would recommend using enumerate here, as it is considered more Pythonic than indexing.

Below is how you would set both the titles and axes:

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')

Output:

Output

Upvotes: 3

Adhun Thalekkara
Adhun Thalekkara

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

enter image description here

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

Zephyr
Zephyr

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}')

enter image description here

Upvotes: 3

Related Questions