diff --git a/galleries/examples/text_labels_and_annotations/figlegend_demo.py b/galleries/examples/text_labels_and_annotations/figlegend_demo.py index f6f74b837c10..50b3eeabc085 100644 --- a/galleries/examples/text_labels_and_annotations/figlegend_demo.py +++ b/galleries/examples/text_labels_and_annotations/figlegend_demo.py @@ -3,51 +3,25 @@ Figure legend demo ================== -Instead of plotting a legend on each axis, a legend for all the artists on all -the sub-axes of a figure can be plotted instead. +Rather than plotting a legend on each axis, a legend for all the artists +on all the sub-axes of a figure can be plotted instead. """ import matplotlib.pyplot as plt import numpy as np -fig, axs = plt.subplots(1, 2) - -x = np.arange(0.0, 2.0, 0.02) -y1 = np.sin(2 * np.pi * x) -y2 = np.exp(-x) -l1, = axs[0].plot(x, y1) -l2, = axs[0].plot(x, y2, marker='o') +fig, axs = plt.subplots(1, 2, layout='constrained') -y3 = np.sin(4 * np.pi * x) -y4 = np.exp(-2 * x) -l3, = axs[1].plot(x, y3, color='tab:green') -l4, = axs[1].plot(x, y4, color='tab:red', marker='^') +x = np.arange(0.0, 4*np.pi, 0.2) +axs[0].plot(x, np.sin(x), label='Line 1') +axs[0].plot(x, np.exp(-x/2), marker='o', label='Line 2') +axs[1].plot(x, np.sin(x), color='tab:green', label='Line 3') +axs[1].plot(x, np.exp(-x/4), color='tab:red', marker='^', label='Line 4') -fig.legend((l1, l2), ('Line 1', 'Line 2'), loc='upper left') -fig.legend((l3, l4), ('Line 3', 'Line 4'), loc='upper right') +fig.legend(loc='outside right upper') -plt.tight_layout() plt.show() # %% -# Sometimes we do not want the legend to overlap the Axes. If you use -# *constrained layout* you can specify "outside right upper", and -# *constrained layout* will make room for the legend. - -fig, axs = plt.subplots(1, 2, layout='constrained') - -x = np.arange(0.0, 2.0, 0.02) -y1 = np.sin(2 * np.pi * x) -y2 = np.exp(-x) -l1, = axs[0].plot(x, y1) -l2, = axs[0].plot(x, y2, marker='o') - -y3 = np.sin(4 * np.pi * x) -y4 = np.exp(-2 * x) -l3, = axs[1].plot(x, y3, color='tab:green') -l4, = axs[1].plot(x, y4, color='tab:red', marker='^') - -fig.legend((l1, l2), ('Line 1', 'Line 2'), loc='upper left') -fig.legend((l3, l4), ('Line 3', 'Line 4'), loc='outside right upper') - -plt.show() +# The outside positioning is discussed in detail here: +# https://matplotlib.org/stable/users/explain/axes/legend_guide.html#figure-legends