Ask Your Question
1

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

asked 2016-11-27 17:24:15 +0100

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?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2016-11-27 19:21:04 +0100

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.

edit flag offensive delete link more

Comments

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

kcrisman gravatar imagekcrisman ( 2016-11-28 02:21:38 +0100 )edit
kcrisman gravatar imagekcrisman ( 2022-03-24 15:22:19 +0100 )edit

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: 2016-11-27 17:24:15 +0100

Seen: 3,912 times

Last updated: Nov 27 '16