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

Skip to content

Commit a06ed93

Browse files
choyinyjklymak
authored andcommitted
Fix IndexError for pyplot.legend() when plotting empty bar chart with label (#13551)
* FIX: legend crashes when bar chart is empty with label * add test with generating legend with empty bar chart * remove image_comparison from legend test case
1 parent 325a1c8 commit a06ed93

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

lib/matplotlib/legend_handler.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,9 @@ def legend_artist(self, legend, orig_handle, fontsize, handlebox)
3535

3636

3737
def update_from_first_child(tgt, src):
38-
tgt.update_from(src.get_children()[0])
38+
first_child = next(iter(src.get_children()), None)
39+
if first_child is not None:
40+
tgt.update_from(first_child)
3941

4042

4143
class HandlerBase(object):

lib/matplotlib/tests/test_legend.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,14 @@ def test_handler_numpoints():
477477
ax.legend(numpoints=0.5)
478478

479479

480+
def test_empty_bar_chart_with_legend():
481+
"""Test legend when bar chart is empty with a label."""
482+
# related to issue #13003. Calling plt.legend() should not
483+
# raise an IndexError.
484+
plt.bar([], [], label='test')
485+
plt.legend()
486+
487+
480488
def test_shadow_framealpha():
481489
# Test if framealpha is activated when shadow is True
482490
# and framealpha is not explicitly passed'''

0 commit comments

Comments
 (0)