It is certainly useful at times to break your legend up into multiple
parts, but doing so in python (matplotlib) can be a pain in the neck.
Luckily there’s a quick and fairly simple solution!
First thing you need to do, is actually name your plotted lines like
so:
fig=figure()
ax1=fig.add_subplot(111)
l1 = ax1.plot(x, y, 'bo', label='ONE')
l2 = ax1.plot(i, j, 'rx', label='TWO')
we now separate these lines and their labels into different variables
legendlines1 = l1
legendlabels1 = [l.get_label() for l in legendlines1]
legendlines2 = l2
legendlabels2 = [l.get_label() for l in legendlines2]
at this point we can’t just plot a legend, then another legend. The
second legend always takes precedence and essentially erases the
first. So in order to get around this, we name the first legend, and
render the second:
legend1 = ax1.legend(legendlines1,legendlabels1,loc=1)
ax1.legend(legendlines2,legendlabels2,loc=3)
if you run the script up until this point, you’ll only have the
second legend showing in location 3. In order to get the second legend
we add the object via gca():
gca().add_artist(legend1)
from pylab import *
from numpy import *
x=linspace(0,5,20)
y=-x
fig=figure()
ax1=fig.add_subplot(111)
l1=ax1.plot(x,y,label='ONE')
l2=ax1.plot(y,x,label='TWO')
legendlines1 = l1
legendlabels1 = [l.get_label() for l in legendlines1]
legendlines2 = l2
legendlabels2 = [l.get_label() for l in legendlines2]
legend1=ax1.legend(legendlines1,legendlabels1,loc=1)
ax1.legend(legendlines2,legendlabels2,loc=3)
gca().add_artist(legend1)
show()