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

时间:2019-05-10 09:35:18

标签: 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)
          )

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

为清楚起见,图例应类似于以下示例,即带有标记+错误栏的行。

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

编辑: 一种可能的解决方法是从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'
          )

1 个答案:

答案 0 :(得分:1)

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

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

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

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