简体   繁体   中英

Python variable names through a for loop

In Matplotlib, I set an axis label using: axes1.set_ylabel('....')

If I have three axes, is there a way to use a loop to do the following?:

for i in range(3):
    axes[i].set_ylabel('AVG')

Of course, this is not correct syntax as I'm not using a list/dictionary. However, does anyone have any recommendations?

Here's what I use for multiple vertical-only axes:

f, axes = plt.subplots(nrows=3, ncols=1, figsize=(12,5))
try:
    iter(axes)       # Check if axes can be iterated over
except TypeError:
    axes = [axes]    # If not, then make it into a list

for ax in axes:
    ax.plot(x, y)
    ax.set_ylabel('AVG')

Usually I even change the figure size depending on how many rows I have. Doing this gets a little complicated if you have ncols > 1 . Therefore this is for vertical-only plots.

Put your axes in a list:

my_axes = []
for n in range(1, 4):
    my_axes.append(fig.add_subplot(1, 3, n))
for ax in my_axes:
     ax.set_ylabel('AVG')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM