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

Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
VanDavv opened this issue Dec 17, 2018 · 3 comments · Fixed by #13551
Closed

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

VanDavv opened this issue Dec 17, 2018 · 3 comments · Fixed by #13551
Milestone

Comments

@VanDavv
Copy link

VanDavv commented Dec 17, 2018

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
@timhoffm
Copy link
Member

timhoffm commented Dec 17, 2018

Thanks for the report.

Current behavior with bar()

ax = plt.gca()
ax.bar([], [], label='foo')
print(ax.get_legend_handles_labels())
ax.legend()

prints ([<BarContainer object of 0 artists>], ['foo'])

Current behavior with plot() and raises the above error.

ax = plt.gca()
ax.plot([], [], label='foo')
print(ax.get_legend_handles_labels())
ax.legend()

prints ([<matplotlib.lines.Line2D object at 0x7f14fb7c10f0>], ['foo']) and renders an empty plot with a legend.
image

Not sure we can bar() behave similarly.

@choyiny
Copy link
Contributor

choyiny commented Feb 26, 2019

Hi, this is my first time contributing to a large scale open source project, please do pardon my beginner knowledge.

The error originates the function update_from_first_child in legend_handler, which is called by the legend handler of BarContainer defined at legend.py:682

def update_from_first_child(tgt, src):
        tgt.update_from(src.get_children()[0])

In the case where there is no children from the original handler src, it will result in an IndexError. A simple fix like so would fix the issue:

def update_from_first_child(tgt, src):
        try:
            tgt.update_from(src.get_children()[0])
        except IndexError:
            pass

Similarly, we could first check the length of src.get_children() then only update if there is something.

Could anyone please advise if this is the correct approach to this particular issue?

@VanDavv
Copy link
Author

VanDavv commented Feb 26, 2019

@choyiny I'd rather do

def update_from_first_child(tgt, src):
    first_child = next(iter(src.get_children()), None)
    tgt.update_from(first_child)

And handle None value either here or in tgt.update_from method

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants