@cosmosis 答案的不同实现。它可能更灵活。
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(0,100,11)
plt.plot(X,-X, label='plot 1', color='red')
plt.plot(X,-2*X, label='plot 2', color='green')
plt.plot(X,-3*X, label='plot 3', color='blue')
(lines, labels) = plt.gca().get_legend_handles_labels()
#it's safer to use linestyle='none' and marker='none' that setting the color to white
#should be invisible whatever is the background
lines.insert(1, plt.Line2D(X,X, linestyle='none', marker='none'))
labels.insert(1,'')
plt.legend(lines,labels,numpoints=1, loc=4,ncol=1)
plt.show()
另一种选择是在此处创建两个图例,然后在此处使用 bbox_to_anchor 关键字替换它们
(lines, labels) = plt.gca().get_legend_handles_labels()
leg1 = plt.legend(lines[:1], labels[:1], bbox_to_anchor=(0,0,0.8,1), loc=1)
leg2 = plt.legend(lines[1:], labels[1:], bbox_to_anchor=(0,0,1,1), loc=1)
gca().add_artist(leg1)
这样做我不需要在其他对象上添加任何东西。