Matplotlib:Don';t在图例中显示错误条

Matplotlib:Don';t在图例中显示错误条,matplotlib,Matplotlib,我正在绘制一系列带有x和y错误的数据点,但不希望在图例中包含错误条(仅标记)。有没有办法做到这一点 例如: import matplotlib.pyplot as plt import numpy as np subs=['one','two','three'] x=[1,2,3] y=[1,2,3] yerr=[2,3,1] xerr=[0.5,1,1] fig,(ax1)=plt.subplots(1,1) for i in np.arange(len(x)): ax1.error

我正在绘制一系列带有x和y错误的数据点,但不希望在图例中包含错误条(仅标记)。有没有办法做到这一点

例如:

import matplotlib.pyplot as plt
import numpy as np
subs=['one','two','three']
x=[1,2,3]
y=[1,2,3]
yerr=[2,3,1]
xerr=[0.5,1,1]
fig,(ax1)=plt.subplots(1,1)
for i in np.arange(len(x)):
    ax1.errorbar(x[i],y[i],yerr=yerr[i],xerr=xerr[i],label=subs[i],ecolor='black',marker='o',ls='')
ax1.legend(loc='upper left', numpoints=1)
fig.savefig('test.pdf', bbox_inches=0)
这是一个丑陋的补丁:

pp = []
colors = ['r', 'b', 'g']
for i, (y, yerr) in enumerate(zip(ys, yerrs)):
    p = plt.plot(x, y, '-', color='%s' % colors[i])
    pp.append(p[0])
    plt.errorbar(x, y, yerr, color='%s' % colors[i])  
plt.legend(pp, labels, numpoints=1)
以下是一个示例图:


您可以修改图例处理程序。看。 根据您的示例,这可以是:

import matplotlib.pyplot as plt
import numpy as np

subs=['one','two','three']
x=[1,2,3]
y=[1,2,3]
yerr=[2,3,1]
xerr=[0.5,1,1]
fig,(ax1)=plt.subplots(1,1)

for i in np.arange(len(x)):
    ax1.errorbar(x[i],y[i],yerr=yerr[i],xerr=xerr[i],label=subs[i],ecolor='black',marker='o',ls='')

# get handles
handles, labels = ax1.get_legend_handles_labels()
# remove the errorbars
handles = [h[0] for h in handles]
# use them in the legend
ax1.legend(handles, labels, loc='upper left',numpoints=1)


plt.show()
这就产生了


如果我将label参数设置为None类型,我就可以使用它

plt.errorbar(x, y, yerr, label=None)

公认的解决方案适用于简单情况,但不适用于一般情况。特别是,在我自己更复杂的情况下,它没有起作用

我找到了一个更健壮的解决方案,它测试
ErrorbarContainer
,对我来说确实有效。它是由提出的,为了完整起见,我将其复制到这里

import matplotlib.pyplot as plt
from matplotlib import container

label = ['one', 'two', 'three']
color = ['red', 'blue', 'green']
x = [1, 2, 3]
y = [1, 2, 3]
yerr = [2, 3, 1]
xerr = [0.5, 1, 1]

fig, (ax1) = plt.subplots(1, 1)

for i in range(len(x)):
    ax1.errorbar(x[i], y[i], yerr=yerr[i], xerr=xerr[i], label=label[i], color=color[i], ecolor='black', marker='o', ls='')

handles, labels = ax1.get_legend_handles_labels()
handles = [h[0] if isinstance(h, container.ErrorbarContainer) else h for h in handles]

ax1.legend(handles, labels)

plt.show()
它生成以下绘图(在Matplotlib 3.1上)


一种方法是使用
plot
分别绘制点,并在图例中使用。谢谢。这很有效,似乎是最简单的解决方案。找不到任何选项来切换此行为。我想,否则,在将句柄传递给图例之前,必须先更改句柄,这似乎比连续调用errobar/plot更难。如果您认为这是一个有用的功能,我建议您在github上开始一个问题。这根本不会生成图例。一个最简单的工作示例和结果将有助于澄清您的意思。