|
59 | 59 | line_down, = ax.plot([3, 2, 1], label='Line 1')
|
60 | 60 | ax.legend(handles=[line_up, line_down])
|
61 | 61 |
|
62 |
| -In the rare case where the labels cannot directly be set on the handles, they |
63 |
| -can also be directly passed to :func:`legend`:: |
| 62 | +Renaming legend entries |
| 63 | +----------------------- |
| 64 | +
|
| 65 | +When the labels cannot directly be set on the handles, they can be directly passed to |
| 66 | +`.Axes.legend`:: |
64 | 67 |
|
65 | 68 | fig, ax = plt.subplots()
|
66 | 69 | line_up, = ax.plot([1, 2, 3], label='Line 2')
|
67 | 70 | line_down, = ax.plot([3, 2, 1], label='Line 1')
|
68 | 71 | ax.legend([line_up, line_down], ['Line Up', 'Line Down'])
|
69 | 72 |
|
70 | 73 |
|
| 74 | +If the handles are not directly accessible, for example when using some |
| 75 | +`Third-party packages <https://matplotlib.org/mpl-third-party/>`_, they can be accessed |
| 76 | +via `.Axes.get_legend_handles_and_labels`. Here we use a dictionary to rename existing |
| 77 | +labels:: |
| 78 | +
|
| 79 | + my_map = {'Line Up':'Up', 'Line Down':'Down'} |
| 80 | +
|
| 81 | + handles, labels = ax.get_legend_handles_labels() |
| 82 | + ax.legend(handles, [my_map[l] for l in labels]) |
| 83 | +
|
| 84 | +
|
71 | 85 | .. _proxy_legend_handles:
|
72 | 86 |
|
73 | 87 | Creating artists specifically for adding to the legend (aka. Proxy artists)
|
|
0 commit comments