|
| 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"
C1D3
span>) |
| 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() |
0 commit comments