2017-04-11 76 views
2

在定義了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 

我不知道爲什麼會這樣,真的希望建議。

+0

這似乎與繪製錯誤條有關。但爲了幫助你,你需要提供[mcve]。 – ImportanceOfBeingErnest

+1

確實用誤差線繪製:'ax1.errorbar(tensionsarray,meanproportionsarray,yerr = stdproportionsarray,label =「adhsion = {:02.1f}」。format(l))' – crevell

+0

這不是[mcve]。 [編輯]你的問題,如果你想提供更多的信息。 – ImportanceOfBeingErnest

回答

2


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)) 


該代碼給出了相同的回溯中的問題。 空數組錯誤導致錯誤條柄錯誤。通過@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線。

enter image description here

所以要檢查提供給matplotlib errorbar功能的數據。