|
469 | 469 | ax = axs[1] |
470 | 470 | ax.legend(hs2, loc="b", ncols=3, center=True, title="centered rows") |
471 | 471 | axs.format(xlabel="xlabel", ylabel="ylabel", suptitle="Legend formatting demo") |
| 472 | +# %% [raw] raw_mimetype="text/restructuredtext" |
| 473 | +# .. _ug_guides_decouple: |
| 474 | +# |
| 475 | +# Decoupling legend content and location |
| 476 | +# -------------------------------------- |
| 477 | +# |
| 478 | +# Sometimes you may want to generate a legend using handles from specific axes |
| 479 | +# but place it relative to other axes. In UltraPlot, you can achieve this by passing |
| 480 | +# both the `ax` and `ref` keywords to :func:`~ultraplot.figure.Figure.legend` |
| 481 | +# (or :func:`~ultraplot.figure.Figure.colorbar`). The `ax` keyword specifies the |
| 482 | +# axes used to generate the legend handles, while the `ref` keyword specifies the |
| 483 | +# reference axes used to determine the legend location. |
| 484 | +# |
| 485 | +# For example, to draw a legend based on the handles in the second row of subplots |
| 486 | +# but place it below the first row of subplots, you can use |
| 487 | +# ``fig.legend(ax=axs[1, :], ref=axs[0, :], loc='bottom')``. If ``ref`` is a list |
| 488 | +# of axes, UltraPlot intelligently infers the span (width or height) and anchors |
| 489 | +# the legend to the appropriate outer edge (e.g., the bottom-most axis for ``loc='bottom'`` |
| 490 | +# or the right-most axis for ``loc='right'``). |
| 491 | + |
| 492 | +# %% |
| 493 | +import numpy as np |
| 494 | + |
| 495 | +import ultraplot as uplt |
| 496 | + |
| 497 | +fig, axs = uplt.subplots(nrows=2, ncols=2, refwidth=2, share=False) |
| 498 | +axs.format(abc="A.", suptitle="Decoupled legend location demo") |
| 499 | + |
| 500 | +# Plot data on all axes |
| 501 | +state = np.random.RandomState(51423) |
| 502 | +data = (state.rand(20, 4) - 0.5).cumsum(axis=0) |
| 503 | +for ax in axs: |
| 504 | + ax.plot(data, cycle="mplotcolors", labels=list("abcd")) |
| 505 | + |
| 506 | +# Legend 1: Content from Row 2 (ax=axs[1, :]), Location below Row 1 (ref=axs[0, :]) |
| 507 | +# This places a legend describing the bottom row data underneath the top row. |
| 508 | +fig.legend(ax=axs[1, :], ref=axs[0, :], loc="bottom", title="Data from Row 2") |
| 509 | + |
| 510 | +# Legend 2: Content from Row 1 (ax=axs[0, :]), Location below Row 2 (ref=axs[1, :]) |
| 511 | +# This places a legend describing the top row data underneath the bottom row. |
| 512 | +fig.legend(ax=axs[0, :], ref=axs[1, :], loc="bottom", title="Data from Row 1") |
0 commit comments