Matplotlib 中的图例——通过 For 循环绘制子图

Legend in Matplotlib -- Subplotting by a For loop

我是 Python 和 Matplotlib 的新手,对于如何为我使用 FOR 循环创建的每个子图创建图例的任何帮助,我将不胜感激。这是代码和我可以接近标记我的数字的最佳代码。

import matplotlib.pyplot as plt
import numpy as np
n_rows=2
n_cols=2
leg=['A','B','C','D']
fig, axes = plt.subplots(n_rows,n_cols)
for row_num in range(n_rows):
    for col_num in range (n_cols):
    ax = axes[row_num][col_num]
    ax.plot(np.random.rand(20))
    ax.set_title(f'Plot ({row_num+1}, {col_num+1})')
    ax.legend(leg[row_num+col_num])   
fig.suptitle('Main Title')
fig.tight_layout()               
plt.show()

这里是代码的输出: Image with incorrect legends

您正在使用 ax.legend(leg[row_num+col_num]),但 row_num+col_num 不是列表索引的正确表示。

这就是正在发生的事情

row_num | col_num | idx=row_num+col_num |  leg[idx]
    0   |     0   |  0                  |    A
    0   |     1   |  1                  |    B
    1   |     0   |  1                  |    B
    1   |     1   |  2                  |    C

如果您使用 leg[row_num+col_num],您会得到不正确的图例条目。

有很多方法可以解决这个问题。一个简单的是引入一个计数器(下面代码中的变量j),它在每个循环中递增。

import matplotlib.pyplot as plt
import numpy as np
n_rows=2
n_cols=2
leg=['A','B','C','D']
fig, axes = plt.subplots(n_rows,n_cols)
j = 0
for row_num in range(n_rows):
    for col_num in range(n_cols):
        ax = axes[row_num][col_num]
        ax.plot(np.random.rand(20))
        ax.set_title(f'Plot ({row_num+1}, {col_num+1})')
        ax.legend(leg[j]) 
        j += 1
fig.suptitle('Main Title')
fig.tight_layout()               
plt.show()