Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python matplotlib从图例中获取错误条颜色_Python_Matplotlib_Legend - Fatal编程技术网

Python matplotlib从图例中获取错误条颜色

Python matplotlib从图例中获取错误条颜色,python,matplotlib,legend,Python,Matplotlib,Legend,有没有与此代码相同的内容 plt.plot([1,2,3],[1,2,3],label='22') z = plt.legend() tm = z.get_lines() tm[0].get_color() 但是对于错误条呢 plt.errorbar([1,2,3],[1,2,3],[0.5,0.5,0.5],label='22') z = plt.legend() tm = z.get_ ???? tm[0].get_color() 我没有得到z+ 这就是我所看到的: 我试了很多,

有没有与此代码相同的内容

plt.plot([1,2,3],[1,2,3],label='22')
z  = plt.legend()
tm = z.get_lines()
tm[0].get_color()
但是对于错误条呢

plt.errorbar([1,2,3],[1,2,3],[0.5,0.5,0.5],label='22')
z  = plt.legend()
tm = z.get_ ???? 
tm[0].get_color()
我没有得到z+ 这就是我所看到的:

我试了很多,但都不走运


谢谢。

编辑:感谢邮件列表中的人添加了正确的解决方案

变通方法 到目前为止,我最好的解决方案是:

plt.errorbar([1,2,3],[1,2,3],[0.5,0.5,0.5])
plt.gca().set_prop_cycle(None) # Reset the color cycle to get the same one
plt.plot([1,2,3],[1,2,3],label='22')
z = plt.legend()
tm = z.get_lines()
tm[0].get_color()
这是再次绘制数据。当然,您在图例中没有得到相同的标记;在我的例子中,这不是一个问题(我用给标签上色来代替它们),而是YMMV

正道 Scott Lasley暗示,实现这一点的方法是操纵
plt.legend().legendHandles
,正如Tom Caswell在回答OP时指出的那样。尽管它们是两个微妙之处,第一个是我们在处理
LineCollection
,而不是Paul Hobson指出的
Line2D
(这样我们就可以得到返回中的数组),第二个是颜色作为RGBA数组而不是十六进制值返回,这可能很重要,取决于您的用例。因此,要获得与
plt.plot()
案例中使用
plt.errorbar()
时完全相同的输出,您需要执行以下操作:

import matplotlib.pyplot as plt
from matplotlib.colors import to_hex
plt.errorbar([1,2,3],[1,2,3],[0.5,0.5,0.5])
z = plt.legend()
tm = z.legendHandles
to_hex(tm[0].get_colors()[0]) # tm[0].get_colors() looks like [[r g b a]]

如果你不关心颜色格式,你可以删除
来导入和使用_hex

在许多程序员编辑器中查看
z.legendholds
中的内容,在
ipython
交互式解释器中,你可以编写z.get来列出可能的方法。在许多情况下,您也可以填写并要求提供方法签名和/或帮助字符串,但细节差别更大。如果您不能使用tab,请尝试打印出
dir(X)
,这将为您提供它的所有方法。