matplotlib iterate subplot axis array through single list

前端 未结 6 1290
醉话见心
醉话见心 2020-12-13 04:08

Is there a simple/clean way to iterate an array of axis returned by subplots like

nrow = ncol = 2
a = []
fig, axs = plt.subplots(nrows=nrow, ncols=ncol)
for         


        
6条回答
  •  情话喂你
    2020-12-13 04:48

    TLDR; axes.flat is the most pythonic way of iterating through axes

    As others have pointed out, the return value of plt.subplots() is a numpy array of Axes objects, thus there are a ton of built-in numpy methods for flattening the array. Of those options axes.flat is the least verbose access method. Furthermore, axes.flatten() returns a copy of the array whereas axes.flat returns an iterator to the array. This means axes.flat will be more efficient in the long run.

    Stealing @Sukjun-Kim's example:

    fig, axes = plt.subplots(2, 3)
    for ax in axes.flat:
        ## do something with instance of 'ax'
    

    sources: axes.flat docs Matplotlib tutorial

提交回复
热议问题