Skip to content

Commit fbd5005

Browse files
committed
figure.legend can be called without arguments
1 parent 76f902c commit fbd5005

File tree

5 files changed

+873
-1
lines changed

5 files changed

+873
-1
lines changed

lib/matplotlib/figure.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1073,7 +1073,7 @@ def draw_artist(self, a):
10731073
def get_axes(self):
10741074
return self.axes
10751075

1076-
def legend(self, handles, labels, *args, **kwargs):
1076+
def legend(self, *args, **kwargs):
10771077
"""
10781078
Place a legend in the figure. Labels are a sequence of
10791079
strings, handles is a sequence of
@@ -1083,6 +1083,12 @@ def legend(self, handles, labels, *args, **kwargs):
10831083
10841084
USAGE::
10851085
1086+
To make a legend from existing artists on every axes::
1087+
1088+
legend()
1089+
1090+
To make a legend for a list of lines and labels::
1091+
10861092
legend( (line1, line2, line3),
10871093
('label1', 'label2', 'label3'),
10881094
'upper right')
@@ -1164,6 +1170,25 @@ def legend(self, handles, labels, *args, **kwargs):
11641170
11651171
.. plot:: mpl_examples/pylab_examples/figlegend_demo.py
11661172
"""
1173+
1174+
if len(args) == 0:
1175+
ldict = {}
1176+
for ax in self.axes:
1177+
handles, labels = ax.get_legend_handles_labels()
1178+
ldict = dict(ldict, **dict(zip(labels, handles)))
1179+
1180+
handles, labels = ldict.values(), ldict.keys()
1181+
if len(handles) == 0:
1182+
warnings.warn("No labeled objects found. "
1183+
"Use label='...' kwarg on individual plots.")
1184+
return None
1185+
1186+
elif len(args) == 2:
1187+
handles, labels = args
1188+
1189+
else:
1190+
raise TypeError('Invalid arguments to legend')
1191+
11671192
l = Legend(self, handles, labels, *args, **kwargs)
11681193
self.legends.append(l)
11691194
l._remove_method = lambda h: self.legends.remove(h)
Binary file not shown.

0 commit comments

Comments
 (0)