当我想用 python 绘制子图时如何插入标签和图例

How can I insert label and legend when I want to draw subplot with python

我正在尝试在每个 graf 中编写单独的图例,但它不起作用。谁能给我一些建议吗?

import matplotlib.pyplot as plt
s=range(1,6)
a=[1,2,3,4,5]
b=[1,4,9,16,25]
c=a
d=b
fig = plt.figure()
gs = fig.add_gridspec(2, hspace=0)
axs = gs.subplots(sharex=True, sharey=True)
axs[0].step(s, a,label="Male")
axs[0].step(s, b, label="Female")
axs[1].step(s,c, label="$Age\leq 35$")
axs[1].step(s, d, label="$Age>35$")
#fig.legend(bbox_to_anchor=(1.05, 1.0), loc='upper left')
plt.legend() 

试试这个:

import matplotlib.pyplot as plt
s=range(1,6)
a=[1,2,3,4,5]
b=[1,4,9,16,25]
c=a
d=b
fig = plt.figure()
gs = fig.add_gridspec(2, hspace=0)
axs = gs.subplots(sharex=True, sharey=True)
axs[0].step(s, a,label="Male")
axs[0].step(s, b, label="Female")
axs[1].step(s,c, label="$Age\leq 35$")
axs[1].step(s, d, label="$Age>35$")
axs[0].legend()
axs[1].legend()
#fig.legend(bbox_to_anchor=(1.05, 1.0), loc='upper left')
plt.show()

输出: