Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e044cf5

Browse files
authored
Merge pull request #20792 from dmatos2012/legend-tutorial-to-oo
Change legend guide to object oriented approach
2 parents 9d20dd8 + 7f7aa64 commit e044cf5

File tree

1 file changed

+52
-41
lines changed

1 file changed

+52
-41
lines changed

tutorials/intermediate/legend_guide.py

Lines changed: 52 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -53,16 +53,18 @@
5353
For full control of what is being added to the legend, it is common to pass
5454
the appropriate handles directly to :func:`legend`::
5555
56-
line_up, = plt.plot([1, 2, 3], label='Line 2')
57-
line_down, = plt.plot([3, 2, 1], label='Line 1')
58-
plt.legend(handles=[line_up, line_down])
56+
fig, ax = plt.subplots()
57+
line_up, = ax.plot([1, 2, 3], label='Line 2')
58+
line_down, = ax.plot([3, 2, 1], label='Line 1')
59+
ax.legend(handles=[line_up, line_down])
5960
6061
In some cases, it is not possible to set the label of the handle, so it is
6162
possible to pass through the list of labels to :func:`legend`::
6263
63-
line_up, = plt.plot([1, 2, 3], label='Line 2')
64-
line_down, = plt.plot([3, 2, 1], label='Line 1')
65-
plt.legend([line_up, line_down], ['Line Up', 'Line Down'])
64+
fig, ax = plt.subplots()
65+
line_up, = ax.plot([1, 2, 3], label='Line 2')
66+
line_down, = ax.plot([3, 2, 1], label='Line 1')
67+
ax.legend([line_up, line_down], ['Line Up', 'Line Down'])
6668
6769
6870
.. _proxy_legend_handles:
@@ -81,8 +83,9 @@
8183
import matplotlib.patches as mpatches
8284
import matplotlib.pyplot as plt
8385

86+
fig, ax = plt.subplots()
8487
red_patch = mpatches.Patch(color='red', label='The red data')
85-
plt.legend(handles=[red_patch])
88+
ax.legend(handles=[red_patch])
8689

8790
plt.show()
8891

@@ -92,9 +95,10 @@
9295

9396
import matplotlib.lines as mlines
9497

98+
fig, ax = plt.subplots()
9599
blue_line = mlines.Line2D([], [], color='blue', marker='*',
96100
markersize=15, label='Blue stars')
97-
plt.legend(handles=[blue_line])
101+
ax.legend(handles=[blue_line])
98102

99103
plt.show()
100104

@@ -110,25 +114,25 @@
110114
# figure's top right-hand corner instead of the axes' corner, simply specify
111115
# the corner's location and the coordinate system of that location::
112116
#
113-
# plt.legend(bbox_to_anchor=(1, 1),
114-
# bbox_transform=plt.gcf().transFigure)
117+
# ax.legend(bbox_to_anchor=(1, 1),
118+
# bbox_transform=fig.transFigure)
115119
#
116120
# More examples of custom legend placement:
117121

118-
plt.subplot(211)
119-
plt.plot([1, 2, 3], label="test1")
120-
plt.plot([3, 2, 1], label="test2")
121-
122+
fig, ax_dict = plt.subplot_mosaic([['top', 'top'], ['bottom', 'BLANK']],
123+
empty_sentinel="BLANK")
124+
ax_dict['top'].plot([1, 2, 3], label="test1")
125+
ax_dict['top'].plot([3, 2, 1], label="test2")
122126
# Place a legend above this subplot, expanding itself to
123127
# fully use the given bounding box.
124-
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc='lower left',
125-
ncol=2, mode="expand", borderaxespad=0.)
128+
ax_dict['top'].legend(bbox_to_anchor=(0., 1.02, 1., .102), loc='lower left',
129+
ncol=2, mode="expand", borderaxespad=0.)
126130

127-
plt.subplot(223)
128-
plt.plot([1, 2, 3], label="test1")
129-
plt.plot([3, 2, 1], label="test2")
131+
ax_dict['bottom'].plot([1, 2, 3], label="test1")
132+
ax_dict['bottom'].plot([3, 2, 1], label="test2")
130133
# Place a legend to the right of this smaller subplot.
131-
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)
134+
ax_dict['bottom'].legend(bbox_to_anchor=(1.05, 1),
135+
loc='upper left', borderaxespad=0.)
132136

133137
plt.show()
134138

@@ -144,17 +148,18 @@
144148
# handles on the Axes. To keep old legend instances, we must add them
145149
# manually to the Axes:
146150

147-
line1, = plt.plot([1, 2, 3], label="Line 1", linestyle='--')
148-
line2, = plt.plot([3, 2, 1], label="Line 2", linewidth=4)
151+
fig, ax = plt.subplots()
152+
line1, = ax.plot([1, 2, 3], label="Line 1", linestyle='--')
153+
line2, = ax.plot([3, 2, 1], label="Line 2", linewidth=4)
149154

150155
# Create a legend for the first line.
151-
first_legend = plt.legend(handles=[line1], loc='upper right')
156+
first_legend = ax.legend(handles=[line1], loc='upper right')
152157

153-
# Add the legend manually to the current Axes.
154-
plt.gca().add_artist(first_legend)
158+
# Add the legend manually to the Axes.
159+
ax.add_artist(first_legend)
155160

156161
# Create another legend for the second line.
157-
plt.legend(handles=[line2], loc='lower right')
162+
ax.legend(handles=[line2], loc='lower right')
158163

159164
plt.show()
160165

@@ -188,10 +193,11 @@
188193

189194
from matplotlib.legend_handler import HandlerLine2D
190195

191-
line1, = plt.plot([3, 2, 1], marker='o', label='Line 1')
192-
line2, = plt.plot([1, 2, 3], marker='o', label='Line 2')
196+
fig, ax = plt.subplots()
197+
line1, = ax.plot([3, 2, 1], marker='o', label='Line 1')
198+
line2, = ax.plot([1, 2, 3], marker='o', label='Line 2')
193199

194-
plt.legend(handler_map={line1: HandlerLine2D(numpoints=4)})
200+
ax.legend(handler_map={line1: HandlerLine2D(numpoints=4)})
195201

196202
###############################################################################
197203
# As you can see, "Line 1" now has 4 marker points, where "Line 2" has 2 (the
@@ -208,23 +214,25 @@
208214

209215
z = randn(10)
210216

211-
red_dot, = plt.plot(z, "ro", markersize=15)
217+
fig, ax = plt.subplots()
218+
red_dot, = ax.plot(z, "ro", markersize=15)
212219
# Put a white cross over some of the data.
213-
white_cross, = plt.plot(z[:5], "w+", markeredgewidth=3, markersize=15)
220+
white_cross, = ax.plot(z[:5], "w+", markeredgewidth=3, markersize=15)
214221

215-
plt.legend([red_dot, (red_dot, white_cross)], ["Attr A", "Attr A+B"])
222+
ax.legend([red_dot, (red_dot, white_cross)], ["Attr A", "Attr A+B"])
216223

217224
###############################################################################
218225
# The `.legend_handler.HandlerTuple` class can also be used to
219226
# assign several legend keys to the same entry:
220227

221228
from matplotlib.legend_handler import HandlerLine2D, HandlerTuple
222229

223-
p1, = plt.plot([1, 2.5, 3], 'r-d')
224-
p2, = plt.plot([3, 2, 1], 'k-o')
230+
fig, ax = plt.subplots()
231+
p1, = ax.plot([1, 2.5, 3], 'r-d')
232+
p2, = ax.plot([3, 2, 1], 'k-o')
225233

226-
l = plt.legend([(p1, p2)], ['Two keys'], numpoints=1,
227-
handler_map={tuple: HandlerTuple(ndivide=None)})
234+
l = ax.legend([(p1, p2)], ['Two keys'], numpoints=1,
235+
handler_map={tuple: HandlerTuple(ndivide=None)})
228236

229237
###############################################################################
230238
# Implementing a custom legend handler
@@ -253,9 +261,10 @@ def legend_artist(self, legend, orig_handle, fontsize, handlebox):
253261
handlebox.add_artist(patch)
254262
return patch
255263

264+
fig, ax = plt.subplots()
256265

257-
plt.legend([AnyObject()], ['My first handler'],
258-
handler_map={AnyObject: AnyObjectHandler()})
266+
ax.legend([AnyObject()], ['My first handler'],
267+
handler_map={AnyObject: AnyObjectHandler()})
259268

260269
###############################################################################
261270
# Alternatively, had we wanted to globally accept ``AnyObject`` instances
@@ -286,7 +295,9 @@ def create_artists(self, legend, orig_handle,
286295

287296
c = mpatches.Circle((0.5, 0.5), 0.25, facecolor="green",
288297
edgecolor="red", linewidth=3)
289-
plt.gca().add_patch(c)
290298

291-
plt.legend([c], ["An ellipse, not a rectangle"],
292-
handler_map={mpatches.Circle: HandlerEllipse()})
299+
fig, ax = plt.subplots()
300+
301+
ax.add_patch(c)
302+
ax.legend([c], ["An ellipse, not a rectangle"],
303+
handler_map={mpatches.Circle: HandlerEllipse()})

0 commit comments

Comments
 (0)