gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:53:37 25 4
gpt4 key购买 nike

我想通过

生成一个单独的图例(例如,对于共享相似元素的几个子图)
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'
)

最佳答案

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

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

关于python - 将错误栏添加到图例的 Line2D 元素中的标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56074771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com