matplotlib图例中缺少标签

matplotlib图例中缺少标签,matplotlib,Matplotlib,我正在用matplotlib绘制子图,一些图中没有显示图例。 在本例中,散点图图例不显示 import numpy as np import matplotlib from matplotlib import pyplot as plt from matplotlib.legend_handler import HandlerLine2D from matplotlib.patches import Rectangle, Circle fig = plt.figure() plt.cla()

我正在用matplotlib绘制子图,一些图中没有显示图例。 在本例中,散点图图例不显示

import numpy as np
import matplotlib
from matplotlib import pyplot as plt
from matplotlib.legend_handler import HandlerLine2D
from matplotlib.patches import Rectangle, Circle

fig = plt.figure()
plt.cla()
plt.clf()

x = np.arange(5) + 1
y = np.full(5, 10)
fig, subplots = plt.subplots(2, sharex=False, sharey=False)
subplots[0].bar(x, y, color='r', alpha=0.5, label='a')
scat = subplots[0].scatter(x, y-1, color='g', label='c')
subplots[0].set_yscale('log')

subplots[1].bar(x, y, color='r', alpha=0.5, label='a')
x = [2, 3]
y = [4, 4]
subplots[1].bar(x, y, color='b', alpha=1, label='b')
subplots[1].set_yscale('log')

plt.legend(loc='center left', bbox_to_anchor=(1, 0.5), handler_map={scat: HandlerLine2D(numpoints=4)})

plt.show()
以下是我尝试的解决方法:

p1 = Rectangle((0, 0), 1, 1, fc="r", alpha=0.5)
p2 = Rectangle((0, 0), 1, 1, fc="b")
p3 = Circle((0, 0), 1, fc="g")
legend([p1, p2, p3], ['a', 'b', 'c'], loc='center left', bbox_to_anchor=(1, 0.5))
我真的更喜欢在没有解决方法的情况下解决这个问题,所以如果有人知道如何解决它,请让我知道。
此外,解决方法的一个问题是,圆形对象仍在图例上显示为条形。

plt。图例以
gca()
开头(返回当前轴):

因此,调用
plt.legend
只会为您的最后一个子批次获取一个图例。但是也可以调用例如
ax.legend()
,或者在您的情况下调用
子批[0].legend()
。将其添加到代码的末尾,可以为这两个子批次提供一个图例

样本:

for subplot in subplots:
    subplot.legend(loc='center left', bbox_to_anchor=(1, 0.5))

伟大的谢谢,我在你的答案中添加了一个示例代码。
for subplot in subplots:
    subplot.legend(loc='center left', bbox_to_anchor=(1, 0.5))