在定义ax1=fig1.add_subplot(111)并绘制 8 个数据系列及其关联label值后,我使用以下代码行添加图例。
ax1.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
Run Code Online (Sandbox Code Playgroud)
我以前曾多次使用过此方法,没有出现任何问题,但这次它会产生错误: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
Run Code Online (Sandbox Code Playgroud)
我不知道为什么会发生这种情况,并且非常感谢建议。
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))
Run Code Online (Sandbox Code Playgroud)
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))
Run Code Online (Sandbox Code Playgroud)
此代码提供与问题中相同的回溯。错误数组为空会导致错误栏的句柄错误。
@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))
Run Code Online (Sandbox Code Playgroud)
它有效,但图例出现时没有错误栏线。
因此,应该检查提供给 matplotlib errorbar 函数的数据。