将错误栏添加到图例的 Line2D 元素中的标记

Ste*_*fan 5 python matplotlib

我想通过以下方式生成一个单独的图例(例如,对于共享相似元素的几个子图)

import matplotlib as mpl
import matplotlib.pyplot as plt

plt.legend(handles=[
                mpl.lines.Line2D([0], [0],linestyle='-' ,marker='.',markersize=10,label='example')
            ]
           ,loc='upper left'
           ,bbox_to_anchor=(1, 1)
          )
Run Code Online (Sandbox Code Playgroud)

但我不知道如何添加误差线。那么,如何生成带有标记和误差线的独立图例?

为清楚起见,图例应如下例所示,即带有标记 + 错误栏的线条。

import numpy as np
import matplotlib.pyplot as plt

x=np.linspace(0,5,5)
y=x

yerr=np.random.rand(5,1)*5e-1
fig,ax=plt.subplots(nrows=1,ncols=1)
ax.errorbar(x=x,y=y,yerr=yerr,marker='.',ms=10,label='example')

ax.legend(loc='upper left'
          ,bbox_to_anchor=(1, 1)
         )
Run Code Online (Sandbox Code Playgroud)

编辑: 一种可能的解决方法是从对象中提取标签和句柄ax,即通过

import numpy as np
import matplotlib.pyplot as plt

x=np.linspace(0,5,5)
y=x

yerr=np.random.rand(5,1)*5e-1
fig,ax=plt.subplots(nrows=1,ncols=1, constrained_layout=True)
ax.errorbar(x=x,y=y,yerr=yerr,marker='.',ms=10,label='example',legend=None)

handles,labels=ax.get_legend_handles_labels()
fig.legend(handles=handles,labels=labels
           ,loc='upper right'
          )
Run Code Online (Sandbox Code Playgroud)

Imp*_*est 3

为什么不采用(其中一个)现有错误栏并将其用作图例句柄?

import numpy as np
import matplotlib.pyplot as plt

x=np.linspace(0,5,5)
y=x

yerr=np.random.rand(5,1)*5e-1
fig,ax=plt.subplots(nrows=1,ncols=1)
err = ax.errorbar(x=x,y=y,yerr=yerr,marker='.',ms=10, label='example')

ax.legend(handles=[err], labels=["my custom label"], 
          loc='upper left' ,bbox_to_anchor=(1, 1)  )

plt.show()
Run Code Online (Sandbox Code Playgroud)

相反,如果您坚持从头开始创建错误栏图例句柄,则结果将如下所示。

import numpy as np
import matplotlib.pyplot as plt

x=np.linspace(0,5,5)
y=x

yerr=np.random.rand(5,1)*5e-1
fig,ax=plt.subplots(nrows=1,ncols=1)
ax.errorbar(x=x,y=y,yerr=yerr,marker='.',ms=10, label='example')


from matplotlib.container import ErrorbarContainer
from matplotlib.lines import Line2D
from matplotlib.collections import LineCollection
line = Line2D([],[], ls="none")
barline = LineCollection(np.empty((2,2,2)))
err = ErrorbarContainer((line, [line], [barline]), has_xerr=True, has_yerr=True)

ax.legend(handles=[err], labels=["my custom label"], 
          loc='upper left' ,bbox_to_anchor=(1, 1)  )

plt.show()
Run Code Online (Sandbox Code Playgroud)