Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit a97ccbb

Browse filesBrowse files
committed
Move userdemo/simple_legend01 to
texts_albels_and_annotations/legend_outside This also splits the plots in two and adds context documentation.
1 parent 896b78b commit a97ccbb
Copy full SHA for a97ccbb

File tree

2 files changed

+44
-25
lines changed
Filter options

2 files changed

+44
-25
lines changed
+44Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""
2+
==============
3+
Legend outside
4+
==============
5+
6+
.. redirect-from:: /gallery/userdemo/simple_legend01
7+
8+
To move a legend outside the Axes, one can position it manually via the anchor
9+
point ``bbox_to_anchor`` (in Axes coordinates), and then use ``loc`` to determine
10+
where the anchor point is relative to the legend.
11+
12+
In the example, we specify that the upper left edge of the legend (
13+
``loc='upper left'``) is at ``bbox_to_anchor=(1.05, 1)``, i.e. vertically at the
14+
top of the Axes and just a bit outside to the right.
15+
16+
We additionally set ``borderaxespad=0``, so that there is no extra space around the
17+
legend box.
18+
19+
By default, Axes fill the whole figure area, and thus legends placed outside would
20+
be cut of. We therefore use a layout manager to resize everything so that the legend
21+
fits into the figure. Either of the 'constrained' or 'tight' layout managers will
22+
work.
23+
"""
24+
25+
import matplotlib.pyplot as plt
26+
27+
fig, ax = plt.subplots(layout='constrained')
28+
ax.plot([1, 2, 3], label="line 1")
29+
ax.plot([3, 2, 1], label="line 2")
30+
ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0)
31+
plt.show()
32+
33+
###############################################################################
34+
# Similarly, one can place the legend at the top or bottom. In this case, it's
35+
# reasonable to place the entries horizontally, by using as many columns as
36+
# legend entries (here ``ncol=2``). Additionally, ``mode="expand"`` makes sure
37+
# the legend spans the full width of the Axes.
38+
39+
fig, ax = plt.subplots(layout='constrained')
40+
ax.plot([1, 2, 3], label="line 1")
41+
ax.plot([3, 2, 1], label="line 2")
42+
ax.legend(bbox_to_anchor=(0, 1.02, 1, .102), loc='lower left',
43+
ncols=2, mode="expand", borderaxespad=0)
44+
plt.show()

‎galleries/examples/userdemo/simple_legend01.py

Copy file name to clipboardExpand all lines: galleries/examples/userdemo/simple_legend01.py
-25Lines changed: 0 additions & 25 deletions
This file was deleted.

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.