带有错误栏图的Matplotlib中的图例文本颜色

时间:2018-05-03 19:28:09

标签: python matplotlib

我正在尝试将图例中的文字与图中线条的颜色相匹配。 Dan在这里有一个很好的总结如何做到这一点:Matplotlib: Color-coded text in legend instead of a line

但是,它似乎不适用于错误栏图类型。有没有人知道我应该用什么句柄来做这个改变?

下面是一些示例代码,说明它如何与plot类型元素一起使用,但不能与errorbar类型元素一起使用:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0.1,4,0.5)
y1 = np.exp(-x)
y2 = np.exp(-x)*1.2+0.25

plot = plt.figure()
ax = plot.add_axes([0,0,1,1])

ax.plot(x,y1,color="red",label="Y1")
ax.errorbar(x,y2,yerr=0.1,color="blue",marker='*',capsize=4,label="Y2")

leg = ax.legend();

for line, text in zip(leg.get_lines(), leg.get_texts()):
       text.set_color(line.get_color())

以下是该情节的示例:

Code will change text color of plot types but not errorbar types

感谢您的任何建议!

1 个答案:

答案 0 :(得分:1)

System.Diagnostics.Process方法为您提供图例中的线条。

.get_lines()

错误栏不是[h for h in self.legendHandles if isinstance(h, Line2D)] 。所以原则上你可以反复迭代Line2D。问题是颜色没有很好地指定。它们可能是名称或数组。需要注意这一点,使解决方案变得有点复杂。

leg.legendHandles

enter image description here