Skip to content

IndexError thrown by pyplot.legend() when plotting empty bar chart with label #13003

Closed
@VanDavv

Description

@VanDavv

Bug report

Bug summary

When I try to create bar chart with no data, and add a label to this chart, IndexError will be raised when trying to create legend for this plot

Code for reproduction

import matplotlib.pyplot as plt
plt.bar([], [], label='foo')
plt.legend()

Actual outcome

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    plt.legend()
  File "/opt/conda/lib/python3.6/site-packages/matplotlib/pyplot.py", line 3823, in legend
    ret = gca().legend(*args, **kwargs)
  File "/opt/conda/lib/python3.6/site-packages/matplotlib/axes/_axes.py", line 557, in legend
    self.legend_ = mlegend.Legend(self, handles, labels, **kwargs)
  File "/opt/conda/lib/python3.6/site-packages/matplotlib/legend.py", line 699, in __init__
    self._init_legend_box(handles, labels, markerfirst)
  File "/opt/conda/lib/python3.6/site-packages/matplotlib/legend.py", line 954, in _init_legend_box
    fontsize, handlebox))
  File "/opt/conda/lib/python3.6/site-packages/matplotlib/legend_handler.py", line 119, in legend_artist
    fontsize, handlebox.get_transform())
  File "/opt/conda/lib/python3.6/site-packages/matplotlib/legend_handler.py", line 303, in create_artists
    self.update_prop(p, orig_handle, legend)
  File "/opt/conda/lib/python3.6/site-packages/matplotlib/legend_handler.py", line 76, in update_prop
    self._update_prop(legend_handle, orig_handle)
  File "/opt/conda/lib/python3.6/site-packages/matplotlib/legend_handler.py", line 69, in _update_prop
    self._update_prop_func(legend_handle, orig_handle)
  File "/opt/conda/lib/python3.6/site-packages/matplotlib/legend_handler.py", line 42, in update_from_first_child
    tgt.update_from(src.get_children()[0])
IndexError: list index out of range

Expected outcome

Matplotlib version

  • Operating system: Linux 1f8cb2653e0b 4.14.85-1-MANJARO Fix autofmt_xdate() when using in conjunction with twinx() #1 SMP PREEMPT Sat Dec 1 12:18:09 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
  • Matplotlib version: 3.0.2 (installed from PyPi)
  • Matplotlib backend (print(matplotlib.get_backend())): module://backend_interagg
  • Python version: 3.6.7

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions