 # aligning multiple legends

I want to have two legends (from different axes) positioned right up
against on another.

Here's a static example, except I want the second legend to be defined
relative to the first (if leg is moved, I want leg2 to move as well). I
can't seem to figure out the proper bbox_to_anchor and bbox_transform
parameters to pass to the second legend() to make this work.

# small example
ax = plt.subplot(1,1,1)
ax2 = ax.twinx()
ax.plot([0,1], label='ax1')
ax2.plot([1,0], 'r--',label='ax2')
bbox_to_anchor=(.85,.85))
bbox_to_anchor=(.85,.85))

Paul Ivanov

Paul Ivanov, on 2010-09-06 18:01, wrote:

I want to have two legends (from different axes) positioned right up
against on another.

Here's a static example, except I want the second legend to be defined
relative to the first (if leg is moved, I want leg2 to move as well). I
can't seem to figure out the proper bbox_to_anchor and bbox_transform
parameters to pass to the second legend() to make this work.

# small example
ax = plt.subplot(1,1,1)
ax2 = ax.twinx()
ax.plot([0,1], label='ax1')
ax2.plot([1,0], 'r--',label='ax2')
bbox_to_anchor=(.85,.85))
bbox_to_anchor=(.85,.85))

I guess I really just want one legend, so I figured out an alternative
solution:

# alternative to having two legends
ax = plt.subplot(1,1,1)
ax2 = ax.twinx()
lines= ax.plot([0,1], label='ax1')
lines2= ax2.plot([4,3], 'r--',label='ax2')
lines.extend(lines2)
labels = [l.get_label() for l in lines]
leg = ax.legend(lines, labels)

Is this a reasonable way of achieving the desired result?

thanks,
Paul

Yes.
You may take a look at the legend guide.

http://matplotlib.sourceforge.net/users/legend_guide.html

For your original question, it is not possible to do that with the
current legend implementation. However, you may put the legend inside
the AnnotationBbox, which enables this. I'm posting the example for
any future reference.

Regards,

-JJ

# small example
ax = plt.subplot(1,1,1)
ax.plot([0,1], label='ax1')

leg = ax.legend()
ax.legend_ = None # remove the legend from the axes.

ax2 = ax.twinx()
ax2.plot([1,0], 'r--',label='ax2')
leg2 = ax2.legend() # create a legend

from matplotlib.offsetbox import AnnotationBbox

leg3 = AnnotationBbox(leg._legend_box, (0, 1),
xybox=(-5, 0),
xycoords=leg2.legendPatch,
boxcoords="offset points",