Ask Your Question
1

How to put legend outside of the graph at its bottom?

asked 8 years ago

Eugene gravatar image

Hello!

I would like to have legend located outside of the of the graph at the bottom. In the matplotlib legend guide there is an example how to locate it on the top:

# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
           ncol=2, mode="expand", borderaxespad=0.)

Base on that example I write in Sage Note the following code:

p = line([(0, 0), (1, 1)], legend_label='test', axes_labels=('X LABEL', 'Y LABEL'))
p.set_legend_options(bbox_to_anchor=(0., -.14, 1., .102), loc=3, mode="expand", borderaxespad=0.)
p.show(frame=True, axes=False)

bbox_to_anchor parameter is (left, bottom, width, height) , the issue is that I have to manually set bottom (-.14 in the example) to compensate for the X label (it may be present, may be missing, may have a bigger font etc.)

Is there a way to automatically put legend on the bottom just below the x-axes label?

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
1

answered 8 years ago

The keywords for graphics usually end up in a dictionary called _extra_kwds. You can check to see if axes_labels and the x-axis label are given in that dictionary, and adjust your vertical displacement accordingly:

p = line([(0, 0), (1, 1)], legend_label='test', axes_labels=('X LABEL', 'Y LABEL'))

labels = p._extra_kwds.get('axes_labels')
if labels and labels[0]:
    displace = -.14 - .005 * p.fontsize()
else:
    displace = -.14

p.set_legend_options(bbox_to_anchor=(0., displace, 1., .102), loc=3, mode="expand", borderaxespad=0.)
p.show(frame=True, axes=False)

Here' a live example.

Preview: (hide)
link

Comments

Nice! Can you open a ticket to put an example like this in the Sage documentation?

kcrisman gravatar imagekcrisman ( 8 years ago )
kcrisman gravatar imagekcrisman ( 3 years ago )

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 8 years ago

Seen: 4,176 times

Last updated: Nov 27 '16