Python 首先填充matplotlib图例的右列

Python 首先填充matplotlib图例的右列,python,matplotlib,legend,Python,Matplotlib,Legend,嘿,我正试图把一个传说放在一个情节上,这样它就不会模糊这个图表 import numpy as np import matplotlib.pyplot as plt X = np.linspace(0,100,11) plt.plot(X,-X, label='plot 1') plt.plot(X,-2*X, label='plot 2') plt.plot(X,-3*X, label='plot 3') leg=plt.legend(ncol=2) leg.get_frame().se

嘿,我正试图把一个传说放在一个情节上,这样它就不会模糊这个图表

import numpy as np
import matplotlib.pyplot as plt

X = np.linspace(0,100,11)

plt.plot(X,-X, label='plot 1')
plt.plot(X,-2*X, label='plot 2')
plt.plot(X,-3*X, label='plot 3')

leg=plt.legend(ncol=2)
leg.get_frame().set_visible(False)

plt.show()
因此,在上面的最小工作示例中,我希望能够将图例中的“plot 2”标签移动到右列,即“plot 3”的正下方


任何帮助都将不胜感激。

图例将从左到右填入各列。换句话说,如果你欺骗它相信还有另一行(图例中没有任何文本或线条颜色),那么你可以填充“plot 3”下的空间

import numpy as np
import matplotlib.pyplot as plt
from pylab import *

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')


line1 = Line2D(range(10), range(10), marker='', color="red")
line2 = Line2D(range(10), range(10), marker='',color="green")
line3 = Line2D(range(10), range(10), marker='', color="blue")
line4 = Line2D(range(10), range(10), marker='', color="white")
plt.legend((line1,line4, line3,line2),('plot1','','plot3','plot2'),numpoints=1, loc=4,ncol=2)

plt.show()

@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_锚关键字替换它们


这样做我不需要在其他对象上添加任何内容

第三种方法,基于Franesco的答案。 绘制alpha=0(透明)的占位符线


这与他的回答中描述的优点相同。但是,该解决方案在matplotlib 1.5.1(python3下)中不起作用,它说
ValueError:unrecogned marker style none

不需要重新定义所有行并导入pylab。看我的回答谢谢,你建议的两种方法都有效,如果我想制作更复杂的传奇,那么使用这种策略会更容易。
(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)
#draw your actual lines here
#plt....

lines, labels = plt.gca().get_legend_handles_labels()

lines.insert(1, plt.Line2D([],[], alpha=0))
labels.insert(1,'')

plt.legend(lines,labels,ncol=2)
plt.show()