Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add errorbar to marker in Line2D element for legend

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'
          )
like image 594
Stefan Avatar asked Oct 27 '22 15:10

Stefan


1 Answers

Why not take the (one of the) existing errorbar(s) and use it as legend handle?

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()

If instead you persist on creating the errorbar legend handle from scratch, this would look as follows.

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()
like image 50
ImportanceOfBeingErnest Avatar answered Oct 31 '22 10:10

ImportanceOfBeingErnest