Pyplot图例索引错误:元组索引超出范围
问题描述:
在定义了ax1=fig1.add_subplot(111)
并绘制了8个数据系列以及相关的label
值后,我使用以下代码行添加图例。Pyplot图例索引错误:元组索引超出范围
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.如果数据完好无损且数组不为空,则此代码完美工作。
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))
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))
该代码给出了相同的回溯中的问题。 空数组错误导致错误条柄错误。通过@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))
它的工作原理,但传说似乎没有errorbar线。
所以要检查提供给matplotlib errorbar功能的数据。
这似乎与绘制错误条有关。但为了帮助你,你需要提供[mcve]。 – ImportanceOfBeingErnest
确实用误差线绘制:'ax1.errorbar(tensionsarray,meanproportionsarray,yerr = stdproportionsarray,label =“adhsion = {:02.1f}”。format(l))' – crevell
这不是[mcve]。 [编辑]你的问题,如果你想提供更多的信息。 – ImportanceOfBeingErnest