|
3 | 3 | Figure legend demo
|
4 | 4 | ==================
|
5 | 5 |
|
6 |
| -Instead of plotting a legend on each axis, a legend for all the artists on all |
7 |
| -the sub-axes of a figure can be plotted instead. |
| 6 | +Rather than plotting a legend on each axis, a legend for all the artists |
| 7 | +on all the sub-axes of a figure can be plotted instead. |
8 | 8 | """
|
9 | 9 |
|
10 | 10 | import matplotlib.pyplot as plt
|
11 | 11 | import numpy as np
|
12 | 12 |
|
13 |
| -fig, axs = plt.subplots(1, 2) |
14 |
| - |
15 |
| -x = np.arange(0.0, 2.0, 0.02) |
16 |
| -y1 = np.sin(2 * np.pi * x) |
17 |
| -y2 = np.exp(-x) |
18 |
| -l1, = axs[0].plot(x, y1) |
19 |
| -l2, = axs[0].plot(x, y2, marker='o') |
| 13 | +fig, axs = plt.subplots(1, 2, layout='constrained') |
20 | 14 |
|
21 |
| -y3 = np.sin(4 * np.pi * x) |
22 |
| -y4 = np.exp(-2 * x) |
23 |
| -l3, = axs[1].plot(x, y3, color='tab:green') |
24 |
| -l4, = axs[1].plot(x, y4, color='tab:red', marker='^') |
| 15 | +x = np.arange(0.0, 4*np.pi, 0.2) |
| 16 | +axs[0].plot(x, np.sin(x), label='Line 1') |
| 17 | +axs[0].plot(x, np.exp(-x/2), marker='o', label='Line 2') |
| 18 | +axs[1].plot(x, np.sin(x), color='tab:green', label='Line 3') |
| 19 | +axs[1].plot(x, np.exp(-x/4), color='tab:red', marker='^', label='Line 4') |
25 | 20 |
|
26 |
| -fig.legend((l1, l2), ('Line 1', 'Line 2'), loc='upper left') |
27 |
| -fig.legend((l3, l4), ('Line 3', 'Line 4'), loc='upper right') |
| 21 | +fig.legend(loc='outside right upper') |
28 | 22 |
|
29 |
| -plt.tight_layout() |
30 | 23 | plt.show()
|
31 | 24 |
|
32 | 25 | # %%
|
33 |
| -# Sometimes we do not want the legend to overlap the Axes. If you use |
34 |
| -# *constrained layout* you can specify "outside right upper", and |
35 |
| -# *constrained layout* will make room for the legend. |
36 |
| - |
37 |
| -fig, axs = plt.subplots(1, 2, layout='constrained') |
38 |
| - |
39 |
| -x = np.arange(0.0, 2.0, 0.02) |
40 |
| -y1 = np.sin(2 * np.pi * x) |
41 |
| -y2 = np.exp(-x) |
42 |
| -l1, = axs[0].plot(x, y1) |
43 |
| -l2, = axs[0].plot(x, y2, marker='o') |
44 |
| - |
45 |
| -y3 = np.sin(4 * np.pi * x) |
46 |
| -y4 = np.exp(-2 * x) |
47 |
| -l3, = axs[1].plot(x, y3, color='tab:green') |
48 |
| -l4, = axs[1].plot(x, y4, color='tab:red', marker='^') |
49 |
| - |
50 |
| -fig.legend((l1, l2), ('Line 1', 'Line 2'), loc='upper left') |
51 |
| -fig.legend((l3, l4), ('Line 3', 'Line 4'), loc='outside right upper') |
52 |
| - |
53 |
| -plt.show() |
| 26 | +# The outside positioning is discussed in detail here: |
| 27 | +# https://matplotlib.org/stable/users/explain/axes/legend_guide.html#figure-legends |
0 commit comments