I want to produce a separate legend (e.g. for several subplots sharing similar elements) via
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)
)
but I cannot figure out how to add error bars. So, how do I produce a standalone legend with markers and error bars?
For clarity, the legend should look like in the example below, i.e. line with marker + error bar.
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)
)
Edit:
A possible workaround is to extract labels and handles from the ax
object,
i.e. via
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'
)