8000 Add example to legend guide · matplotlib/matplotlib@f7be69c · GitHub
[go: up one dir, main page]

Skip to content

Commit f7be69c

Browse files
Matt Elmermatthewelmer
Matt Elmer
authored and
matthewelmer
committed
Add example to legend guide
1 parent 00ec4ec commit f7be69c

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

tutorials/intermediate/legend_guide.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,51 @@
137137

138138
plt.show()
139139

140+
###############################################################################
141+
# If you have multiple plots side-by-side each with a common legend and wish to
142+
# instead have one legend that represents all subplots, you can do this:
143+
144+
import numpy as np
145+
import matplotlib.pyplot as plt
146+
147+
# Make a mosaic of subplots and use the top one for the legend.
148+
fig, axes = plt.subplot_mosaic(
149+
(("legend", "legend", "legend"), # Top row has one column.
150+
("f", "df_deta", "d2f_deta2")), # Bottom row has three columns.
151+
height_ratios=(0.1, 0.9), # Size the dummy plot appropriately.
152+
num="distributions") # I like to name my figures. :)
153+
fig.set_constrained_layout(True)
154+
155+
eta = np.linspace(0, 1)
156+
cap_lambda_vals = np.array([-24, -12, 0, 12, 24])
157+
for cap_lambda in cap_lambda_vals:
158+
# Some data
159+
f = 2 * eta - 2 * eta**3 + eta**4 + cap_lambda * eta / 6 * (1 - eta)**3
160+
df_deta = 2 - 6 * eta**2 + 4 * eta**3 + cap_lambda / \
161+
6 * (1 - 6 * eta + 9 * eta**2 - 4 * eta**3)
162+
d2f_deta2 = -12 * eta + 12 * eta**2 + \
163+
cap_lambda / 6 * (-6 + 18 * eta - 12 * eta**2)
164+
165+
for axis in axes:
166+
# Make the dummy plot blank.
167+
if axis == "legend":
168+
axes[axis].axis("off")
169+
continue
170+
171+
# Plot data
172+
axes["f"].plot(f, eta, label=f"$\Lambda = {cap_lambda}$")
173+
axes["df_deta"].plot(df_deta, eta, label=f"$\Lambda = {cap_lambda}$")
174+
axes["d2f_deta2"].plot(d2f_deta2, eta, label=f"$\Lambda = {cap_lambda}$")
175+
176+
# Add a legend to the dummy plot, using the handles from the plot you want to
177+
# create the legend for.
178+
axes["legend"].legend(
179+
handles=axes["f"].get_legend_handles_labels()[0],
180+
loc="center", ncol=len(cap_lambda_vals),
181+
mode="expand", borderaxespad=0)
182+
183+
plt.show() # Ta-daa! (They look better if you squish em down a bit)
184+
140185
###############################################################################
141186
# Multiple legends on the same Axes
142187
# =================================

0 commit comments

Comments
 (0)
0