Adam Cook
Adam Cook

Reputation: 31

for loop in range efficiency

doing an online python course and playing around with matplotlib object oriented plots.

have the code

fig,axes = plt.subplots(1,4)

which gives you an array of axes so you can iterate through your plots.

I've played around with this to try and iterate through and make many plots and assign titles, etc to all of them.

the code I made is here:

numplots = 4
fig,axes = plt.subplots(1,numplots)

titles = "title_1 title_2 title3 title4".split()
xlabels = "x1 x2 x3 x4".split()
ylabels = "ya y2 y3 y4".split()


for i in range(numplots):
    axes[i].plot(x,y)
    axes[i].set_title(titles[i])
    axes[i].set_xlabel(xlabels[i])
    axes[i].set_ylabel(ylabels[i])
    
plt.tight_layout()

which produces the desired output. My question is:

Is "For i in range(n)" the best way to do this? I've found I create these kind of for loops due to my familiarity with matlab, but heard in python it's generally better practice to do something like:

for current_axis in axes:

but I don't understand how i could then index the titles,xlables,ylabels etc.

Any help/ direction to relevant materials comparing the two for loop methods would be great, thanks!

Note* whilst this is in the context of matplotlib, and info on how to achieve these plots in a better way would be welcome, it's more generally a question about the efficiency of this for loop.

Upvotes: 0

Views: 80

Answers (1)

xqt
xqt

Reputation: 333

You don't need this for the axis but for the other sequences. Instead of

for i in range(numplots):
    axes[i].plot(x,y)
    axes[i].set_title(titles[i])
    axes[i].set_xlabel(xlabels[i])
    axes[i].set_ylabel(ylabels[i])

you can do:

for i, current_axis in enumerate(axes):
    current_axis.plot(x,y)
    current_axis.set_title(titles[i])
    current_axis.set_xlabel(xlabels[i])
    current_axis.set_ylabel(ylabels[i])

Upvotes: 1

Related Questions