我是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()
以下是代码的输出:带有错误图例的图像
您使用的是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()