错误栏,但不是线,作为 python matplotlib 图例中的标记符号

errorbar, but not line, as marker symbol in python matplotlib legend

我有一个误差条图,每个数据集只有一个数据点(即一个误差条)。因此,我也想在图例中有一个错误栏符号。 单一个可以达到legend(numpoints=1)。在以下代码中使用它:

    import matplotlib.pyplot as plt

    fig, ax = plt.subplots()

    ax.errorbar(x=[0.3], y=[0.7], xerr=[0.2], marker='+', markersize=10, label='horizontal marker line')
    ax.errorbar(x=[0.7], y=[0.3], yerr=[0.2], marker='+', markersize=10, label='is too long')

    ax.set_xlim([0,1])
    ax.set_ylim([0,1])
    ax.legend(numpoints=1) # I want only one symbol

    plt.show()

导致图例中的这些符号:

如您所见,误差线与水平线混合在一起,当要连接多个误差线时(使用 legend(numpoints=2) 或更高),这很有意义,但在我的情况下看起来很难看。

如何在不丢失错误栏的情况下去掉图例标记中的线条?

这是由于 matplotlib 中的默认设置。在代码的开头,您可以通过使用 rcParams:

更改设置来更改它们
import matplotlib as mpl
import matplotlib.pyplot as plt

mpl.rcParams['legend.handlelength'] = 0
mpl.rcParams['legend.markerscale'] = 0

fig, ax = plt.subplots()

ax.errorbar(x=[0.3], y=[0.7], xerr=[0.2], marker='+', markersize=10, label='horizontal marker')
ax.errorbar(x=[0.7], y=[0.3], yerr=[0.2], marker='+', markersize=10, label='is gone')

ax.set_xlim([0,1])
ax.set_ylim([0,1])
ax.legend(numpoints=1) 
plt.show()

注意:这会更改将在代码中绘制的所有图表的设置。