从图例获取matplotlib误差条颜色
有没有什么代码可以和这个一样
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.get+
这是我看到的结果:
我尝试了很多方法,但都没有成功
谢谢你。
1 个回答
0
编辑:感谢邮件列表上的朋友们,添加了正确的解决方案。
变通方法
到目前为止,我找到的最佳解决方案大概是这样的:
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()
这其实是重新绘制数据。当然,你在图例中不会得到相同的标记;在我的情况下这不是问题(我通过给标签上色来替代它们),但你的情况可能会有所不同。
正确的方法
Scott Lasley 提到,正确的方法是操作 plt.legend().legendHandles
,这是 Tom Caswell 在回答原问题时指出的。不过这里有两个小细节,第一个是我们处理的是 LineCollection
而不是 Line2D
,正如 Paul Hobson 所提到的(这样返回的是数组),第二个是颜色以 RGBA 数组的形式返回,而不是 HEX 值,这可能根据你的使用情况很重要。因此,要想在使用 plt.errorbar()
时得到与 plt.plot()
一样的输出,你需要这样做:
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]]
如果你不在乎颜色格式,可以去掉 to_hex
的导入,直接使用。