Pyplot图例索引错误:元组索引超出范围

时间:2017-04-11 14:07:25

标签: python matplotlib

在定义ax1=fig1.add_subplot(111)并使用关联的label值绘制8个数据系列后,我使用以下代码行添加图例。

ax1.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))

我以前多次使用过这种方法没有问题,但是在这种情况下会产生错误,说IndexError: tuple index out of range

Traceback (most recent call last):
   File "interface_tension_adhesion_plotter.py", line 45, in <module>
      ax1.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
   File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/matplotlib/axes/_axes.py", line 564, in legend
      self.legend_ = mlegend.Legend(self, handles, labels, **kwargs)
   File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/matplotlib/legend.py", line 386, in __init__
      self._init_legend_box(handles, labels, markerfirst)
   File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/matplotlib/legend.py", line 655, in _init_legend_box
      fontsize, handlebox))
   File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/matplotlib/legend_handler.py", line 119, in legend_artist
      fontsize, handlebox.get_transform()) 
   File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/matplotlib/legend_handler.py", line 476, in create_artists
      self.update_prop(coll, barlinecols[0], legend)
IndexError: tuple index out of range

我不知道为什么会这样,我真的很感激建议。

1 个答案:

答案 0 :(得分:3)


1.如果数据完好且数组不为空,则此代码可以正常工作。

fig = plt.gcf()
ax=fig.add_subplot(111)

for i in range(8):
    x = np.arange(10)
    y = i + random.rand(10)
    yerr = .1*y
    l = .1*i
    ax.errorbar(x,y,yerr=yerr,label="adhsion={:02.1f}".format(l))

ax.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))

enter image description here
2.当我将过滤器应用于我的数据并获得空数组时,我遇到了同样的错误。这可以转载如下:

fig = plt.gcf()
ax=fig.add_subplot(111)

for i in range(8):
    x = np.arange(10)
    y = i + random.rand(10)
    yerr = .1*y
    l = .1*i
    if i == 7:
        ind = np.isnan(y)
        y = y[ind]
        x = x[ind]
        yerr = yerr[ind]
    ax.errorbar(x,y,yerr=yerr,label="adhsion={:02.1f}".format(l))

ax.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))


此代码提供与问题中相同的Traceback。错误的空数组会导致错误栏的句柄错误。


@crevell提到的解决方法:

handles, labels = ax.get_legend_handles_labels()
handles = [h[0] for h in handles]
ax.legend(handles, labels,loc='center left', bbox_to_anchor=(1.0, 0.5))


它可以工作,但图例没有错误栏行。

enter image description here

因此,应检查提供给matplotlib错误栏功能的数据。