diff --git a/lib/matplotlib/legend_handler.py b/lib/matplotlib/legend_handler.py index b94fc679ce16..0d66105af55e 100644 --- a/lib/matplotlib/legend_handler.py +++ b/lib/matplotlib/legend_handler.py @@ -35,7 +35,9 @@ def legend_artist(self, legend, orig_handle, fontsize, handlebox) def update_from_first_child(tgt, src): - tgt.update_from(src.get_children()[0]) + first_child = next(iter(src.get_children()), None) + if first_child is not None: + tgt.update_from(first_child) class HandlerBase(object): diff --git a/lib/matplotlib/tests/test_legend.py b/lib/matplotlib/tests/test_legend.py index b4bcecde81fa..beaa312ff4fe 100644 --- a/lib/matplotlib/tests/test_legend.py +++ b/lib/matplotlib/tests/test_legend.py @@ -477,6 +477,14 @@ def test_handler_numpoints(): ax.legend(numpoints=0.5) +def test_empty_bar_chart_with_legend(): + """Test legend when bar chart is empty with a label.""" + # related to issue #13003. Calling plt.legend() should not + # raise an IndexError. + plt.bar([], [], label='test') + plt.legend() + + def test_shadow_framealpha(): # Test if framealpha is activated when shadow is True # and framealpha is not explicitly passed'''