|
6 | 6 | Instead of plotting a legend on each axis, a legend for all the artists on all
|
7 | 7 | the sub-axes of a figure can be plotted instead. If constrained layout is
|
8 | 8 | used (:doc:`/tutorials/intermediate/constrainedlayout_guide`) then room
|
9 |
| -can be made automatically for the legend by using `~.Figure.legend_outside`. |
| 9 | +can be made automatically for the legend by using `~.Figure.legend` with the |
| 10 | +``outside=True`` kwarg. |
10 | 11 |
|
11 | 12 | """
|
12 | 13 |
|
|
29 | 30 | h4, = axs[1].plot(x, y4, 'k^', label='Line4')
|
30 | 31 |
|
31 | 32 | fig.legend(loc='upper center', outside=True, ncol=2)
|
32 |
| -fig.legend(axs=[axs[1]], outside=True, loc='lower right') |
| 33 | +fig.legend(ax=[axs[1]], outside=True, loc='lower right') |
33 | 34 | fig.legend(handles=[h2, h4], labels=['curve2', 'curve4'],
|
34 | 35 | outside=True, loc='center left', borderaxespad=6)
|
35 | 36 | plt.show()
|
| 37 | + |
| 38 | +############################################################################### |
| 39 | +# The usual codes for the *loc* kwarg are allowed, however, the corner |
| 40 | +# codes have an ambiguity as to whether the legend is stacked |
| 41 | +# horizontally (the default) or vertically. To specify the vertical stacking |
| 42 | +# the *outside* kwarg can be specified with ``"vertical"`` instead of just |
| 43 | +# the booloean *True*: |
| 44 | + |
| 45 | +fig, axs = plt.subplots(1, 2, sharey=True, constrained_layout=True) |
| 46 | +axs[0].plot(x, y1, 'rs-', label='Line1') |
| 47 | +h2, = axs[0].plot(x, y2, 'go', label='Line2') |
| 48 | + |
| 49 | +axs[0].set_ylabel('DATA') |
| 50 | +axs[1].plot(x, y3, 'yd-', label='Line3') |
| 51 | +h4, = axs[1].plot(x, y4, 'k^', label='Line4') |
| 52 | + |
| 53 | +fig.legend(loc='upper right', outside='vertical', ncol=2) |
| 54 | +plt.show() |
| 55 | + |
| 56 | +############################################################################### |
| 57 | +# Significantly more complicated layouts are possible using the gridspec |
| 58 | +# organization of subplots: |
| 59 | + |
| 60 | +fig = plt.figure(constrained_layout=True) |
| 61 | +gs0 = fig.add_gridspec(1, 2) |
| 62 | + |
| 63 | +gs = gs0[0].subgridspec(1, 1) |
| 64 | +for i in range(1): |
| 65 | + ax = fig.add_subplot(gs[i,0]) |
| 66 | + ax.plot(range(10), label=f'Boo{i}') |
| 67 | +lg = fig.legend(ax=[ax], loc='upper left', outside=True, borderaxespad=4) |
| 68 | + |
| 69 | +gs2 = gs0[1].subgridspec(3, 1) |
| 70 | +axx = [] |
| 71 | +for i in range(3): |
| 72 | + ax = fig.add_subplot(gs2[i, 0]) |
| 73 | + ax.plot(range(10), label=f'Who{i}', color=f'C{i+1}') |
| 74 | + if i < 2: |
| 75 | + ax.set_xticklabels('') |
| 76 | + axx += [ax] |
| 77 | +lg2 = fig.legend(ax=axx[:-1], loc='upper right', outside=True, borderaxespad=4) |
| 78 | +plt.show() |
0 commit comments