在图例的Line2D元素中为标记添加误差线

5
我希望能够通过以下方法制作单独的图例(例如,针对共享类似元素的多个子图):
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'
          )

也许可以看看这篇帖子,它可能包含答案:https://dev59.com/1mYq5IYBdhLWcg3wrSWs - Richard
1
通过这个答案,我能够找到一个解决方法,即从其中一个轴中提取句柄和标签,并使用它们创建图例。我将这个解决方法作为编辑添加了进去。然而,仍然希望能够从头开始创建一个图例,以避免与众多的句柄/标签玩耍。 - Stefan
也许 https://topanswers.xyz/tex?q=1004#a1198 对你的 beamer 问题有所帮助。 - samcarter_is_at_topanswers.xyz
1个回答

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

如果您坚持从头开始创建错误线图例句柄,则应按以下方式进行。
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()

这基本上是我使用的解决方法(请参见我的编辑)。但是,如果有几个不同的子图通过循环填充各种跟踪,则可能会变得非常混乱。 - Stefan
目标是在一个图例中获得一个误差条吗?那么您只需要将循环中的一个误差条作为“err”可用。否则我可能无法理解问题。 - ImportanceOfBeingErnest
想象一下,我有几个子图,每个子图都有不同的迹线(有些带误差条,有些不带)。有些子图也可能是不同类型的,例如直方图。因此,某些信息可能是冗余的,不需要在图例中显示。因此,最好从头开始构建图例,而不必担心各种句柄和标签。 - Stefan
好的,我更新了答案。但是这比仅仅将出现在图形中某个误差条的输出分配给变量并在后续使用它要复杂得多。 - ImportanceOfBeingErnest
太好了,谢谢!正是我想要的。如先前所述,有时从头开始创建图例更可取,特别是当图形由多个子图组成时。对于简单的绘图(如我所给出的示例),当然最好的方法是只获取轴的标签和句柄。 - Stefan
嗨@ImportanceOfBeingErnest!我正在做类似的项目,想知道如何添加带有误差条值的文本。谢谢。 - Megan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接